
    epjN                    -   U d Z 	 ddlZn# e$ r Y nw xY w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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 ddlmZ ddlmZ ddlmZ ddlmZmZmZmZm Z m!Z!m"Z"m#Z#m$Z$ ddl%m&Z&m'Z' dd	l(m)Z)m*Z*m+Z+m,Z,m-Z-m.Z.m/Z/m0Z0 dd
l1m2Z2 ddl3m4Z4 ddl5m6Z6 ddl7m8Z8 ddl9m:Z: dZ;dZ<dZ=dZ>dZ?dZ@dZA ejB        d          ZCdZD ejB        dejE        ejF        z            ZGdeHdeIddfdZJdeHdeHfdZK ejB        dL                    d  e)e/e0e.e-e+e,e*fD                       ejE                  ZMdeNfd!ZO ePh d"          ZQd#e deNfd$ZR ejB        d%ejE                  ZS ejB        d&ejE                  ZT ejB        d'ejE                  ZU ejB        d(ejE                  ZV ejB        d)           ejB        d*           ejB        d+           ejB        d,           ejB        d-           ejB        d.           ejB        d/          fZWdd0ZXd#e deHfd1ZY	 ddd2d3eeeHe f                  d#e deeeHe f                  fd4ZZd5e d6eeeHe f                  deNfd7Z[d8e\deNfd9Z]d:d;d<eeHe f         ddfd=Z^d>eHdeHfd?Z_d@dAdeHfdBZ`dCdCdDdEdFeHdGeHdHeHdIeNdJeNdKeNdeHfdLZad>eHdeHfdMZb ejB        dNejE                  Zcd>eHdeNfdOZdd#e d>eHdeHfdPZed#e dQeHdReHdeeH         fdSZfdeHfdTZgdU ZhdCdVd#e dWe dXe dYeNdeeH         f
dZZid[ejd\eHd]eHdeNfd^ZkdDddd_d[ejd\eHd]eHd`eNd#e daele          dz  deNfdbZmd>eHd#e deHfdcZnddZodZpdee deeI         fdfZqdeIfdgZrdeIfdhZsdieHd`eIdeIfdjZtd5e dkeHdldmdneHddf
doZudddpdee dqeeI         dreeI         deNfdsZv	 ddCdudveeH         dReHdweNdeHfdxZwdyZxeyeHdzf         ezd{<   	 dd|eHd}e d~eeHe f         deNdeeHe f         f
dZ{dZ|dZ}dZ~deeH         deNfdZde deleH         fdZde deleH         fdZde deHfdZde de deNfdZd[eej         deNfdZddDdde!eeHe f                  deeH         deNdeye!eeHe f                  eeH         f         fdZde!eeHe f                  de de!eeHe f                  fdZdRe deeH         de fdZdee!eeHe f                           de fdZh dZddlmZmZmZ dZdZd}e deNfdZd}e de fdZdZ ejB        dejE                  Z	 	 dde!eeHe f                  dedeel         deye!eH         eNf         fdZde!eeHe f                  delfdZddZdeHdeHfdZdeHdeHfdZdeNfdZdefdZdeNfdZddZdej        d<    e             ej                            d eH ee          j        j                             ddlmZmZ ddlmZmZ  e            ZddlmZ ddlmZ edz  Z ee ee                                          j        d         dz             ddZddZdefdZddlmZ ddlmZmZ  G d de          Z G d de          ZeddÄ            ZddńZd#ddddeNfdɄZ ejB        dʦ          ZddhZedz  ZeĠ                                ri	 ddl7mZmZ  eeĦ          Z eeȦ          Z eeej          si Z	 ddlmZ  ej        eȦ          Zn# e$ r Y nw xY weȠ                                D ]1\  ZZ eeeHeeIeNf          reej        vr eHeЦ          ej        e<   2eȠ                    di           ZeҐrw eeej          rj eHeҠ                    dѦ          pej                            dҦ          pdt                                                                          Zi ddғddԓdd֓ddؓddړddܓddޓdddddddddddddddddddddddddddddddddd Ze֠                                D ]\  ZZeev ree         Zedk    r eHeЦ          dv r&edk    rK eeeH          r?ddlmZ  eeeР                                          sej                            eЦ          Z eeeejf          r e	j        eЦ          ej        e<    eHeЦ          ej        e<   eȠ                    di           Zeސr eeej          rh dZ	 ddlmZ  e            D ]Zeߠ                    ed                    n# e$ r Y nw xY weD ]QZeޠ                    ei           Z eeej          s& eHe                    ddt                                                    Z eHe                    ddt                                                    Z eHe                    d	dt                                                    Z eHe                    d
dt                                                    Ze                                Zeredk    reej        de d<   ereej        de d<   ereej        de d<   ereej        de d<   SeȠ                    d5i           Zer eeej          r dev r eHed                   ej        d<   dev r eHed                   ej        d<   dev r eHed                   ej        d<   dev r eHed                   ej        d<   dev r eHed                   ej        d<   dev r eHed                   ej        d<   dev r eHed                   ej        d<   dev r eHed                   ej        d <   eȠ                    d!i           ZerL eeej          r@d"ev r eHed"                   ej        d#<   d$ev r eHed$                   ej        d%<   eȠ                    d&i           Zer eeej          rd'ev r eHed'                   ej        d(<   d)ev r eHed)                   ej        d*<   d+ev r eHed+                   ej        d,<   d-ev r%d.ej        vr eHed-                   ej        d.<   eȠ                    d/dt          Zer) eeeH          re                                ej        d0<   eȠ                    d1i           Z eeej          r>e                    d2          Ze& eHe                                          ej        d3<   eȠ                    d4i           Z eeej          r4e                    d5          Zeerdnd6ej        d7<   e                    d8          ZerR eeeH          reZn6 eeeeyf          r&ej        L                    d9 eD                       ZndtZereej        d:<   e                    d;          Zeerdnd6ej        d<<   e                    d=          Ze eHe          ej        d><   d?ev rIej                            d@dt                                          s eHed?                   ej        d@<   nO# e$ rGZ edA ee          j         dBe ej        C            edDej        C           Y dZ[ndZ[ww xY w	 ddElmZ dF e            v reni                     dGi           Z  eɐe ej          r$e                     dH          r edCI           n/# e$ r'Z edJe ej        C           Y dZ[n
dZ[ww xY w	 ddKl7mZ  e             n/# e$ r'Z edLe ej        C           Y dZ[n
dZ[ww xY w	 ddMl7mZ  e             n/# e$ r'Z edNe ej        C           Y dZ[n
dZ[ww xY wdej        dO<   dej        dP<   ddQlmZmZ ej                            ddt          Zereev r eeej                            ddt           ej        dR           ej        ddS                                          dTv  eH ej	                              U          Z
e
ej                            dd           ne
ej        d<   ddVlmZmZmZmZmZmZmZ ddWlmZmZmZmZmZmZmZmZmZmZmZ ddXlm Z m!Z!m"Z" ddYl#m$Z$ ddZl%m&Z'm(Z(m)Z)m*Z* dd[l+m,Z, dd\l-m.Z. dd]l/m0Z0 dd^l1m2Z2 dd_l3m4Z4m5Z5m6Z6m7Z7m8Z8m9Z9m:Z:m;Z;m<Z< dd`l=m>Z>m?Z?m@Z@mAZAmBZBmCZC ddalDmEZEmFZFmGZGmHZHmIZImJZJ ddblKmLZMmNZOmPZQ  e
jR        e          ZSejT        dcejU        ddejV        deejW        dfejX        dgiZYdeeH         fdhZZ e[            Z\diZ]eyezdj<    e[            Z^dejfdkZ_deHdejfdlZ`deeH         fdmZadejdz  fdnZbdoedeHfdpZcdoedeNfdqZddoedeNfdrZedoedeNfdsZfdoedeNfdtZgdeHfduZhdveHdweHdxeHdeHfdyZidzeIdeHfd{Zjd|eHdeeH         fd}Zkd~eHde6dz  fdZldZmdZndZodZpdZqdZrdddeHdeHdeeg eNf                  defdZsdddeHdejt        dejt        deju        deeg eNf                  deNfdZvddddeHdeIdejt        dejt        deju        deIdeeg eNf                  ddfdZw ePem                                en                                eo                                ep                                eq                                er                                h          ZxdReeH         deNfdZydedeyeHdz  eHdz  f         fdZzdeHdeHdz  fdZ{d#ddeHfdZ|deNfdZ}defdZ~dejfdZdejdz  dejfdZdejfdZddejdz  deHfdZddddeHdeeH         deeH         deeH         fdZdddded#edeHdeeH         deeH         dee         fdZdeeeH                  fdZd~eHddfdZdejddAfdZdߐdZddlZd aej        ezd<   dddejdeHdedeHfdZdejdeNfdZdejdeNfdZdejdejdejfdZddZdZdedefdZ G d d          Z G d de,e.e0          Zdddejt        d:ej        deIddfdÄZddejt        defdƄZddejt        defdǄZdȐZdɐZ	 ddeej                 deIdeIdeNfd̈́Zde ddfdτZddee         deNdee         deNfd҄Zdӄ ZdeddfdՄZedk    r e             dS dS (  a<  
Gateway runner - entry point for messaging platform integrations.

This module provides:
- start_gateway(): Start all configured platform adapters
- GatewayRunner: Main class managing the gateway lifecycle

Usage:
    # Start the gateway
    python -m gateway.run
    
    # Or from CLI
    python cli.py --gateway
    N)OrderedDict)copy_contextPath)datetime)		AwaitableCallableDictOptionalAnyListTupleUnioncast)consume_detached_task_resultsafe_schedule_threadsafe)COMPACTION_STATUS1COMPRESSION_RETRY_CONTEXT_REDUCED_STATUS_TEMPLATE*COMPRESSION_RETRY_MESSAGES_STATUS_TEMPLATE(COMPRESSION_RETRY_TOKENS_STATUS_TEMPLATE+COMPRESSION_RETRY_TOO_LARGE_STATUS_TEMPLATEIDLE_COMPACTION_STATUS_TEMPLATE#PRE_API_COMPRESSION_STATUS_TEMPLATE%PREFLIGHT_COMPRESSION_STATUS_TEMPLATE)"INTERRUPT_WAITING_FOR_MODEL_PREFIX)t)request_hard_interrupt)cfg_get)get_fallback_chain         @      >@g     f@      @g      .@i   z'(?<![\w:/])/([A-Za-z0-9][A-Za-z0-9_-]*)gateway_hygieneuC  (auxiliary\s+.+\s+failed|compression\s+summary\s+failed|fallback\s+context\s+marker|configured\s+compression\s+model\s+.+\s+failed|no\s+auxiliary\s+llm\s+provider\s+configured|auto-lowered\s+compression\s+threshold|auto-lowered\s+(?:this\s+)?session'?s?\s+threshold|configured\s+auxiliary\s+compression\s+provider\s+.+\s+unavailable|skipping\s+concurrent\s+compression|compacting\s+context\s+[—-]\s+summarizing\s+earlier\s+conversation|resumed\s+after\s+\d+s\s+idle\s+[—-]\s+compacting|preflight\s+compression|pre[- ]api\s+compression|context\s+too\s+large\s+\(~[\d,]+\s+tokens\)\s+[—-]+\s+compressing|compressed\s+\d[\d,]*\s+(?:→|->)\s+\d[\d,]*\s+messages,\s+retrying|compressed\s+~[\d,]+\s+(?:→|->)\s+~[\d,]+\s+tokens,\s+retrying|context\s+reduced\s+to\s+[\d,]+\s+tokens\s+\(was\s+[\d,]+\),\s+retrying|session\s+compressed\s+\d+\s+times|rate\s+limited\.\s+waiting\s+\d|retrying\s+in\s+\d|max\s+retries\s+\(\d+\).*(?:trying\s+fallback|exhausted|invalid\s+responses)|stream\s+(?:drop|drop\s+mid\s+tool-call).+retry\s+\d|stale\s+connections\s+from\s+a\s+previous\s+provider\s+issue)
session_idcooldown_secondsreturnc                 .   ddl }t          | dd          }|dS t          |d|          }t          |dd          }|dS 	  |||                                 |z              dS # t          $ r&}t                              d|           Y d}~dS d}~ww xY w)aZ  Persist a session-hygiene compression-failure cooldown to the state DB.

    Uses the same ``compression_failure_cooldown_until`` column and
    ``record_compression_failure_cooldown`` method that the in-conversation
    compression path (``agent/context_compressor.py``) already uses, so the
    cooldown survives gateway restarts (#74136).
    r   N_session_db_db#record_compression_failure_cooldownz+session hygiene cooldown persist failed: %s)timegetattr	Exceptionloggerdebug)gatewayr%   r&   _time
session_dbrecorderexcs          1/home/thesage/.hermes/hermes-agent/gateway/run.py_record_hygiene_cooldownr7   {   s     -66JUJ77Jz#H$OOHIUZZ\\,<<===== I I IBCHHHHHHHHHIs   !A$ $
B.BBtemplatec                 j    t          j        d|           }d                    d |D                       S )u  Compile a compression status template constant into a regex source.

    Literal text is escaped verbatim (so wording drift in
    agent/conversation_compression.py cannot silently diverge from this
    matcher — the constants ARE the wording) and each ``{field}`` format
    placeholder is replaced with a numeric-ish pattern covering every value
    the emit sites format in (ints, ``{:,}`` thousands separators).
    z
\{[^{}]*\}z[\d,]+c              3   >   K   | ]}t          j        |          V  d S N)reescape.0parts     r6   	<genexpr>z,_status_template_to_regex.<locals>.<genexpr>   s*      <<d")D//<<<<<<    )r<   splitjoin)r8   partss     r6   _status_template_to_regexrF      s6     H]H--E>><<e<<<<<<rB   |c              #   4   K   | ]}t          |          V  d S r;   )rF   )r?   	_templates     r6   rA   rA      s>         	"),,     rB   c                  Z   	 t                      } t          | t                    r|                     d          nd}t          |t                    rIt	          |                    dd                                                                                    dv S n# t          $ r Y nw xY wdS )u  True when the user opted into routine compression progress notices.

    Reads ``compression.progress_notices`` from the gateway's raw YAML config
    (#52995). Default False — routine compression stays silent-by-design on
    chat platforms unless explicitly enabled. Read live (mtime-cached) so a
    config edit on a running gateway takes effect on the next status.
    Fail-closed: any config read error keeps the silent default.
    compressionNprogress_noticesF>   1onyestrue)_load_gateway_config
isinstancedictgetstrstriplowerr.   )configcompression_cfgs     r6   -_gateway_compression_progress_notices_enabledrZ      s    %''7A&$7O7OY&**]333UYot,, 	**+=uEEFFLLNNTTVV [  	    5s   BB 
B('B(>   localwebhook
api_servermsgraph_webhookplatformc                 .    t          |           t          v S )zBTrue only for programmatic/local surfaces that must keep raw text.)_gateway_platform_value_GATEWAY_RAW_TEXT_PLATFORMSr_   s    r6    _gateway_surface_passes_raw_textrd      s    "8,,0KKKrB   z(api\s+(?:call\s+)?failed|provider\s+authentication\s+failed|non-retryable\s+error|rate\s+limited\s+after\s+\d+\s+retries|error\s+code\s*:|\bhttp\s*\d{3}\b|incorrect\s+api\s+key|invalid\s+api\s+key)z(cybersecurity\s+risk|security\s+policy|safety\s+policy|policy\s+violation|violat(?:e|es|ed|ion)|blocked\s+(?:because|by|under)|request\s+(?:was\s+)?(?:blocked|rejected)|disallowed|moderation)zV(provider\s+authentication\s+failed|incorrect\s+api\s+key|invalid\s+api\s+key|\b401\b)z7(rate\s+limit|rate-limited|\b429\b|quota|usage\s+limit)z%\bsk-[A-Za-z0-9][A-Za-z0-9_\-]{12,}\bz\bgh[pousr]_[A-Za-z0-9_]{20,}\bz\bxapp-\d+-[A-Za-z0-9\-]{20,}\bz!\bxox[baprs]-[A-Za-z0-9\-]{20,}\bz\bhf_[A-Za-z0-9]{20,}\bz\bglpat-[A-Za-z0-9_\-]{20,}\bz'(?i)\b(Bearer\s+)[A-Za-z0-9._\-]{20,}\bc                     t           j        dk    rdS t          t                                                    j        j        } g }t          j                            d          r2|	                    t          t          j        d                              |	                    | dz             t                      }|D ]}	 |                                }n# t          $ r |}Y nw xY wt          |                                          }||v rQ|                    |           |dz  dz  }|                                st          |           }t          |          }|t           j        vr t           j                            d|           t%          j        |           |t           j        v rt           j                            |           t           j        rt           j        d         |k    rdnd}	t           j                            |	|           t          |          t          j        d<   ||g}
t          j                            d	          r%|
	                    t          j        d	                    t          j                            t.                              |
                    t          j        d	<    dS dS )
a  Make detached Windows gateway runs see the Hermes venv packages.

    Some Windows restart paths run the gateway under uv's base ``pythonw.exe``
    to avoid the venv launcher respawning a visible console interpreter.  That
    mode can import the source tree via cwd/PYTHONPATH but still miss optional
    packages installed only in ``venv/Lib/site-packages`` (notably the MCP SDK).
    Patch the live process before MCP discovery so tool injection does not
    depend on every launcher preserving PYTHONPATH perfectly.
    win32NVIRTUAL_ENVvenvLibsite-packagesr      
PYTHONPATH)sysr_   r   __file__resolveparentosenvironrT   appendsetOSErrorrU   rW   addexistspathinsertsite
addsitedirremovepathseprD   rS   fromkeys)project_root
candidatesseenvenv_dirresolved_venvvenv_keysite_packagesproject_entry
site_entry	insert_at
pythonpaths              r6   $_ensure_windows_gateway_venv_importsr     si    |w>>))++29LJ	z~~m$$ ;$rz-899:::lV+,,,UUD  	%$,,..MM 	% 	% 	%$MMM	%}%%++--t%-?##%% 	L))''
((HOOA}--- 	
###!!HOOJ'''Ichqk]&B&BAA		:...$'$6$6
=!#Z0
:>>,'' 	8bj6777#%:??4==3L3L#M#M
< ? s   CC&%C&c                     t          t          | d|           pd                                                                          S )zDReturn a normalized gateway platform value for enums or raw strings.value )rU   r-   rV   rW   rc   s    r6   ra   ra   H  s9    wx(339r::@@BBHHJJJrB   rc   metadatac                \    t          |          dk    r| S t          | pi           }d|d<   |S )zEMark Discord lifecycle/status sends without changing other platforms.discordTnon_conversational)ra   rS   )r   r_   mergeds      r6   _non_conversational_metadatar   M  s=     x((I55(.b!!F#'F MrB   agentsession_rowc                     d}t          |t                    r@|                    d          }t          |t                    r|                                r|}|| _        t          |          S )a]  Keep gateway hygiene from rebuilding a live session's system prompt.

    The hygiene helper intentionally skips memory-provider initialization.
    Compression is allowed to persist a system prompt, so letting that helper
    rebuild one would strip external provider blocks from the live session.
    Seed the exact persisted prompt instead.  When no usable prompt can be
    restored, seed an empty cache entry.  Compression either preserves that
    unusable value or rebuilds with the hygiene-only platform marker; the real
    turn will rebuild either form with its fully initialized providers.
    r   system_prompt)rR   rS   rT   rU   rV   _cached_system_promptbool)r   r   stored_prompt
raw_prompts       r6   _seed_hygiene_system_promptr   Z  sl     M+t$$ ' ___55
j#&& 	':+;+;+=+= 	'&M"/ErB   r5   c                     t                      }| }d}h d}|d|dk     r^t          |          }||v rnJ|                    |           |dz  }t          |          j        }||v rdS |j        p|j        }||dk     ^dS )uh  Return True for transient network errors safe to log + swallow.

    The crash class targeted by #31066 / #31110: an unhandled Telegram
    ``TimedOut`` (or peer ``NetworkError`` / ``httpx`` connection error)
    propagating to the event loop and killing the entire gateway
    process. These are by definition transient — the next poll cycle or
    user action recovers — so they must never crash the process.

    Walk the exception cause chain so wrapped errors (e.g. PTB's
    ``NetworkError`` wrapping ``httpx.ConnectError``) are still
    classified. The chain is bounded to avoid pathological cycles.
    r   >   TimedOut	ReadError
WriteErrorPoolTimeoutReadTimeoutConnectErrorNetworkErrorWriteTimeoutClientOSErrorConnectTimeoutRemoteProtocolErrorClientConnectorErrorServerDisconnectedErrorN   rk   TF)rt   idrv   type__name__	__cause____context__)r5   r   curdepthtransient_class_namesidentnames          r6   _is_transient_network_errorr   r  s     UUD#&CE   /ebjj3D==
Cyy!(((4m.s /ebjj 5rB   loopzasyncio.AbstractEventLoopcontextc           	         |                     d          }|t          |          r|                     d          p|                     d          }d}|T	 t          |d          r|                                nt	          |          }n# t
          $ r t	          |          }Y nw xY wt                              d|pdt          |          j	        |t          |          ||j
        f	           dS |                     |           dS )
a  Loop-level safety net for transient network errors.

    Installed once during :func:`start_gateway`. Catches the
    ``telegram.error.TimedOut`` crash class (issues #31066 / #31110)
    and any peer transient network error before it can kill the
    gateway process. Logs at WARNING with full traceback so the
    originating call site stays diagnosable; non-transient errors
    are forwarded to the default loop handler so real bugs still
    surface.
    	exceptionNfuturetaskr   get_namez9Gateway swallowed transient network error from %s: %s: %sz<unknown task>exc_info)rT   r   hasattrr   reprr.   r/   warningr   r   __traceback__default_exception_handler)r   r   r5   r   	task_names        r6   _gateway_loop_exception_handlerr     s    ++k
"
"C
6s;;{{8$$;F(;(;	'/6tZ/H/HXDMMOOOdSWjj		 ' ' ' JJ			'G))II3iic&78 	 	
 	
 	
 	""7+++++s   3B
 
B&%B&textc                     t          | pd          }	 ddlm}  ||d          }n# t          $ r Y nw xY wt          D ]}|                    d |          }|S )u  Secret redaction before text can leave the gateway.

    Delegates to the authoritative ``agent.redact.redact_sensitive_text`` — the
    same Tirith-grade redactor already applied to logs, tool output, and
    approval-command prompts — so the outbound chat path masks the full
    credential set the startup banner promises ("chat responses are scrubbed
    before delivery"), not a divergent subset. ``force=True`` honors redaction
    even when ``security.redact_secrets`` is off, matching the
    ``_redact_approval_command`` reasoning (#23810).

    The narrow ``_GATEWAY_SECRET_PATTERNS`` set runs as a belt-and-suspenders
    second pass so nothing the gateway historically caught can regress, and so
    redaction still degrades gracefully if the import ever fails.
    r   r   redact_sensitive_textTforcec                 D    | j         r|                     d          nddz   S )Nrk   r   z
[REDACTED])	lastindexgroup)ms    r6   <lambda>z5_redact_gateway_user_facing_secrets.<locals>.<lambda>  s     *K!''!***|)[ rB   )rU   agent.redactr   r.   _GATEWAY_SECRET_PATTERNSsub)r   redactedr   patterns       r6   #_redact_gateway_user_facing_secretsr     s     4:2H666666((>>>    	 , g g;;[[]effOs   ' 
44cmdz
str | Nonec                 F    ddl m}  |t          | pd          d          S )ug  Redact credentials from a command before it goes into an approval prompt.

    Tirith's *findings* are already redacted, but the gateway approval prompt
    is built from the raw command string, so a credential-shaped value Tirith
    flagged would otherwise be echoed verbatim to the chat platform (#48456).
    Uses ``redact_sensitive_text(force=True)`` — the same Tirith-grade redactor
    — so the prompt honors redaction even when ``security.redact_secrets`` is
    off. Module-level so the wiring is unit-testable (the call site is a deeply
    nested gateway closure that cannot be driven directly).
    r   r   r   Tr   )r   r   rU   )r   r   s     r6   _redact_approval_commandr     s6     322222  SYBt<<<<rB   TFallow_permanentallow_sessionsmart_deniedcommanddescriptioncommand_prefixr   r   r   c                n   t          |           dk    r| dd         dz   n| }d}|rd}d| dg}|s6|r4|                    d| d	           |r|                    d| d
           |                    d| d           | d| d| dd                    |dd                   z   d|d          dz   S )zHRender the text fallback from approval capabilities, not platform names.   N...u/   ⚠️ **Dangerous command requires approval:**u;   ⚠️ **Smart DENY — owner override for one operation:**zReply `z&approve` to execute this one operation`z8approve session` to approve this pattern for the sessionz&approve always` to approve permanentlyzdeny` to cancelz
```
z
```
Reason: 

, z, or .)lenrs   rD   )	r   r   r   r   r   r   cmd_previewheadingchoicess	            r6   _format_exec_approval_fallbackr     s!    ,/w<<#+=+='$3$-%''7K?G POOOOOPG WM WXXXX	
 	
 	
  	WNNU~UUUVVVNN6~666777HH;HH{HHH
))GCRCL
!
!	"$:GBK$:$:$:	;rB   c                     t                               |           r	 dS t                              |           r	 dS t                              |           rdS 	 dS )z@Map raw provider/API errors to a short user-safe Telegram reply.uv   ⚠️ Provider authentication failed. Check the configured credentials; raw provider details are in the gateway logs.u   ⚠️ The model provider rejected the request. I kept the raw provider error out of chat; check gateway logs for details or try rephrasing.uX   ⏱️ The model provider is rate-limiting requests. Please wait a moment and try again.u|   ⚠️ The model provider failed after retries. I kept raw provider details out of chat; check gateway logs for diagnostics.)_GATEWAY_AUTH_ERROR_REsearch_GATEWAY_PROVIDER_POLICY_RE_GATEWAY_RATE_LIMIT_REr   s    r6   _gateway_provider_error_replyr   
  s}    $$T** 
<	
 	
 #))$// 
S	
 	
 $$T** jii	; rB   z^\s*(\W*\s*)?(api\s+(?:call\s+)?failed|provider\s+authentication\s+failed|non-retryable\s+error|rate\s+limited\s+after\s+\d+\s+retries|error\s+code\s*:|http\s*\d{3}\b|incorrect\s+api\s+key|invalid\s+api\s+key)c                     | sdS t          |                                           }t          |          dk    s|                    d          dk    rdS t	          t
                              |                    S )uI  True when text is infrastructure/provider failure, not normal content.

    Two heuristics combined so the rewrite only fires on actual provider
    error envelopes, not on assistant prose that happens to mention an
    HTTP status code:

    1. The text is short — real provider errors are 1–3 lines of envelope
       text; assistant answers are usually longer.
    2. AND the error marker appears at the start of the message (optionally
       behind a punctuation/symbol prefix), not buried mid-paragraph in an
       explanation like "HTTP 404 means 'not found' — ...".
    F  
   )rU   rV   r   countr    _GATEWAY_PROVIDER_ERROR_SHAPE_REr   )r   bodys     r6   "_looks_like_gateway_provider_errorr   -  so      ut99??D 4yy3$**T**Q..u077==>>>rB   c                    |s|S t          |           r|S t          |                                                              t                    rdS t          t          |                    }t          |          rt          |          S |S )a  Sanitize final gateway replies before sending them to chat surfaces.

    Every human-facing chat surface (Telegram, WhatsApp, Discord, Slack,
    Signal, Matrix, plugin platforms, etc.) should receive concise, safe
    provider failure categories with secrets redacted instead of raw HTTP
    bodies, request IDs, leaked credentials, or policy text. Only programmatic
    surfaces in ``_GATEWAY_RAW_TEXT_PLATFORMS`` (CLI/TUI ``local`` diagnostics,
    API JSON, webhook payloads) keep the raw text unchanged.
    r   )rd   rU   rV   
startswithr   r   r   r   )r_   r   r   s      r6    _sanitize_gateway_final_responser   D  s      '11  4yy##$FGG r23t99==H)(33 7,X666OrB   
event_typemessagec                 X   t          |pd                                          }|sdS t          |           r|S t          |          }t                              |          r*t                      rt                              |          sdS t          |          rt          |          S |S )zFilter/sanitize agent status callbacks before platform delivery.

    Local/CLI sessions keep the raw diagnostic stream. Messaging gateway
    surfaces should not receive transient auxiliary/compression chatter.
    r   N)
rU   rV   rd   r   _TELEGRAM_NOISY_STATUS_REr   rZ   _COMPRESSION_PROGRESS_STATUS_REr   r   )r_   r  r  r   s       r6   _prepare_gateway_status_messager  ^  s     w}"##%%D t'11 .t44D ''--  :;;	/66t<<	 4)$// 3,T222KrB   c                 f    t          t          | dd          pd                                          S )u  Render an AgentNotice to a single plaintext line for messaging platforms.

    Messaging has no persistent status bar (unlike the TUI), so a notice is a
    one-shot standalone push. The notice policy already bakes the level glyph
    (⚠ / • / ✕ / ✓) into the text, and the TUI + CLI REPL render that text
    verbatim — so we emit it as-is here too. Prepending a per-level glyph would
    DOUBLE it ("⚠ ⚠ Credits 90% used", "⛔ ✕ Credit access paused"). Plaintext
    only — no markdown — so it renders uniformly across Telegram/Discord/Slack/
    SMS without per-platform escaping. Fail-soft: a malformed/empty notice
    degrades to "" rather than raising on the agent's callback path.
    r   r   )rU   r-   rV   )notices    r6   render_notice_liner	  |  s/     wvvr**0b1177999rB   c                    K   t          | dd          }t          |          r |||||           d{V S |                     |||           d{V S )a5  Route a status message through adapter.send_or_update_status when supported.

    Issue #30045: adapters that implement send_or_update_status (currently
    Telegram) edit the previous bubble for the same status_key instead of
    appending a new one. Adapters without the method fall back to plain send.
    send_or_update_statusNr   )r-   callablesend)adapterchat_id
status_keycontentr   senders         r6   _send_or_update_status_coror    s       W5t<<F MVGZ8LLLLLLLLLLgwBBBBBBBBBrB   reply_in_threadsource_thread_idevent_message_idr  c                0   t          | d|           }t          |pd                                          }|s9|r$|r"t          |          t          |          k    rdS |rt          |          ndS |rt          |          S |dv r|rt          |          S dS )u  Return thread/root ID that progress/status bubbles should target.

    ``reply_in_thread=False`` (Slack ``platforms.slack.extra.reply_in_thread``)
    disables the synthetic-thread fallback: progress messages must not create
    a thread the final flat reply would then inherit. A source.thread_id equal
    to the event's own message id is the adapter's synthetic session-keying
    thread, not a real thread — treat it as "no thread" too (#18859).
    r   r   N>   slack
mattermost)r-   rU   rW   )r_   r  r  r  platform_valueplatform_keys         r6   _resolve_progress_thread_idr    s     Xw99N~+,,2244L C	 	 $%%-=)>)>>>4(8Bs#$$$dB %#$$$...3C.#$$$4rB   user_configr  settingc                 <   t          | t                    r|                     d          nd}t          |t                    sdS |                    d          }t          |t                    sdS |                    |          }t          |t                    o||v S )zFReturn True when display.platforms.<platform> explicitly sets setting.displayNF	platformsrR   rS   rT   )r  r  r   r"  r#  platform_cfgs         r6   _has_platform_display_overrider&    s    ,6{D,I,ISkooi(((tGgt$$ uK((Ii&& u==..LlD))Eg.EErB   defaultr_   require_platform_override_forr(  r)  c                   t          |p|          }d |pt                      D             }||v rt          | ||          sdS ddlm}  || |||          }	t          |	t                    r|	S t          |	t                    r(|	                                	                                dv S |	t          |          S t          |	          S )aj  Resolve a boolean display setting with optional platform-only opt-in.

    Some display features expose assistant scratch text rather than deliberate
    user-facing output.  For high-noise threaded chat surfaces such as
    Mattermost, a global opt-in is too broad: they must be enabled with an
    explicit display.platforms.<platform>.<setting> override.
    c                 ,    h | ]}t          |          S  ra   )r?   	candidates     r6   	<setcomp>z0_resolve_gateway_display_bool.<locals>.<setcomp>  s0        	 	**  rB   Fr   resolve_display_setting>   rM   rN   rO   rP   )
ra   rt   r&  gateway.display_configr1  rR   r   rU   rV   rW   )
r  r  r   r(  r_   r)  current_platformplatform_onlyr1  r   s
             r6   _resolve_gateway_display_boolr5    s      /x/G<HH 7@355  M
 	M)).{L'RR 	* u>>>>>>##KwPPE% % C{{}}""$$(BBB}G}};;rB   c                     t          |d|          }|dk    r| S ddlm dt          j        t
                   dt
          ffd}t                              ||           S )a%  Rewrite slash-command mentions to Telegram-valid command names.

    Telegram Bot API command names allow only lowercase letters, digits, and
    underscores.  Keep other platform renderings unchanged, but normalize
    Telegram help text so command mentions remain clickable/valid there.
    r   telegramr   )_sanitize_telegram_namematchr'   c                 x     |                      d                    }|rd| n|                      d          S )Nrk   /r   )r   )r9  	sanitizedr8  s     r6   _replacez/_telegramize_command_mentions.<locals>._replace  s<    ++EKKNN;;	"+?9Q?rB   )r-   hermes_cli.commandsr8  r<   MatchrU   _TELEGRAM_COMMAND_MENTION_REr   )r   r_   r  r=  r8  s       @r6   _telegramize_command_mentionsrA    s     Xw99N##;;;;;;@ @# @ @ @ @ @ @ (++Hd;;;rB     r   c                 z   | dS t          | t                    r|                                 S t          | t                    rdS t          | t          t
          f          r4t          |           dk    rt          |           dz  nt          |           S t          | t                    r|                                 }|sdS 	 t          |          }|dk    r|dz  n|S # t          $ r Y nw xY w	 t          j	        |
                    dd                                                    S # t          $ r Y dS w xY wdS )a  Best-effort conversion of stored gateway timestamps to epoch seconds.

    Missing/unparseable timestamps return None so legacy transcripts keep the
    historical auto-continue behaviour instead of being silently dropped.
    Accepts: datetime, epoch seconds (int/float), epoch milliseconds (when
    the magnitude exceeds year-2286), ISO-8601 strings (with or without a
    trailing ``Z``), and numeric strings.
    Nl    d(	 g     @@Zz+00:00)rR   r   	timestampr   intfloatrU   rV   
ValueErrorfromisoformatreplace)r   r   numerics      r6   _coerce_gateway_timestamprL    sX    }t%"" !   % t%#u&& X(-e~(E(EuU||f$$5QV<<W% {{}} 	4	DkkG'.'?'?7V##WL 	 	 	D		)$,,sH*E*EFFPPRRR 	 	 	44	4s$   C 
C,+C,09D* *
D87D8c                  "    ddl m}   |             S )a  Return the configured auto-continue freshness window in seconds.

    Thin wrapper that delegates to the canonical implementation in
    ``gateway.session`` (the single source of truth shared with the
    routing-time zombie gate in ``get_or_create_session``).  Reads
    ``HERMES_AUTO_CONTINUE_FRESHNESS`` (bridged from ``config.yaml``
    ``agent.gateway_auto_continue_freshness`` at gateway startup, same
    pattern as ``HERMES_AGENT_TIMEOUT``).  Falls back to the module default
    when unset or malformed.  Non-positive values disable the freshness gate
    (restores the pre-fix "always fresh" behaviour for users who want to opt
    out).  Kept here so existing call sites and test patches importing it
    from ``gateway.run`` continue to work.
    r   auto_continue_freshness_window)gateway.sessionrO  rN  s    r6   _auto_continue_freshness_windowrQ  >  s%     ?>>>>>))+++rB   c                      t           j                            d          } | | dk    rt          t                    S 	 t          |           S # t
          t          f$ r t          t                    cY S w xY w)u8  Max seconds ``_finish_startup_restore`` waits on boot auto-resume turns
    before releasing the inbound gate and draining the queue.

    While startup restore is in progress the gateway QUEUES every inbound
    message (``_queue_startup_restore_event``) instead of processing it, so no
    channel gets a reply until the gate opens.  The gate is opened by
    ``_finish_startup_restore``, which waits for the synthetic boot
    auto-resume turns to finish.  A single long resumed turn therefore held
    the gate shut for every channel — inbound piled up unanswered for as long
    as that one turn ran.

    This bounds that wait.  Duplicate-agent safety does NOT depend on the
    wait: ``_schedule_resume_pending_sessions`` claims each session's
    ``_running_agents`` slot SYNCHRONOUSLY (before the gate ever runs), so a
    message drained while a resume turn is still running queues behind that
    slot rather than spawning a second agent.  So on timeout we release the
    gate and let the slow turn finish in the background.

    Reads ``HERMES_STARTUP_RESTORE_DRAIN_TIMEOUT`` (bridged from
    ``config.yaml`` ``agent.gateway_startup_restore_drain_timeout`` at gateway
    startup, same pattern as the other ``agent.*`` knobs).  Non-positive
    disables the bound (restores the historical "wait forever" behaviour).
    $HERMES_STARTUP_RESTORE_DRAIN_TIMEOUTNr   )rq   rr   rT   rG  +_STARTUP_RESTORE_DRAIN_TIMEOUT_SECS_DEFAULT	TypeErrorrH  )raws    r6   #_startup_restore_drain_timeout_secsrW  P  s    0 *..?
@
@C
{cRii@AAABSzzz" B B B@AAAAABs   A %A43A4r   c                     t           j                            |           }||dk    rt          |          S 	 t          |          S # t          t
          f$ r t          |          cY S w xY w)zRead an env var as float, falling back to ``default`` on typos/empty.

    A misconfigured env var (e.g. ``HERMES_AGENT_TIMEOUT=abc``) must not
    crash the gateway or an agent turn.  Unset/empty also falls back.
    Nr   )rq   rr   rT   rG  rU  rH  )r   r(  rV  s      r6   
_float_envrY  q  ss     *..

C
{cRiiW~~Szzz"   W~~s   A  A*)A*desc
provenanceActivityProvenancedebug_labelc                     	 |                      ||           dS # t          $ r  t                              |d           Y dS w xY w)zJBest-effort activity provenance stamp for hygiene compression transitions.)r[  Tr   N)_touch_activityr.   r/   r0   )r   rZ  r[  r]  s       r6   %_stamp_hygiene_compression_provenancer`    s`    1dz::::: 1 1 1[40000001s    &AA)nowwindow_secsra  rb  c                    |t          |          nt          t                    }|dk    rdS t          |           }|dS |t          j                    n|}||z
  |k    S )a  Return True when an interruption marker is fresh enough to auto-continue.

    Unknown timestamps are treated as fresh for backward compatibility with
    legacy transcripts (pre-dating timestamp persistence) and with in-memory
    test scaffolding that constructs history entries without timestamps.

    A non-positive ``window_secs`` disables the gate (always fresh), which
    restores the pre-fix behaviour for users who opt out via config.
    Nr   T)rG  %_AUTO_CONTINUE_FRESHNESS_SECS_DEFAULTrL  r,   )r   ra  rb  windowrE  currents         r6   _is_fresh_gateway_interruptionrg    sv    " " 	k899 
 {{t)%00It [dikkkcGY&((rB   r   interactivereasonri  c                v    | dk    rdn	| dk    rdnd}|rd}d}n|rd}d}nd	}d
}d| d| d| d|rd| ndz   S )up  Build the resume-pending recovery system note for an interrupted turn.

    ``reason`` is the session's ``resume_reason`` (``restart_timeout``,
    ``shutdown_timeout``, or anything else → generic interruption phrasing).
    ``message`` is the user's NEW message text; empty means this is the
    startup auto-resume turn synthesized by
    ``_schedule_resume_pending_sessions`` with no human message attached.

    ``interactive`` selects the empty-message guidance: on interactive
    platforms a human is present, so "report the restore and ask what next"
    is right.  On non-interactive event platforms (webhook, API server —
    adapters with ``interactive_resume = False``) nobody can answer; the
    resumed turn must instead complete the interrupted work, or the task is
    silently abandoned behind a "restored" acknowledgement that goes
    nowhere (#57056).
    restart_timeoutza gateway restartshutdown_timeoutza gateway shutdownza gateway interruptionzTAddress the user's NEW message below FIRST and focus on what the user is asking now.u\   Do NOT re-execute old tool calls — skip any unfinished work from the conversation history.zfReport to the user that the session was restored successfully and ask what they would like to do next.zNo user is present on this non-interactive platform, so do NOT emit a 'session restored' acknowledgement or ask questions. Review the conversation history and CONTINUE the interrupted task to completion.u   Do NOT re-run tool calls whose results already appear in the history — resume from the first step that has no recorded result.z3[System note: The previous turn was interrupted by u   ; the gateway is now back online. Any restart/shutdown command in the history has already run — do NOT re-execute or verify it.  ]r   r   r,  )rj  r  ri  reason_phraseresume_guidancetail_guidances         r6   build_resume_recovery_noters    s    0 &&& 	 ''' "!%   
. 	
= 	 
 
D 	
= 	; 	+ 			 	 4C	 	 		 	 	
  '.'B	0rB   )	reasoningreasoning_contentreasoning_detailscodex_reasoning_itemscodex_message_itemsfinish_reason._ASSISTANT_REPLAY_FIELDSroler  msgpreserve_timestampc                 `   | |d}|                     d          }| dv r5t          |t                    r |r||                     d          k    r||d<   | dk    r6t          D ].}||vr|                     |          }|dk    r|%n|s)|||<   /|r|                     d          }|r||d<   |S )	u	  Build a replay entry for a non-tool-calling message, preserving the
    assistant fields the agent's API builders rely on for multi-turn fidelity.

    Lifted out of the inline ``run_sync`` closure so the field whitelist can
    be unit-tested in isolation.  Mirrors the ``_ASSISTANT_REPLAY_FIELDS``
    contract above.

    ``preserve_timestamp``: when True, copy the source row's ``timestamp``
    onto the replay entry. Currently only user messages need this — the
    stale-dangerous-confirmation stripper in ``agent/replay_cleanup.py``
    reads the timestamp to decide whether a confirmation is too old to
    replay safely.  Assistant/tool messages are not timestamp-stripped in
    the same way, so we keep the existing default of dropping it.

    Empty values: most fields are dropped when falsy (matching the original
    PR #2974 behaviour) since an empty list/string for those carries no
    information.  The exception is ``reasoning_content``: DeepSeek/Kimi
    thinking-mode replay treats an empty string as a meaningful sentinel
    that ``_copy_reasoning_content_for_api`` upgrades to a single space.
    Dropping it here would make the gateway send no ``reasoning_content``
    at all on the next turn, which can cause HTTP 400 from strict thinking
    providers.
    r{  r  api_content)user	assistantr  r  ru  NrE  )rT   rR   rU   rz  )	r{  r  r|  r}  entry_sidecar_rkey_rvaltss	            r6   _build_replay_entryr    s   : &*g>>E ww}%%H%%%x%% 	& 	& swwy))))'m{- 
	! 
	!ECGGENNE+++= !  E%LL $WW[!! 	$!#E+LrB   zobserved Telegram group contextz>[Observed Telegram group context - context only, not requests]zh[Current addressed message - answer only this unless it explicitly asks you to use the observed context]channel_promptc                 2    t          | ot          | v           S )a  Return True for Telegram group turns that may include observed chatter.

    Telegram's observe-unmentioned mode persists skipped group chatter so a
    later @mention can see it. Those rows must not replay as ordinary user
    turns: a weak wake word like ``@bot cambio`` should not make the model treat
    old unmentioned chatter as pending work. The Telegram adapter marks these
    turns with a channel prompt; this helper keeps the run-path check explicit
    and unit-testable.
    )r   (_TELEGRAM_OBSERVED_CONTEXT_PROMPT_MARKER)r  s    r6   %_uses_telegram_observed_group_contextr  \  s     ]#K~#]^^^rB   rV  c                    | t                      S t          | t                    rd | D             S t          |                                           }|st                      S d |                    d          D             S )zDNormalize a config list or comma-separated scalar into a string set.Nc                     h | ]D}t          |                                          #t          |                                          ES r,  )rU   rV   r>   s     r6   r/  z&_csv_or_list_to_set.<locals>.<setcomp>o  s=    GGGdSYY__5F5FGD		!!GGGrB   c                 ^    h | ]*}|                                 |                                 +S r,  rV   r>   s     r6   r/  z&_csv_or_list_to_set.<locals>.<setcomp>s  s-    BBBTTZZ\\BDJJLLBBBrB   ,)rt   rR   listrU   rV   rC   )rV  ss     r6   _csv_or_list_to_setr  j  s{    
{uu#t HGGcGGGGCA uuBBQWWS\\BBBBrB   rX   c                     t          | di                               t          j                  }d}|$t          |di                               d          }|t	          j        d          pd}t          |          S )a  Return Slack channels that the generic gateway must never dispatch.

    The Slack adapter has the first-line drop, but this runner-level guard is
    intentionally duplicated as a fail-safe. If a future Slack code path, test
    hook, malformed event, or stale adapter instance bypasses the Slack plugin
    adapter, ignored channels still cannot reach auth, pairing, sessions, or
    the agent/home-channel prompt pipeline.
    r#  Nextraignored_channelsSLACK_IGNORED_CHANNELS)r-   rT   PlatformSLACKrq   getenvr  )rX   r%  rV  s      r6   +_slack_ignored_channels_from_gateway_configr  v  sz     6;3377GGL
ClGR00445GHH
{ i0119Ts###rB   r  c                 \    | sdS t          |                               dd          d         S )zFReturn the parent Slack channel from a possibly thread-scoped chat ID.r   :rk   r   )rU   rC   r  s    r6   _slack_parent_channel_idr    s0     rw<<c1%%a((rB   c                 l    t          |          }t          |           }t          |od|v p||v           S )zDCheck the generic Slack gateway blacklist for channel or thread IDs.*)r  r  r   )rX   r  
channel_idignoreds       r6   _is_slack_ignored_channelr    s=    )'22J9&AAG
Hw G*2GIIIrB   c                 @   t          | t                    sdS |                     d          }t          |t                    sdS |                    d          }t          |t                    r#t          |                    dd                    S t          |          S )a;  True when gateway.message_timestamps.enabled is opted in.

    Default OFF: injecting a ``[Tue 2026-04-28 13:40:53 CEST]`` prefix onto
    every user message changes what the model sees for all gateway users, so
    it must be explicitly enabled in config.yaml under
    ``gateway.message_timestamps.enabled``.
    Fr1   message_timestampsenabled)rR   rS   rT   r   )r  gwmts      r6   _message_timestamps_enabledr    s     k4(( u		#	#Bb$ u	$	%	%B"d .BFF9e,,---88OrB   r  inject_timestampshistoryr  c                \   ddl m} ddlm}  |            }g }g }t	          |          }| pg D ]}	|	                    d          }
|
s|
dv r |
dk    r'|	                    d          }|r<|
dk    r6t          |t                    r! |||	                    d	          |
          }|rR|	                    d          r=|
dk    r7|r5|                    t          |          	                                           d|	v }d|	v }|
dk    }|s|s|r5d |	
                                D             }|                    |           |rx|
dk    rt          |          }|s2|	                    d          r|	                    dd          }d| d| }t          |
||	|
dk              }|                    |           t          |          }t          |          }t          |t!          j                              }d                    |          	                                pd}||fS )a  Convert stored gateway transcript rows into agent replay messages.

    Observed Telegram group rows are returned as API-only context for the
    current addressed message instead of being replayed as normal prior user
    turns.  Keeping that context out of ``conversation_history`` avoids
    consecutive-user repair merging it with the live user turn and then hiding
    the current message behind ``history_offset`` during persistence.

    When ``inject_timestamps`` is True (gateway.message_timestamps.enabled),
    each replayed user message is rendered with a single human-readable
    timestamp prefix from its stored metadata.
    r   get_timezone)"render_user_content_with_timestampr{  >   session_metasystemr  r  rE  tzobserved
tool_callstool_call_idtoolc                 "    i | ]\  }}|d v	||S )>   r  rE  r,  r?   kvs      r6   
<dictcomp>z0_build_gateway_agent_history.<locals>.<dictcomp>  s)    \\\$!QB[9[9[A9[9[9[rB   mirrormirror_sourcezanother sessionz[Delivered from ] )r}  ra  r   N)hermes_timer  gateway.message_timestampsr  r  rT   rR   rU   rs   rV   items_strip_auto_continue_noiser  strip_interrupted_tool_tailsstrip_dangling_tool_call_tail#strip_stale_dangerous_confirmationsr,   rD   )r  r  r  _get_msg_tz_render_msg_ts_msg_tzagent_historyobserved_group_contextseparate_observed_contextr|  r{  r  has_tool_callshas_tool_call_idis_tool_message	clean_msg
mirror_srcr  observed_contexts                      r6   _build_gateway_agent_historyr    s   & 877777      kmmG*,M(* En U U}" 2( 2(wwv 	 $$$ 8'')$$ 	PJw4L4L$nWcggk.B.BwOOOG$ 	)<)< 	T["))#g,,*<*<*>*>??? &,)S0&. 	(- 	( 	(\\#))++\\\I  ++++ 	( v~~4W== wwx   E WW_6GHH
DZDD7DD (gsPTX^P^```E  ''' 1??M 2-@@M 849;;  M yy!788>>@@HD***rB   persisted_historylive_historyc                     t          |t                    r/t          |          t          |           k    rt          |          S | S )a  Prefer a cached agent's live in-memory transcript over a shorter
    persisted one.

    Guards the FTS write-corruption case (#50502): when message writes fail
    silently through corrupt FTS triggers, the next turn reloads a stale/empty
    ``conversation_history`` from disk even though the same cached ``AIAgent``
    still holds the full live ``_session_messages``. Replacing the live
    transcript with that shorter persisted copy causes immediate same-session
    amnesia. When the live transcript is strictly longer, keep it.

    Returns ``persisted_history`` unchanged unless the live copy is a longer
    list, in which case a copy of the live transcript is returned.
    )rR   r  r   )r  r  s     r6   _select_cached_agent_historyr    sE    " ,%% "#l*;*;cBS>T>T*T*TL!!!rB   r  c                    |s| S t            d| dt           d}t          | t                    r| |  S t          | t                    r{d | D             }|D ]Q}t          |t
                    r:|                    d          dk    r!| |                    dd           |d<   |c S Rd|                                dg|z   S | S )zDPrepend observed Telegram context to the API-only current user turn.r   r   c                 Z    g | ](}t          |t                    rt          |          n|)S r,  )rR   rS   r>   s     r6   
<listcomp>z?_wrap_current_message_with_observed_context.<locals>.<listcomp><  s1    VVVdD$!7!7A4:::TVVVrB   r   r   r   )r   r   )_OBSERVED_GROUP_CONTEXT_HEADER!_CURRENT_ADDRESSED_MESSAGE_HEADERrR   rU   r  rS   rT   rstrip)r  r  prefixwrappedr@   s        r6   +_wrap_current_message_with_observed_contextr  ,  s      * 	1 	1	1 	1,	1 	1 	1  '3 $#'###'4   EVVgVVV 	 	D$%% $((6*:*:f*D*D"(@$((62*>*>@@V99:WDDNrB   c                     | sdS t          |           D ]Q}t          |t                    s|                    d          }|r|dv r4|                    d          }||c S  dS dS )uI  Return the ``timestamp`` of the last usable transcript row, if any.

    Skips metadata-only rows (``session_meta``, system injections) that are
    dropped before being handed to the agent.  Returns ``None`` when no
    usable row carries a timestamp — callers should treat that as "fresh"
    for backward compatibility.
    Nr{  >   r  r  rE  )reversedrR   rS   rT   )r  r|  r{  r  s       r6   _last_transcript_timestampr  F  s      t    #t$$ 	wwv 	t999WW[!!>III tt4rB   >   image_generatetext_to_speechtext_to_speech_toolbfl_flux3_get_result)r  r  r  z [System note: Your previous turnz[System note: A new messagec                     t          | t                    sdS |                     t                    p|                     t                    S )zReturn True if this user-message content is a gateway-injected
    auto-continue note that should NOT be replayed as a real user turn.F)rR   rU   r   _AUTO_CONTINUE_NOTE_PREFIX_AUTO_CONTINUE_FALLBACK_PREFIX)r  s    r6   _is_auto_continue_noiser  |  sI     gs## u566 	><==rB   c                     t          |           s| S t          |           }t          |          rK|                    d          }|dk     rdS ||dz   d                                         }t          |          K|S )aW  Remove persisted gateway auto-continue note prefix from user text.

    Older gateway builds prepended the recovery note directly to the user
    message, so the transcript row can contain both the synthetic note and
    the user's real question.  Strip one or more leading synthetic notes while
    preserving any real text that follows.
    ro  r   r   rk   N)r  rU   findlstrip)r  r   ends      r6   r  r    s     #7++ w<<D
!$
'
' (iinn772C!GII%%''	 "$
'
' (
 KrB   )
host_imageimageagent_visible_imagezMEDIA:((?:[A-Za-z]:[/\\]|/|~\/)\S+\.(?:png|jpe?g|gif|webp|mp4|mov|avi|mkv|webm|ogg|opus|mp3|wav|m4a|flac|epub|pdf|zip|rar|7z|docx?|xlsx?|pptx?|txt|csv|apk|ipa))messageshistory_offsethistory_media_pathsc                    |pt                      }|rt          |           |k    r| |d         }n| }i }|D ]}|                    d          dk    r|                    d          pg D ]}|                    d          p|                    d          }|                    d          pi }t          |                    d          p|                    d          pd	          }	|r|	r|	|t          |          <   g }
d
}|D ]}|                    d          dvrt          |                    d          p|                    d          pd	          }|                    |          t          vrqt          |                    d          pd	          }|                    |          }|dk    rd|vr	 t          j        |          }n# t          $ r d}Y nw xY wt          |t                    r|                    d          rot          D ]g}|                    |          }t          |t                    r;t                              d|           r||vr|
                    d|             nhwd|vr}t                              |          D ]Z}|                    d                                                              d          }|r||vr|
                    d|            [d|v rd}|
|fS )a9  Collect real media tags from current-turn producer-tool results only.

    Two layered guards keep stale/example MEDIA: strings out of the reply:

    1. Producer-tool allowlist: only tools that intentionally emit deliverable
       artifacts (TTS) are eligible. Documentation, logs, and search results can
       contain example strings such as MEDIA:/absolute/path/to/file, which must
       never be delivered as attachments. (Fixes the original report behind #16721.)
    2. Current-turn isolation: only messages produced this turn are scanned, so a
       tool result from an earlier turn (still present in the full message list)
       cannot leak onto a later text-only reply (#34608).

    Mid-run context compression can rewrite/shrink the message list below the
    original history length. When that happens the slice boundary is no longer
    trustworthy, so fall back to scanning every message and rely on
    ``history_media_paths`` for dedup, preserving the compression-safe behaviour
    of #160. The producer-tool allowlist still applies on the fallback path.
    Nr{  r  r  r   call_idfunctionr   r   F)r  r  r  r  r  MEDIA:successrk   ",}[[audio_as_voice]]T)rt   r   rT   rU   _AUTO_APPEND_MEDIA_TOOL_NAMESjsonloadsr.   rR   rS   _JSON_MEDIA_TOOL_PATH_FIELDS_TOOL_MEDIA_RE	fullmatchrs   finditerr   rV   r  )r  r  r  new_messagestool_name_by_call_idr|  callr  fnr   
media_tagshas_voice_directiver  	tool_namepayloadfieldrx   r9  s                     r6   _collect_auto_append_media_tagsr    s^   . .6   #h-->990+- : :776??k))GGL))/R 	: 	:Dhhtnn;(;(;G*%%+Brvvf~~?&)9)9?R@@D :4 :59$S\\2	: J  '  '776??"666cggn--I1C1CIrJJ##G,,4QQQcggi((.B//(,,W55	 (((XW-D-D*W--   '4(( W[[-C-C 9  E";;u--D"4--  . 8 8$ I I $,? ? ?"))/4//:::7""#,,W55 	3 	3E;;q>>''))0077D 3$777!!/4//2227**"&***s   9GGGr  c                    t                      i }dt          ddffd}| D ]}|                    d          dk    r|                    d          pg D ]}|                    d          p|                    d	          }|                    d
          pi }t          |                    d          p|                    d          pd          }|r|r||t          |          <   | D ]~}|                    d          }|dk    r5t          |                    dd          pd          }	d|	v r ||	           S|dvrXt          |                    dd          pd          }	d|	v r ||	           t          |                    d          p|                    d	          pd          }|                    |          dk    r	 t          j        |	          }
n# t
          $ r d}
Y nw xY wt          |
t                    rb|
                    d          rMt          D ]E}|
                    |          }t          |t                    r|r	                    |            nFS )a  Collect every media path already delivered in prior assistant/tool output.

    Used to dedup auto-appended and model-emitted MEDIA tags so the same file
    is not re-sent on later turns. Covers three delivery shapes:
      * ``MEDIA:<path>`` text tags in tool results,
      * ``MEDIA:<path>`` text tags in assistant messages (model-generated tags),
      * ``image_generate`` JSON-payload paths (``host_image`` / ``image`` /
        ``agent_visible_image``), which carry no MEDIA: tag.

    Missing the JSON-payload shape caused #46627; missing the assistant-message
    shape caused repeated delivery when the model echoed a previous MEDIA tag.
    r  r'   Nc                 P   t                               |           D ]S}|                    d                                                              d          }|r                    |           Tt          j        |           \  }}                    d |D                        d S )Nrk   r  c              3       K   | ]	\  }}|V  
d S r;   r,  )r?   rx   	_is_voices      r6   rA   zN_collect_history_media_paths.<locals>._add_text_media_paths.<locals>.<genexpr>  s&      ==odIT======rB   )	r  r  r   rV   r  rv   BasePlatformAdapterextract_mediaupdate)r  r9  rx   media_files_pathss        r6   _add_text_media_pathsz;_collect_history_media_paths.<locals>._add_text_media_paths  s    #,,W55 	  	 E;;q>>''))0077D  		$
 -:7CCQ==========rB   r{  r  r  r   r  r  r   r   r  >   r  r  r  r  r  )
rt   rU   rT   r  r  r.   rR   rS   r  rv   )r  r	  r  r|  r
  cidr  r   r{  r  r  r  jpr  s                @r6   _collect_history_media_pathsr    s    E+-
>s 
>t 
> 
> 
> 
> 
> 
>  : :776??k))--3 : :hhtnn;(;(;XXj))/R266&>>CTXXf-=-=CDD :4 :59(S2  wwv;#'')R006B77G7""%%g...+++cggi,,233w!!'***#''.))ESWWY-?-?E2FF##C((,<<<*W--   '4(( W[[-C-C 9  E U++B!"c** r 		"Ls   G  G/.G/c                     t           j                            d          } | rnt           j                            |           rdS t          j        t                                        d|            t           j        	                    dd           ddl
}|                                }|j        |j        fD ]5}|r1t           j                            |          r|t           j        d<    dS 6	 ddl}|                                t           j        d<   dS # t           $ r Y nw xY wdD ]3}t           j                            |          r|t           j        d<    dS 4dS )a  Set SSL_CERT_FILE if the system doesn't expose CA certs to Python.

    Windows startup paths (Desktop, Scheduled Tasks, installer children) can
    occasionally inherit a stale SSL_CERT_FILE. Returning just because the
    variable is present makes every later httpx/OpenAI client construction fail
    with FileNotFoundError from ssl.load_verify_locations(). Treat a missing
    path as unset and fall back to certifi instead.
    SSL_CERT_FILENz?Ignoring stale SSL_CERT_FILE=%r because the path does not existr   )z"/etc/ssl/certs/ca-certificates.crtz /etc/pki/tls/certs/ca-bundle.crtz1/etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pemz/etc/ssl/ca-bundle.pemz/etc/ssl/cert.pemz/etc/pki/tls/cert.pemz#/usr/local/etc/openssl@1.1/cert.pemz&/opt/homebrew/etc/openssl@1.1/cert.pem)rq   rr   rT   rx   rw   logging	getLoggerr   r   popsslget_default_verify_pathscafileopenssl_cafilecertifiwhereImportError)configured_certr%  r  r.  r)  s        r6   _ensure_ssl_certsr-  B  ss    jnn_55O .7>>/** 	F(##++M	
 	
 	
 	
---JJJ ((**ElE$89  	 		22 	*3BJ'FF&-mmoo
?#   	  	 7>>)$$ 	*3BJ'FF	 s   -%D 
D! D!platform_namec                 Z    ddl m}  ||           }|r|S |                                  dS )a  Return the configured home-target env var for a platform.

    Consults built-in ``_HOME_TARGET_ENV_VARS`` first, then the plugin
    registry via ``cron.scheduler._resolve_home_env_var``, then falls back
    to ``<PLATFORM>_HOME_CHANNEL`` for unknown names.
    r   )_resolve_home_env_var_HOME_CHANNEL)cron.schedulerr0  upper)r.  r0  resolveds      r6   _home_target_env_varr5  u  sN     544444$$]33H !!##2222rB   c                 &    t          |            dS )zDReturn the optional thread/topic env var for a platform home target.
_THREAD_ID)r5  )r.  s    r6   _home_thread_env_varr8    s    "=11====rB   c                  :    t           dz                                  S )zIReturn True when a /restart completion marker is waiting to be delivered..restart_notify.json)_hermes_homerw   r,  rB   r6   _restart_notification_pendingr<    s    1199;;;rB   c                      t           dz  S )Nz.restart_pending.json)r;  r,  rB   r6   "_planned_restart_notification_pathr>    s    111rB   c                  B    t                                                      S )zHReturn True when a non-chat planned restart should notify home channels.)r>  rw   r,  rB   r6   %_planned_restart_notification_pendingr@    s    -//66888rB   c                  J    t                                          d           d S )NT
missing_ok)r>  unlinkr,  rB   r6   #_clear_planned_restart_notificationrE    s%    &((//4/@@@@@rB   rM   _HERMES_GATEWAY)get_hermes_homeget_hermes_home_override)atomic_json_writeis_truthy_value)load_dotenv)load_hermes_dotenv.envrk   hermes_homeproject_envc                  
   ddl m}   |             rt          t                     dS t	          t          t          t                                                    j        d         dz             t          t                     dS )a  Reload .env for fresh credentials without letting stale .env override config.

    Gateway processes are long-lived, so per-turn code reloads ~/.hermes/.env to
    pick up rotated API keys. config.yaml remains authoritative for agent budget
    settings such as agent.max_turns; otherwise a stale HERMES_MAX_ITERATIONS in
    .env can replace the startup bridge on later turns.

    In multiplex mode this is a NO-OP for the credential reload: secrets come
    from the per-turn ``set_secret_scope`` (installed by ``_profile_runtime_scope``)
    which loads the routed profile's ``.env`` into an isolated mapping. Mutating
    the process-global ``os.environ`` here would defeat that isolation and leak
    the default profile's keys to every profile's turns and subprocesses.
    r   is_multiplex_activeNrk   rM  rN  )	agent.secret_scoperS  _bridge_max_turns_from_configr;  rL  r   rn   ro   parentsrR  s    r6   /_reload_runtime_env_preserving_config_authorityrW    s     766666  	&l333 NN**,,4Q7&@    ",/////rB   homer   c                    | dz  }|                                 sdS 	 ddlm}m}  ||          } ||          }t	          |t
                    si }	 ddlm}  |j        |          }n# t          $ r Y nw xY wn# t          $ r Y dS w xY w|
                    di           }t	          |t
                    r&d|v r"t          |d                   t          j        d<   |
                    d	i           }t	          |t
                    rNd
|v r"t          |d
                   t          j        d<   d|v r&t          |d                   t          j        d<   dS dS dS )zIBridge config.yaml agent.max_turns into HERMES_MAX_ITERATIONS (a global).config.yamlNr   _expand_env_varsread_user_config_rawmanaged_scoper   	max_turnsHERMES_MAX_ITERATIONSsessionscjk_ftsHERMES_CJK_FTSsearch_slow_msHERMES_SEARCH_SLOW_MS)rw   hermes_cli.configr\  r]  rR   rS   
hermes_clir_  apply_managed_overlayr.   rT   rU   rq   rr   )rX  config_pathr\  r]  cfgr_  	agent_cfgsessions_cfgs           r6   rU  rU    s   &K LLLLLLLL #";//s###t$$ 	C
	0000005-5c::CC 	 	 	D	    $$I)T"" J{i'?'?.1)K2H.I.I
*+ 77:r**L,%% V$$+.|I/F+G+GBJ'(|++25lCS6T2U2UBJ.///	V V ,+s5   5A; A* )A; *
A74A; 6A77A; ;
B	B	c                      t                       	 t          t          j        dd                    S # t          t
          f$ r Y dS w xY w)zGReturn the current per-turn iteration budget after runtime env refresh.ra  500  )rW  rF  rq   r  rU  rH  r,  rB   r6   _current_max_iterationsrq    sU    3555294e<<===z"   sss   !2 AA)contextmanager)PORT_BINDING_PLATFORM_VALUESplatform_binds_portc                       e Zd ZdZdS )MultiplexConfigErrora  A profile multiplexer config is invalid.

    Distinct from a transient adapter-connect failure: a config error means the
    operator must fix config.yaml. Fatal configuration errors propagate to the
    startup guard instead of being treated as retryable adapter noise.
    Nr   
__module____qualname____doc__r,  rB   r6   rv  rv    s           rB   rv  c                       e Zd ZdZdS )SecondaryPortBindingConfigErrorzEA secondary profile conflicts with the multiplexer's shared listener.Nrw  r,  rB   r6   r|  r|    s        OOOOrB   r|  profile_homec              #   H  K   ddl m}m} ddlm}m}m} ddlm}  |t          |                     } |t          |                       | |t          |                               }	 dV   ||            ||           dS #  ||            ||           w xY w)u  Scope config/skills/memory AND credentials to a profile for one turn.

    Combines the two seams the multiplexer needs:
      1. ``set_hermes_home_override`` — redirects ``get_hermes_home()`` (config,
         skills, memory, SOUL, sessions) to the profile's home. Contextvar, so
         it propagates into the agent worker thread via ``copy_context()``.
      2. ``set_secret_scope`` — installs the profile's ``.env`` secrets as the
         authoritative credential source, so ``get_secret`` reads this profile's
         keys and never the process-global ``os.environ`` (which in a
         multiplexer may hold another profile's values).

    Only used on the multiplexed inbound path. Single-profile gateways never
    enter this scope, so their behavior is unchanged. Loading the profile's
    ``.env`` here does NOT mutate ``os.environ`` — ``build_profile_secret_scope``
    returns an isolated dict — which is what keeps subprocesses (MCP, kanban)
    from inheriting cross-profile secrets.
    r   )set_hermes_home_overridereset_hermes_home_override)build_profile_secret_scopeset_secret_scopereset_secret_scope)hydrate_profile_secret_sourcesN)hermes_constantsr  r  rT  r  r  r  hermes_cli.env_loaderr  rU   r   )	r}  r  r  r  r  r  r  
home_tokensecret_tokens	            r6   _profile_runtime_scoper    s     & VUUUUUUU         
 EDDDDD))#l*;*;<<J""4#5#5666##$>$>tL?Q?Q$R$RSSL/<((("":..... 	<((("":....s   -B	 	B!GatewayConfigc                  n   t                      } t          | dd          s| S 	 t                      }n# t          $ r | cY S w xY w	 t	          t          |                    5  t                      cddd           S # 1 swxY w Y   dS # t          $ r! t                              dd           | cY S w xY w)u.  Load gateway config for the process-level GatewayRunner.

    When ``gateway.multiplex_profiles`` is off, this is identical to
    ``load_gateway_config()`` (legacy single-profile path).

    When multiplexing is on, reload under the default/active profile's
    ``_profile_runtime_scope`` so platform tokens in that profile's ``.env``
    resolve through the secret scope — the same path secondary profiles use
    in ``_start_one_profile_adapters``. Without this, primary startup calls
    ``load_gateway_config()`` unscoped: ``_getenv`` falls through to
    ``os.environ``, which often has no ``TELEGRAM_BOT_TOKEN`` once the token
    lives only under ``profiles/<name>/.env`` (#64674).

    Single-profile gateways never set ``multiplex_profiles``, so they keep the
    unscoped load and are unaffected.
    multiplex_profilesFNzAmultiplex default-scope config reload failed; using unscoped loadTr   )load_gateway_configr-   rG  r.   r  r   r/   r0   )rk  rX  s     r6   load_gateway_config_for_runnerr  ?  s,   " 

C3,e44 
     


#DJJ// 	) 	)&((	) 	) 	) 	) 	) 	) 	) 	) 	) 	) 	) 	) 	) 	) 	) 	) 	) 	)   O 	 	
 	
 	
 


sE   2 A AB	 !A</B	 <B  B	 B B	 	(B43B4r  platform_configPlatformConfigc                    ddl m} | |vrdS t          |dd          pd}t          |t                    r|                                rdS t          |dd          pd}t          |t                    r|                                rdS dS )	zReturn True when a token-authenticated platform has a usable bot credential.

    Platforms that do not use ``PlatformConfig.token`` always return True so we
    never skip them here (Signal session paths, port-binding HTTP adapters, etc.).
    r   )PLATFORM_TOKEN_ENV_NAMESTtokenNr   api_keyF)gateway.configr  r-   rR   rU   rV   )r_   r  r  r  r  s        r6   _platform_has_bot_credentialr  b  s     877777///tOWd339rE% %++-- toy$77=2G'3 GMMOO t5rB   z=^(?P<host>.+):(?P<container>/[^:]+?)(?::(?P<options>[^:]+))?$z/outputz/outputsrZ  r[  r^  terminalbackendTERMINAL_ENVcwdTERMINAL_CWDtimeoutTERMINAL_TIMEOUT	home_modeTERMINAL_HOME_MODElifetime_secondsTERMINAL_LIFETIME_SECONDSdocker_imageTERMINAL_DOCKER_IMAGEdocker_forward_envTERMINAL_DOCKER_FORWARD_ENVsingularity_imageTERMINAL_SINGULARITY_IMAGEmodal_imageTERMINAL_MODAL_IMAGEdaytona_imageTERMINAL_DAYTONA_IMAGEvercel_runtimeTERMINAL_VERCEL_RUNTIMEssh_hostTERMINAL_SSH_HOSTssh_userTERMINAL_SSH_USERssh_portTERMINAL_SSH_PORTssh_keyTERMINAL_SSH_KEYcontainer_cpuTERMINAL_CONTAINER_CPUcontainer_memoryTERMINAL_CONTAINER_MEMORYTERMINAL_CONTAINER_DISKTERMINAL_CONTAINER_PERSISTENTTERMINAL_DOCKER_VOLUMESTERMINAL_DOCKER_ENVTERMINAL_DOCKER_EXTRA_ARGSTERMINAL_DOCKER_SHM_SIZE&TERMINAL_DOCKER_MOUNT_CWD_TO_WORKSPACETERMINAL_DOCKER_NETWORK TERMINAL_DOCKER_RUN_AS_HOST_USER(TERMINAL_DOCKER_PERSIST_ACROSS_PROCESSESTERMINAL_DOCKER_ORPHAN_REAPERTERMINAL_SANDBOX_DIRTERMINAL_PERSISTENT_SHELL)container_diskcontainer_persistentdocker_volumes
docker_envdocker_extra_argsdocker_shm_sizedocker_mount_cwd_to_workspacedocker_networkdocker_run_as_host_userdocker_persist_across_processesdocker_orphan_reapersandbox_dirpersistent_shell>   r  autor   )_is_ssh_remote_tilde_cwd	auxiliary>   visionapprovalweb_extract)get_plugin_auxiliary_taskskeyprovidermodelbase_urlr  r  
AUXILIARY_	_PROVIDER_MODEL	_BASE_URL_API_KEYr`  ra  gateway_timeoutHERMES_AGENT_TIMEOUTgateway_timeout_warningHERMES_AGENT_TIMEOUT_WARNINGgateway_notify_intervalHERMES_AGENT_NOTIFY_INTERVALsession_stall_timeoutHERMES_SESSION_STALL_TIMEOUTrestart_drain_timeoutHERMES_RESTART_DRAIN_TIMEOUTgateway_auto_continue_freshnessHERMES_AUTO_CONTINUE_FRESHNESS%gateway_startup_restore_drain_timeoutrS  rb  rc  rd  re  rf  r"  busy_input_modeHERMES_GATEWAY_BUSY_INPUT_MODEbusy_text_modeHERMES_GATEWAY_BUSY_TEXT_MODEbusy_ack_enabledHERMES_GATEWAY_BUSY_ACK_ENABLEDbusy_steer_ack_enabled%HERMES_GATEWAY_BUSY_STEER_ACK_ENABLEDtimezoneHERMES_TIMEZONEsecurityredact_secretsHERMES_REDACT_SECRETSr1   strict0HERMES_MEDIA_DELIVERY_STRICTmedia_delivery_allow_dirsc              #   8   K   | ]}|t          |          V  d S r;   rU   r?   ps     r6   rA   rA   N  s.      5W5WUV5Wc!ff5W5W5W5W5W5WrB   HERMES_MEDIA_ALLOW_DIRStrust_recent_filesHERMES_MEDIA_TRUST_RECENT_FILEStrust_recent_files_seconds!HERMES_MEDIA_TRUST_RECENT_SECONDSplatform_connect_timeout'HERMES_GATEWAY_PLATFORM_CONNECT_TIMEOUTu.     Warning: config.yaml → env bridge failed: : )filezz  Gateway will fall back to .env values, which may not match your current config.yaml. Run `hermes doctor` to investigate.)apply_ipv4_preference_cfgnetwork
force_ipv4r   z/  Warning: IPv4 preference application failed: )print_config_warningsz%  Warning: config validation failed: )warn_deprecated_cwd_env_varsz%  Warning: deprecation check failed: HERMES_QUIETHERMES_EXEC_ASK)CWD_PLACEHOLDERS resolve_placeholder_terminal_cwdMESSAGING_CWDfalse>   rM   rO   rP   )configured_cwdterminal_backendmessaging_cwdr  home_fallback)ChannelOverrider  _BUILTIN_PLATFORM_VALUESr  r  _getenvr  )AsyncSessionStoreSessionEntrySessionStoreSessionSourceSessionContextbuild_session_contextbuild_session_context_promptbuild_channel_continuity_notebuild_session_keyis_shared_multi_user_session neutralize_untrusted_inline_text)DeliveryRouter#looks_like_telegram_private_chat_idresolve_delivery_transport)SessionTurnLeaseRegistry)SERVICE_TIER_UNSETSessionStatelegacy_dict_propertylegacy_lease_token_property)GatewayAuthorizationMixin)GatewayKanbanWatchersMixin)GatewaySlashCommandsMixin)TurnContext)	r  EphemeralReplyMessageEventMessageType_prefix_within_utf16_limit_reply_anchor_for_eventbuild_auto_tts_output_pathmerge_pending_message_event	utf16_len)DEFAULT_HEARTBEAT_INTERVAL_S_arm_loop_floor_timerarm_shutdown_watchdogloop_heartbeat_foreverresolve_shutdown_watchdog_delaystart_loop_liveness_watchdog)*DEFAULT_GATEWAY_RESTART_AFTER_TURN_TIMEOUT%DEFAULT_GATEWAY_RESTART_DRAIN_TIMEOUTGATEWAY_FATAL_CONFIG_EXIT_CODE!GATEWAY_SERVICE_RESTART_EXIT_CODE parse_restart_after_turn_timeoutparse_restart_drain_timeout)canonical_whatsapp_identifierexpand_whatsapp_aliasesnormalize_whatsapp_identifier)WECOM_DM_POLICYWECOM_GROUP_POLICYWECOM_ALLOW_ALL_USERS)WEIXIN_DM_POLICYWEIXIN_GROUP_POLICYWEIXIN_ALLOW_ALL_USERS)YUANBAO_DM_POLICYYUANBAO_GROUP_POLICYYUANBAO_ALLOW_ALL_USERS)NNQQ_ALLOW_ALL_USERS)WHATSAPP_DM_POLICYWHATSAPP_GROUP_POLICYWHATSAPP_ALLOW_ALL_USERSc                 .   t          | di                                           D ]o\  }}t          |dd          st                              |          }|s5|\  }}}t          |dd          pi }t	          |                    d          p|rt          |d          nd                                                                          }t	          |                    d          p|rt          |d          nd                                                                          }	|d	k    r|	d	k    rt          j	        d
d                                          dv }
|
p%|o#t          |d                                          dv }|re|j
         dc S dS )zFReturn a startup-abort reason when open policy lacks allow-all opt-in.r#  r  Fr  N	dm_policypairinggroup_policyopenGATEWAY_ALLOW_ALL_USERSr   >   rM   rO   rP   z&: open policy without allow-all opt-in)r-   r  _OWN_POLICY_OPEN_ENVrT   rU   r!  rV   rW   rq   r  r   )rX   r_   r  open_envdm_env	group_envallow_all_envr  r^  r`  gateway_allow_allplatform_opted_ins               r6   "_own_policy_open_startup_violationrj  	  s   %,V["%E%E%K%K%M%M I I!/	599 	'++H55 	+3(	=$77=2IIk"" E.4C	***)
 
 %''%%'' 	 IIn%% K1:I	9---	
 
 %''%%'' 	 <6#9#9I%r
 

%'')* . 
 Kr**00226JJ 	  	.HHHHHH4rB   )	_session_model_overrides _pending_one_turn_model_restores_session_reasoning_overrides_session_service_tier_overrides_pending_model_notes_last_resolved_model_queued_events_session_stall_notified_pending_turn_sidecar_notes_CONVERSATION_SCOPED_STATEc                     ddl m} m}m} ddlm}m} 	  |             }n# |$ rw} ||          rt                              d|           nt                              d|           t                      }||cY d}~S t           ||                    |d}~wt          $ r}t           ||                    |d}~ww xY w |            }	d}
t          j                            d          }|r*	 t          |          }
nZ# t           t"          f$ r d}
Y nEw xY wt%          |	t&                    r,|	                    d          }t%          |t                    r|}
|
2|                    d	          }t%          |t                    r|dk    r|}
|                    d
          |                    d          |                    d          |                    d          |                    d          |                    d          t)          |                    d          pg           |                    d          |
d	S )u5  Resolve provider credentials for gateway-created AIAgent instances.

    Provider is read from ``config.yaml`` ``model.provider`` (the single
    source of truth). ``resolve_runtime_provider()`` falls through to env
    var lookups internally for legacy compatibility, but the gateway does
    not consult environment variables for behavioral config — config.yaml
    is authoritative.

    If the primary provider fails with an authentication error, attempt to
    resolve credentials using the fallback provider chain from config.yaml
    before giving up.
    r   )resolve_runtime_providerformat_runtime_provider_error_get_model_config)	AuthErroris_rate_limited_auth_erroru;   Primary provider rate-limited (429): %s — trying fallbacku4   Primary provider auth failed: %s — trying fallbackNHERMES_MAX_TOKENS
max_tokensmax_output_tokensr  r  r  requested_providerapi_moder   argscredential_pool	r  r  r  r~  r  r   r  r  r|  )hermes_cli.runtime_providerrv  rw  rx  hermes_cli.authry  rz  r/   r   _try_resolve_fallback_providerRuntimeErrorr.   rq   rr   rT   rF  rH  rU  rR   rS   r  )rv  rw  rx  ry  rz  runtimeauth_exc	fb_configr5   	model_cfgr|  _env_mtr  _runtime_mots                 r6   _resolve_runtime_agent_kwargsr  X	  s            
 FEEEEEEEH**,, R R R
 &%h// 	]NNXZbccccNNQS[\\\244	 88BBCCQ H H H88==>>CGH "!##IJjnn011G 	WJJI& 	 	 	JJJ		It	$	$ ]]<((b# 	J {{#677lC(( 	&\A-=-=%J ;;y))KK
++KK
++%kk*>??KK
++;;y))W[[((.B//";;'899 
 
 
s?   
 CAB7C=BC#B<<C2D DDc                    ddl m}m} 	  ||           }n+# t          $ r}t	           ||                    |d}~ww xY w|                    d          |                    d          |                    d          |                    d          |                    d	          |                    d
          t          |                    d          pg           |                    d          dS )zQResolve runtime credentials for a specific provider (e.g. from channel override).r   )rv  rw  )	requestedNr  r  r  r~  r  r   r  r  )r  r  r  r~  r  r   r  r  )r  rv  rw  r.   r  rT   r  )r  rv  rw  r  r5   s        r6   *_resolve_runtime_agent_kwargs_for_providerr  	  s          H**X>>> H H H88==>>CGH ;;y))KK
++KK
++%kk*>??KK
++;;y))W[[((.B//";;'899	 	 	s    
?:?c                 ,   | r!t          |                                           sdS 	 t          t          |                                                                         d          S # t          $ r! t
                              d| d           Y dS w xY w)zJReturn the live credential pool for a provider id (e.g. ``custom:hyper``).Nr  z1Failed to resolve credential pool for provider=%sTr   )rU   rV   r  rT   r.   r/   r0   )r  s    r6   _credential_pool_for_providerr  	  s     3x==..00 t
9#h--:M:M:O:OPPTT
 
 	
    ? 	 	
 	
 	

 tts   A A( ('BBc                     ddl m}  	 t                      }t          |          }|sdS |D ]}	 ddlm}  | |                    d          |                    d           ||                    }t                              d|                    d          p|                    d          |                    d	                     |                    d
          |                    d          |                    d          |                    d          |                    d          |                    d          t          |                    d          pg           |                    d          |                    d	          d	c S # t          $ r:}t                              d|                    d          |           Y d}~d}~ww xY wn# t          $ r Y nw xY wdS )zQAttempt to resolve credentials from the fallback_model/fallback_providers config.r   )rv  N)resolve_entry_api_keyr  r  )r  explicit_base_urlexplicit_api_keyz'Fallback provider resolved: %s model=%sr  r  r~  r  r   r  r  )	r  r  r  r~  r  r   r  r  r  zFallback entry %s failed: %s)r  rv  _load_gateway_runtime_configr   hermes_cli.fallback_configr  rT   r/   infor  r.   r0   )rv  rk  fb_listr  r  r  fb_excs          r6   r  r  	  s!   DDDDDD) +,,$S)) 	4 	 	ELLLLLL22#ii
33&+ii
&;&;%:%:5%A%A   =IIj))DW[[-D-DIIg&&    '{{955 'J 7 7 'J 7 7*1++6J*K*K 'J 7 7&{{955 V!4!4!:;;'.{{3D'E'E"YYw//
 
 
 
 
    ;UYYz=R=RTZ[[[;	@    4s@   G G EFG 
G/G
G GG 
G&%G&indexc                 b    t          | dd          pg }|t          |          k     r||         ndS )zReturn the per-attachment MIME for the attachment at *index*.

    Empty string when the platform didn't populate a per-file MIME for
    that slot (some adapters only set a message-level type).
    media_typesNr   )r-   r   )eventr  r  s      r6   _event_media_type_atr  	  s<     %55;K!&[)9)9!9!9;urArB   c                     t          | |          }|r|                    d          S t          | dd          t          j        k    S )a  True if the attachment at *index* is an image.

    Trust the per-attachment MIME when present. Only fall back to the
    message-level ``PHOTO`` type when this attachment's MIME is unknown --
    otherwise a document (or any non-image) uploaded alongside an image in
    the same message gets mis-routed as an image, base64'd into a vision
    content part, and the provider 400s ("Could not process image").
    image/message_typeN)r  r   r-   r;  PHOTOr  r  mtypes      r6   _event_media_is_imager   
  sI     !..E *)))5.$//;3DDDrB   c                     t          | |          }|r|                    d          S t          | dd          t          j        t          j        hv S )zGTrue if the attachment at *index* is audio (per-attachment MIME first).audio/r  N)r  r   r-   r;  VOICEAUDIOr  s      r6   _event_media_is_audior  
  sO     ..E *)))5.$//K4E{GX3YYYrB   c                     t          | dd          }|t          j        t          j        hv rdS |t          j        k    p"t          | |                              d          S )zFTrue when an audio attachment should enter the automatic STT pipeline.r  NFr  )r-   r;  r  DOCUMENTr  r  r   )r  r  r  s      r6   _event_media_is_stt_inputr  
  s_    5.$77L);+?@@@u)) 	Cu--88BBrB   c                     t          | |          }|r|                    d          S t          | dd          t          j        k    S )zGTrue if the attachment at *index* is video (per-attachment MIME first).video/r  N)r  r   r-   r;  VIDEOr  s      r6   _event_media_is_videor  "
  sG     ..E *)))5.$//;3DDDrB   c                    g }t          | dd          pg }t          |          D ]\  }}t          | |          r|                    d| d           /t	          | |          r|                    d| d           Yt          | |          r|                    d| d           |                    d| d           d                    |          S )	ag  Build a text placeholder for media-only events so they aren't dropped.

    When a photo/document is queued during active processing and later
    dequeued, only .text is extracted.  If the event has no caption,
    the media would be silently lost.  This builds a placeholder that
    the vision enrichment pipeline will replace with a real description.
    
media_urlsNz[User sent an image: ro  z[User sent audio: z[User sent a video: z[User sent a file: r   )r-   	enumerater  rs   r  r  rD   )r  rE   r  iurls        r6   _build_media_placeholderr  *
  s    Ed339rJJ'' 7 73 ** 	7LL77778888"5!,, 	7LL4c4445555"5!,, 	7LL66667777LL5s555666699UrB   display_name
agent_pathr  c                 P    |                     d          r	d|  d| dS d|  d| dS )uf  Context note prepended to a user turn when they attach a document.

    Text documents (``text/*``) have their content inlined upstream by the
    platform adapter, so the note just confirms that and records the path.

    Binary documents (PDF, DOCX, XLSX, …) cannot be inlined as text. The note
    must tell the agent to *extract* the text itself before answering — earlier
    wording ("Ask the user what they'd like you to do with it") steered the
    model into punting back to the user, which is why attached PDFs/DOCX looked
    "unreadable" to the agent even though it has the tools to read them.
    ztext/z![The user sent a text document: 'zC'. Its content has been included below. The file is also saved at: ro  z[The user sent a document: ''. It is saved at: u
  . Its text is not inlined here (it's a binary format such as PDF or DOCX). To read it, extract the document's text yourself — for example with the terminal tool or the ocr-and-documents skill — before answering, instead of asking the user to paste the contents.])r   )r  r  r  s      r6   _build_document_context_noter  @
  si        
8 8 8*48 8 8	
	6| 	6 	6
 	6 	6 	6rB   secondsc                     t          t          |                     }|dk     rd}t          |d          \  }}t          |d          \  }}|r| d|dd|dS | d|dS )Nr   rB  <   r  02d)rF  rounddivmod)r  totalhoursremminutessecss         r6   _format_durationr  [
  s    gEqyyt$$JE33OOMGT 322'2222222""""""rB   rx   c                 J   K   t           j                                       d                                         }|dk    rG	 dt          f fd}t          j        |           d{V }t          |          S # t          $ r Y nw xY w|dv rG	 dt          f fd}t          j        |           d{V }t          |          S # t          $ r Y nw xY w	 t          j	        dd	d
dddd t
          j
        j        t
          j
        j        
  
         d{V }t          j        |                                d           d{V \  }}|j        dk    r@t          t	          |                                                                                    S n# t          $ r Y nw xY wdS )zSBest-effort duration probe. Returns formatted MM:SS / HH:MM:SS, or None on failure.rk   z.wavr'   c                      dd l } |                     d          5 }|                                }|                                pd}|t	          |          z  cd d d            S # 1 swxY w Y   d S )Nr   rbrk   )wavera  
getnframesgetframeraterG  )r  wfframesraterx   s       r6   _wav_durationz,_probe_audio_duration.<locals>._wav_durationl
  s    YYtT** 0b]]__F??,,1D!E$KK/0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0s   <A%%A),A)N)z.oggz.opusz.ogac                  T    ddl m}  t           |           j        j                  S )Nr   )OggOpus)mutagen.oggopusr  rG  r  length)r  rx   s    r6   _ogg_durationz,_probe_audio_duration.<locals>._ogg_durationy
  s1    333333WWT]]/6777rB   ffprobe-verrorz-show_entrieszformat=durationz-ofz"default=noprint_wrappers=1:nokey=1)stdoutstderrr#   r  r   )rq   rx   splitextrW   rG  asyncio	to_threadr  r.   create_subprocess_exec
subprocessPIPEwait_forcommunicate
returncodedecoderV   )rx   extr  r  r  procr  r  s   `       r6   _probe_audio_durationr  f
  s7     
'

4
 
 
#
)
)
+
+C
f}}
	05 0 0 0 0 0 0 !*=99999999D#D))) 	 	 	D	 '''	85 8 8 8 8 8 8 !*=99999999D#D))) 	 	 	D	
3tWo7H7%*73E3J
 
 
 
 
 
 
 
 

 "*4+;+;+=+=sKKKKKKKKK	?a#E&--//*?*?*A*A$B$BCCC      4s7   5A8 8
BB5C 
CCB=F 
F F session_keyc                 ,    |                      |          S )zConsume and return the full pending event for a session.

    Queued follow-ups must preserve their media metadata so they can re-enter
    the normal image/STT/document preprocessing path instead of being reduced
    to a placeholder string.
    )get_pending_message)r  r  s     r6   _dequeue_pending_eventr  
  s     &&{333rB   zStop requestedzSession reset requestedz Execution timed out (inactivity)zSSE client disconnectedzGateway shutting downzGateway restarting)is_still_currenttask_idsourcer  c                   | sdS |X	  |            st                               d| |           dS n.# t          $ r! t                               d| |d           Y nw xY wddlm} 	 |                    | ||          }n/# t          $ r" t                               d	| |d           Y dS w xY w|rt                               d
|| |           |S )u  Reap only background processes created by one abandoned turn.

    ``task_id`` is session-scoped (task_id == session_id), not turn-scoped,
    so a *replacement* turn on the same session can start and spawn its own
    legitimate process while this reap is still in flight. ``is_still_current``
    — a closure over the run_generation captured when the reaping turn began
    or was interrupted — lets the caller detect that a newer turn has since
    claimed the session and bail out instead of killing that newer turn's
    process. The newer turn snapshots its own baseline independently, so
    skipping here does not leave anything permanently unreaped.
    r   NzdSkipping reap for turn %s (%s): a newer turn already claimed this session; it owns its own baseline.z>is_still_current check failed for turn %s (%s); reaping anywayTr   process_registryr  z4Failed to reap background processes for turn %s (%s)zBReaped %d background process(es) created by abandoned turn %s (%s))r/   r0   r.   tools.process_registryr  kill_started_sincer   )r  process_baseliner  r  r  killeds         r6   _reap_gateway_turn_processesr  
  sk   $   q#	##%% F	   q  	 	 	LLP	      	 877777!44 5 
 

    
 	B	 	 	
 	
 	
 qq  
P		
 	
 	
 Ms!   &1 (AA&A? ?(B+*B+worker_donetimeout_firedcleanup_lockc                    |5  |                                 s|                                 r	 ddd           dS |                                 ddd           n# 1 swxY w Y   | r| d         nd}|C	 t          |t                     n,# t          $ r t
                              dd           Y nw xY w	 t          ||d|           n-# t          $ r  t
                              d	|d           Y nw xY wdS )
z@Interrupt one timed-out turn and reap only processes it created.NFr   z Timed-out agent interrupt failedTr   gateway_turn_timeoutr  r  z9Failed to reap background processes for timed-out turn %s)	is_setrt   r   _INTERRUPT_REASON_TIMEOUTr.   r/   r0   r  r   )agent_holderr  r  r  r  r  r  r   s           r6   _abandon_timed_out_gateway_turnr  
  s    
   	=#7#7#9#9 	        	              
  ,5LOOE	L"5*CDDDD 	L 	L 	LLL;dLKKKKK	L
$)-		
 	
 	
 	
 	
  
 
 
G 	 	
 	
 	
 	
 	

 4s:   *AAA!A4B
 
&B32B37C 'C54C5)poll_intervalr  r  c        	   	      V   |                     t          d|                    s| r| d         nd}	|	t          |	d          sB	 t          |	                                                    dd                    }
n# t          $ r Y w xY w|
|k     rt          | ||||||           dS dS )zFThread watchdog that remains runnable when gateway asyncio is starved.g{Gz?r   Nget_activity_summaryseconds_since_activity        r  r  r  r  r  r  r  )waitmaxr   rG  r	  rT   r.   r  )r  r  r  r  r  r  r  r  r  r   idle_secondss              r6   _watch_gateway_turn_inactivityr    s     s47788 #/9QT=/E F F=	 **,,001I3OO LL  	 	 	H	'!!'%-#'%-	
 	
 	
 	
 	+ s   5A: :
BBc                     | sdS d                     t          |                                                                                                                     }|t
          v S )z?Return True when an interrupt message is internal control flow.Frn  )rD   rU   rV   rC   rW   _CONTROL_INTERRUPT_MESSAGES)r  
normalizeds     r6   _is_control_interrupt_messager  A  sV     u#g,,,,..446677==??J444rB   skill_mdc                    	 |                      dd          }n# t          $ r Y dS w xY w|                    d          }|                    d          sdS |                    dd          }|d	k     rdS d
}|d|                                         D ]}|                                }|                    d          r}|                    dd          d                                         }t          |          dk    r&|d	         |d         k    r|d	         dv r
|dd         }|                                } n|sdS |	                                
                    dd          
                    dd          }d	d
l}|                    dd|          }|                    dd|                              d          }|sd
|fS ||fS )u  Derive the /command slug and declared frontmatter name from a SKILL.md.

    Matches the exact normalization used by
    :func:`agent.skill_commands.scan_skill_commands` so the slug here is the
    same string a user types after the leading ``/`` (e.g. a skill with
    frontmatter ``name: Stable Diffusion Image Generation`` resolves to
    ``stable-diffusion-image-generation`` — NOT the parent directory name,
    which is commonly shorter/different, e.g. ``stable-diffusion``).

    Using the directory name silently broke :func:`_check_unavailable_skill`
    for every skill whose directory name drifted from its frontmatter name
    (19 such skills on a standard install as of 2026-05), causing a generic
    "unknown command" response where a "disabled — enable with …" or
    "not installed — install with …" hint was expected.

    Returns ``(slug, declared_name)`` or ``(None, None)`` when the file
    can't be read or lacks a ``name:`` in its frontmatter.
    utf-8rJ  )encodingerrorsNNu   ﻿z---z
---   r   Nzname:r  rk      r   >   "'rn  -r  z
[^a-z0-9-]r   z-{2,})	read_textr.   r  r   r  
splitlinesrV   rC   r   rW   rJ  r<   r   )r  r  r  declared_namelinerV  slug_res           r6   _skill_slug_from_frontmatterr&  I  s   &$$gi$HH   zznnX&&Ge$$ z
,,w
"
"C
Qwwz $M#))++  zz||??7## 	**S!$$Q'--//C3xx1}}Q3r7!2!2s1v7K7K!B$iIIKKME	  z  ((c22::3DDD77="d++D778S$''--c22D #]""s    
((command_namec                 \   |                                                      dd          }	 ddlm} ddlm}m}  |            } |            D ]f}|                                s|                    d          D ]9} ||          rt          |          \  }}	|r|	s%||k    r|	|v r
d|  dc c S :gdd	l
m}
 t          t                                                    j        j        } |
|d
z            }|                                r|                    d          D ]z} ||          rt          |          \  }}|s#||k    rQ|j                            |          }t#          |j                  }dd                    |           }d|  d| dc S {n# t(          $ r Y nw xY wdS )u  Check if a command matches a known-but-inactive skill.

    Returns a helpful message if the skill exists but is disabled or only
    available as an optional install. Returns None if no match found.

    The slug for each on-disk skill is derived from its frontmatter ``name:``
    (via :func:`_skill_slug_from_frontmatter`), NOT from its containing
    directory name — because the two can differ (e.g. directory
    ``stable-diffusion`` + frontmatter ``Stable Diffusion Image Generation``
    yields slug ``stable-diffusion-image-generation``). Matching on
    directory name would miss that slug entirely and fall through to the
    generic "unknown command" path.
    r  r  r   )_get_disabled_skill_names)get_all_skills_dirsis_excluded_skill_pathzSKILL.mdThe **zJ** skill is installed but disabled.
Enable it with: `hermes skills config`)get_optional_skills_dirzoptional-skillsz	official/r;  zQ** skill is available but not installed.
Install it with: `hermes skills install r   N)rW   rJ  tools.skills_toolr)  agent.skill_utilsr*  r+  rw   rglobr&  r  r-  r   rn   ro   rp   relative_tor  rE   rD   r.   )r'  r  r)  r*  r+  disabled
skills_dirr  r$  r"  r-  	repo_rootoptional_dir	_declaredrelrE   install_paths                    r6   _check_unavailable_skillr9  |  s    ##%%--c377J,??????QQQQQQQQ,,.. .-// 	 	J$$&& &,,Z88  ))(33 &B8&L&L#m =  :%%-8*C*CB B B B     	=<<<<<NN**,,3:	..y;L/LMM   	(..z::  ))(33 ">x"H"Hi :%%"/55lCCC OOE#@sxx#@#@LS S SCOS S S   &    4s   BF 1C(F F 
F)(F)c                 4    | t           j        k    rdn| j        S )uN   Map a Platform enum to its config.yaml key (LOCAL→"cli", rest→enum value).cli)r  LOCALr   rc   s    r6   _platform_config_keyr=    s    ..55HNBrB   c                      t                      } t          | ddg           }t          |t                    sdS d|v pd|v S )zAReturn True when the standalone Teams pipeline plugin is enabled.pluginsr  r(  Fteams_pipelinezteams-pipeline)rQ   r   rR   r  )rX   r  s     r6   _teams_pipeline_plugin_enabledrB    sP    !##FfiB???Ggt$$ uw&E*:g*EErB   c                  N    t                      } | rt          |           S t          S )z<Return the Hermes home that gateway config reads should use.)rH  r   r;  )overrides    r6   _gateway_config_homerE    s'    '))H H~~rB   c                     t                      } | dz  }i }d}	 ddlm}m} | |            k    r |            }d}n# t          $ r Y nw xY w|s	 |                                rEddl}t          |dd	          5 }|                    |          pi }ddd           n# 1 swxY w Y   n-# t          $ r  t          
                    d
|           i }Y nw xY w	 ddlm}  |j        t          |t                    r|ni           }n# t          $ r Y nw xY wt          |t                    si S 	 ddlm}	  |	|          }n# t          $ r Y nw xY w|S )u  Load and parse ~/.hermes/config.yaml, returning {} on any error.

    Uses the module-level ``_hermes_home`` (so tests that monkeypatch it
    still see their fixture) and shares the mtime-keyed raw-yaml cache
    from ``hermes_cli.config.read_raw_config`` when the paths match.

    Managed scope is overlaid on the result (via the shared helper) so the
    gateway honors administrator-pinned values — neither read_raw_config nor a
    direct yaml.safe_load carries the managed merge on its own. Fail-open.
    rZ  Fr   )get_config_pathread_raw_configTNrr  r  z%Could not load gateway config from %sr^  )_normalize_root_model_keys)rE  rg  rG  rH  r.   rw   yamlra  	safe_loadr/   r0   rh  r_  ri  rR   rS   rK  )
config_homerj  rV  used_canonicalrG  rH  rL  fr_  rK  s
             r6   rQ   rQ     s/    '((K-KCN
FFFFFFFF
 //++++!/##C!N     	!!## 2+sW=== 2..++1rC2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 	 	 	LL@+NNNCCC	,,,,,,1m1C9N9N2V##TVWW   c4   	@@@@@@((--   Jsi   "< 
A	A	*B) 9BB) B!!B) $B!%B) )'CC-D 
DD-D? ?
EEc                    t          | t                    r|                     di           ni }t          |t                    rd|i}nt          |t                    si }ddlm} |d         }|                    d|d                   |                    d|d                   |                    d|d                   |                    d|d                   dS )	a,  Translate gateway checkpoint config into ``AIAgent`` constructor args.

    The gateway reads raw YAML instead of ``load_config()``, so checkpoint
    defaults must be supplied here.  Keep legacy ``checkpoints: true`` configs
    working while giving every gateway-created agent the same limits.
    checkpointsr  r   )DEFAULT_CONFIGmax_snapshotsmax_total_size_mbmax_file_size_mb)checkpoints_enabledcheckpoint_max_snapshotscheckpoint_max_total_size_mbcheckpoint_max_file_size_mb)rR   rS   rT   r   rg  rS  )rX   cp_cfgrS  defaultss       r6   _checkpoint_agent_kwargsr]    s     /9.F.FNVZZr***BF&$ V$%% 000000m,H%zz)Xi5HII$*JJXo6%
 %
 )/

*=!>)
 )
 (.zz); <(
 (
  rB   c                      t                      } t          | t                    r| si S ddlm}  ||           }t          |t                    r|ni S )u  Load gateway config for runtime reads, expanding supported ``${VAR}`` refs.

    Runtime helpers should honor the same env-template expansion documented for
    ``config.yaml`` while still respecting tests that monkeypatch
    ``gateway.run._hermes_home``. Build on ``_load_gateway_config()`` rather
    than calling the canonical loader directly so both behaviors stay aligned.

    Expansion failures are intentionally NOT swallowed — silently returning
    the unexpanded dict would mask the very bug this helper exists to fix.
    r   r\  )rQ   rR   rS   rg  r\  )rk  r\  expandeds      r6   r  r  -  sh     
 
 Cc4    	222222$$H!(D11988r9rB   c                    | | nt                      }|                    di           }t          |t                    r|S t          |t                    r,|                    d          p|                    d          pdS dS )u   Read model from config.yaml — single source of truth.

    Without this, temporary AIAgent instances (e.g. /compress) fall
    back to the hardcoded default which fails when the active provider is
    openai-codex.
    Nr  r(  r   )rQ   rT   rR   rU   rS   )rX   rk  r  s      r6   _resolve_gateway_modelrb  A  s     &&&,@,B,BC$$I)S!! H	It	$	$ H}}Y''G9==+A+AGRG2rB   	thread_id	parent_idrd  re  c                    g }t                      }| ||fD ]C}|st          |          }||v r|                    |           |                    |           D|S )zOrdered, de-duplicated keys for ``channel_overrides`` lookup.

    Matches ``resolve_channel_prompt`` semantics: exact thread/channel id first,
    then parent channel/forum id (Discord threads inherit parent overrides).
    )rt   rU   rv   rs   )r  rd  re  keysr   r  sks          r6   _channel_override_lookup_keysri  Q  so     DUUDI.   	XX::BKrB   c                    t          | dd          }|sdS |                    |          }|r|j        sdS |j        }t          |||          D ]}|                    |          }	|	|	c S dS )zReturn per-channel override for this platform/chat_id, or None.

    Looks up ``channel_overrides`` by ``chat_id``, then ``thread_id``, then
    ``parent_id`` (forum threads / child channels inherit the parent entry).
    r#  Nrc  )r-   rT   channel_overridesri  )
rX   r_   r  rd  re  r#  r  	overridesr  ovs
             r6   _get_channel_overridern  i  s     T22I tmmH--O /"C t1I,9	     ]]3>III 4rB   c                      ddl } |                     d          }|r|gS 	 ddl}|j                            d          t
          j        ddgS n# t          $ r Y nw xY wdS )us  Resolve the Hermes update command as argv parts.

    Tries in order:
    1. ``shutil.which("hermes")`` — standard PATH lookup
    2. ``sys.executable -m hermes_cli.main`` — fallback when Hermes is running
       from a venv/module invocation and the ``hermes`` shim is not on PATH

    Returns argv parts ready for quoting/joining, or ``None`` if neither works.
    r   Nhermesrh  z-mzhermes_cli.main)shutilwhichimportlib.utilutil	find_specrm   
executabler.   )rq  
hermes_bin	importlibs      r6   _resolve_hermes_binry    s     MMMh''J |>##L11=ND*;<< >    4s   ,A 
AAzdict | Nonec                 
   |                      d          }t          |          dk    rZ|d         dk    rN|d         dk    rB|d         |d         |d	         d
}t          |          dk    r|d         dv r|d         |d<   |S dS )a@  Parse a session key into its component parts.

    Session keys follow the format
    ``agent:main:{platform}:{chat_type}:{chat_id}[:{extra}...]``.
    Returns a dict with ``platform``, ``chat_type``, ``chat_id``, and
    optionally ``thread_id`` keys, or None if the key doesn't match.

    The 6th element is only returned as ``thread_id`` for chat types where
    it is unambiguous (``dm`` and ``thread``).  For group/channel sessions
    the suffix may be a user_id (per-user isolation) rather than a
    thread_id, so we leave ``thread_id`` out to avoid mis-routing.
    r     r   r   rk   mainr  r  r   )r_   	chat_typer  >   dmthreadrd  N)rC   r   )r  rE   results      r6   _parse_session_keyr    s     c""E
5zzQ58w..58v3E3EaqQx
 

 u::>>eAh*:::"'(F;4rB   evtc                    |                      dd          }|                      dd          }|                      dd          }|dk    rd|                      dd	           d
S |dk    rb|                      dd          }|                      dd	          }|                      dd          }d| d| d| d| }|r	|d| dz  }|d
z  }|S |dk    rddlm}  ||           S dS )zOFormat a watch pattern event from completion_queue into a [IMPORTANT:] message.r   
completionr%   unknownr   watch_disabledz[IMPORTANT: r  r   ro  watch_matchr   ?output
suppressedr   z[IMPORTANT: Background process z matched watch pattern "z".
Command: z
Matched output:
z
(z/ earlier matches were suppressed by rate limit)async_delegation)format_process_notificationN)rT   r  r  )	r  evt_type_sid_cmd_pat_out_supr   r  s	            r6   $_format_gateway_process_notificationr    sL   wwv|,,H77<++D779i((D###7cggi447777=  wwy#&&wwx$$ww|Q'''d ' '#' '' ' !%' ' 	  	PO$OOOOD%%%FFFFFF**3///4rB   
list[dict]c                 t   g }g }|                                  s	 |                                 }n# t          $ r Y ncw xY w|                    dd          }|dv r|                    |           n|dk    r|                    |           |                                  |D ]}|                     |           |S )a  Drain gateway-owned watch events without spinning on requeued events.

    Watch events are handled by the post-turn gateway drain. Process
    completions are owned by their per-process watcher task, and async
    delegation completions are owned by ``_async_delegation_watcher``.
    Requeueing async events inside ``while not queue.empty()`` would make the
    loop non-terminating, so detach the current batch first, then requeue any
    events this drain does not own after the queue is empty.
    r   r  >   r  r  r  )empty
get_nowaitr.   rT   rs   put)completion_queuewatch_eventsrequeuer  r  s        r6   _drain_gateway_watch_eventsr    s      "LG$$&& 	 	"--//CC 	 	 	E	776<00888$$$$+++NN3 $$&& 	   " "S!!!!s   / 
<<c                      d S r;   r,  r,  rB   r6   r   r     s    D rB   _gateway_runner_refhistory_lenagent_resultresponser  c                   |r|S |                      d          r||                      dd          }t          |                                          t          fddD                       p	dv o|dk    }|r	 dS d	t          |          d
d          dS t	          |                      dd          pd          }|                      d          r|dk    r	 dS |S |dk    rZt          |           rdS |                      d          r1|                      dd          }dt          |          d
d          dS 	 dS |dk    rB|                      d          s-|                      d          s|                      d          s	 dS |S )a>  Normalize empty/None agent responses into user-facing messages.

    Consolidates the existing ``failed`` handler and adds a catch-all for
    the case where the agent did work (api_calls > 0) but returned no text.
    Fix for #18765.

    Also surfaces a retry hint when the agent never ran at all
    (api_calls == 0) for a non-interrupted, non-failed turn -- this is the
    silent-drop pattern observed after ``/stop`` where the next user
    message hits a stale generation token and returns an empty result,
    leaving the platform with nothing to send. (#31884)
    failedr  unknown errorc              3       K   | ]}|v V  	d S r;   r,  )r?   r  	error_strs     r6   rA   z2_normalize_empty_agent_response.<locals>.<genexpr>  s;       !
 !
 N!
 !
 !
 !
 !
 !
rB   )r   r  z	too largeztoo longexceedr  4002   }   ⚠️ Session too large for the model's context window.
Use /compact to compress the conversation, or /reset to start fresh.zThe request failed: N,  2
Try again or use /reset to start a fresh session.	api_callsr   interrupteduo   ⚠️ Your message was interrupted before processing started (likely by a recent /stop). Please send it again.r   partialprocessing incompleteu   ⚠️ Processing stopped: r   z. Try again.u|   ⚠️ Processing completed but no response was generated. This may be a transient error — try sending your message again.uj   ⚠️ Your message wasn't processed (the previous turn was still being cleaned up). Please send it again.)rT   rU   rW   anyrF  ,_is_gateway_hidden_reasoning_incomplete_turn)r  r  r  error_detailis_context_failurer  errr  s          @r6   _normalize_empty_agent_responser    s+   $  !! 
#''AA%%++--	  !
 !
 !
 !
W!
 !
 !
 
 
 7 y 5[2%5 	  	) @3|#4#4TcT#: @ @ @	

 L$$[!449::I&&  >>D  1}}7EE 	2I&& 	N""7,CDDCMS$3$MMMMP	
 	
 	Q  // 	  ** 	   ++ 	7	
 	

 OrB   c                    t          | t                    sdS |                     d          s|                     d          rdS |                     d          sdS t          |                     dd          pd                                          }d|                                vrdS t          |                     d          pd                                          }| p||k    S )	uJ  Detect retry-exhausted turns with hidden reasoning but no visible answer.

    The conversation loop returns the retry-exhaustion sentinel as BOTH
    ``final_response`` and ``error`` ("Codex response remained incomplete
    after 3 continuation attempts"), so ``final_response`` being non-empty
    does not mean the model produced a visible answer. Treat the turn as
    hidden when the error sentinel is present and ``final_response`` is
    either empty or merely echoes that sentinel — any genuinely different
    final text means the model DID answer and must be delivered.
    Fr  r  r  r  r   zremained incomplete afterfinal_response)rR   rS   rT   rU   rV   rW   )r  
error_textr  s      r6   r  r  S  s     lD)) u!! \%5%5m%D%D uI&& u\%%gr228b99??AAJ"**:*:*<*<<<u))*:;;ArBBHHJJN=:!==rB   c                    t          | t                    sdS |                     d          rdS |                     d          s*|                     d          s|                     d          rdS |                     d          du rdS dS )a  Return True only when a gateway turn really completed successfully.

    Restart recovery uses ``resume_pending`` as a durable marker for sessions
    interrupted during gateway drain.  A soft interrupt can still bubble out as
    a syntactically normal agent result with an empty final response; clearing
    the marker in that case loses the recovery signal and startup auto-resume
    has nothing to schedule.
    Fr  r  r  r  	completedTr$  )r  s    r6   '_should_clear_resume_pending_after_turnr  k  s     lD)) u&& u!! \%5%5i%@%@ LDTDTU\D]D] u$$--u4rB   current_resultfollowup_resultc                 F   t          |t                    s|S t          | t                    s|S |                     d          }|                    d          }t          |t                    s|S t          |t                    r||k    r|S t          |          }||d<   |S )ae  Carry the outer history offset through queued follow-up drains.

    ``_process_message_background()`` persists transcript rows only once, after the
    entire in-band queued-follow-up chain returns.  Each recursive ``_run_agent()``
    call advances ``history_offset`` to the history it received, so without
    correction the outermost persistence step sees only the *last* queued turn as
    "new" and silently drops earlier turns from the same drain chain.

    Preserve the earliest (outermost) history offset so the final transcript slice
    still includes every queued turn that ran during the chain.
    r  )rR   rS   rT   rF  )r  r  current_offsetfollowup_offsetr   s        r6   (_preserve_queued_followup_history_offsetr    s     ot,, nd++ #''(899N%))*:;;Onc** /3'' O~,M,M/""F-FMrB   r  BasePlatformAdapter | Nonec                    K   | dS 	 |                                   d{V  dS # t          $ rB t                              dt	          | dt          |           j                  d           Y dS w xY w)uT  Best-effort dispose for an adapter that never made it onto ``self.adapters``.

    The reconnect watcher in ``GatewayRunner._platform_reconnect_watcher``
    constructs a fresh adapter on every retry attempt. When the connect
    call fails — for any of the three reasons (non-retryable error,
    retryable error, exception during connect) — the adapter is dropped
    without ever being installed, so nothing else will call its
    ``disconnect()``. Any resources the adapter opened in ``__init__``
    (e.g. ``APIServerAdapter`` opens a SQLite ``ResponseStore`` that
    holds 2 fds — the db file and its WAL sidecar) stay open until
    garbage collection sweeps the unreachable object, which Python's
    cyclic GC does not do promptly for asyncio-bound objects with
    native handles. The cumulative leak is 2 fds × every retry at the
    300s backoff cap ≈ 12 fds/hour, and the default 2560-fd ulimit
    is exhausted in ~12h of continuous failure, after which every
    open() call on the gateway raises ``OSError: [Errno 24] Too many
    open files`` and the gateway becomes a zombie (#37011).

    This helper centralises the dispose-with-suppression so the three
    failure paths in the reconnect watcher can all call it without
    each one having to know that ``disconnect()`` may itself raise
    on a half-constructed adapter.

    ``adapter`` may be ``None``: the reconnect watcher initialises
    ``adapter = None`` before the ``try`` so the ``except Exception``
    arm can dispose a half-constructed object, and also early-returns
    here when ``_create_adapter()`` returned ``None``.
    Nz,Adapter dispose raised on unowned adapter %rr   Tr   )
disconnectr.   r/   r0   r-   r   r   r  s    r6   _dispose_unused_adapterr    s      : 
  """"""""""" 
 
 
 	:GVT']]%;<< 	 	
 	
 	
 	
 	
 	

s   $ AA0/A0r  attemptc                 >    t          dd| dz
  z  z  t                    S )zCExponential reconnect backoff: 30s, 60s, 120s, ... capped at 5 min.   r  rk   )min_RECONNECT_BACKOFF_CAP)r  s    r6   _reconnect_backoffr    s!    rQ7Q;'(*@AAArB   c            	           e Zd ZdZdddeddfdZdded	ed
edefdZd Z	d Z
dededdfdZdededdfdZdededdfdZd ZdS )
TurnRunnera   Per-turn collaborator carrying the tool-progress callbacks that used to
    be nested closures inside ``GatewayRunner._run_agent_inner``.

    The bodies are byte-identical to the original closures modulo
    ``local_name`` -> ``ctx.field`` rewrites (closed-over locals now travel on
    the shared :class:`gateway.turn_context.TurnContext`) and ``self`` ->
    ``self._runner`` (the owning :class:`GatewayRunner`). Module-global
    references (logger, cfg_get, BasePlatformAdapter, ...) resolve in this
    same module exactly as before.
    runnerGatewayRunnerctxr'   Nc                 "    || _         || _        d S r;   )_runner_ctx)selfr  r  s      r6   __init__zTurnRunner.__init__  s    			rB   r  r  previewr  c                    | j         }|j        |j        dk    r|dk    r	 |dk    r[|rY|                                rEddlm}  |||j        dk    r|nd          }|j                            |j        j        |           n+|dk    r%|j                            |j        j        d           n2# t          $ r%}	t                              d	|	           Y d}	~	nd}	~	ww xY w|j        {|dk    rl|rj|dk    rdt          j                                        d
          }
|rd| dnd}|j                            |
 d| d|                                            |j        sdS |j        r|                                sdS |dk    r|j        d         s	 |                    d          pd}||j        k    r|j        dk    rddlm}m}m}m} t9                      }t;          t=          |dd          d          }|rL |||          s@d|j        d<   |j                             |                        |t>          dz  |           n2# t          $ r%}t                              d|           Y d}~nd}~ww xY wdS |dk    s|dk    r:|j         sdS |dk    r|n|}|rd| nd}|r|j                            |           dS |j!        sdS |dvrdS |dk    rdS 	 |j"        r|j"        d         nd}|tG          |dd          rdS n# t          $ r Y nw xY w|j        dk    r||j$        d         k    rdS ||j$        d<   ddlm%}  ||d           }d}d}	 | j&        '                    |j                  }n# t          $ r d}Y nw xY wtG          |d!d          r|d"k    rtQ          |tR                    rtQ          |                    d#          tT                    r|d#         +                                rdd$lm,} |d#                                         }|j-        d         rdn| d%| d&}| d'| d(} |            }|dk    r|nd)} |.                                }!|!r|!d         n|}"t_          |!          d*k    }#t_          |"          | k    r|"d| d+z
           d,z   }"n|#r|"d-z   }"| d'|" d(}|j        d.k    r|&d|j-        d<   |j                            |           dS d|j-        d<   |rdd$lm,}  |            }ta          j1        |dtT          /          }$|dk    r#t_          |$          |k    r|$d|d+z
           d,z   }$| d%| d0te          |3                                           d1|$ }n|r| d%| d2| d}n| d%| d,}|j                            |           dS ||}d|j-        d<   n|rdd3lm,}m4}%m5}&m6}'m7}(  |            }|dk    r|nd)}  |&|||| 4          })||8                    |)          }n|)j9        } |%|          }*|*r( |(|          r| d%|* }n | d%|*  |'|           | }n| d%| d2| d}d|j-        d<   n| d%| d,}d|j-        d<   ||j:        d         k    r?|j;        dxx         d*z  cc<   |j                            d5||j;        d         f           dS ||j:        d<   d|j;        d<   |j                            |           dS )6z3Callback invoked by agent on tool lifecycle events.Noff	_thinkingtool.startedr   )build_status_phrasefullztool.completedzlive status update failed: %sz%Y-%m-%d %H:%M:%Sz "r  r   z  r  durationall)TOOL_PROGRESS_FLAGis_seen	mark_seentool_progress_hint_gatewayr"  tool_progress_commandFr@  TrZ  z(tool-progress onboarding hint failed: %su   💬 >   r  clarifyis_interruptednew)get_tool_emojiu   ⚙️supports_code_blocksr  r   )get_tool_preview_max_lenrn  r   ```

```(   rk   r  r   z ...verbose)ensure_asciir(  (z)
z: ")r  get_tool_verbprepare_tool_previewtool_verb_connectorverb_drops_preview)fallbackmax_len	__dedup__)<r  _live_status_adapter_live_status_mode_run_still_currentagent.displayr  set_status_textr  r  r.   r/   r0   	log_queuer   ra  strftimer  r  progress_queuelong_tool_hint_firedrT   _LONG_TOOL_THRESHOLD_Sprogress_modeagent.onboardingr  r  r  r  rQ   rJ  r   r;  _thinking_enabledtool_progress_enabledr  r-   	last_toolr  r  _adapter_for_sourcerR   rS   rU   rV   r  last_was_terminal_blockr!  r   r  dumpsr  rg  r  r  r  r  format_tool_previewr   last_progress_msgrepeat_count)+r  r  r  r  r  kwargsr  r  _phrase_ls_errr  preview_strr  r  r  r  r  r  gate_on	_hint_errthinking_textr|  _agent_for_interruptr  emoji_code_block_full_code_block_short_progress_adapterr  	_cmd_full_block_header_pl_cap_lines
_cmd_short
_multilineargs_strr  r  r  r  _prepared_preview_verbs+                                              r6   progress_callbackzTurnRunner.progress_callback  s
   i $0%..[((G//I/#BXBXBZBZ/AAAAAA11! # 5 ? ?T G ,<<SZ=OQXYYYY#333 ,<<SZ=OQUVVV G G G<gFFFFFFFFG
 =$^++	+i;>V>V\^^,,-@AA18@o7oooob!!R"D"D9"D"D{"D"D"K"K"M"MNNN% ! 	)?)?)A)A 	F )))#2J12M)T!::j116Qs999c>OSX>X>X            011D-i1HII %  G  Twwt5G'H'H T6:03*../I/I/K/KLLL!	,">@RSSS T T TGSSSSSSSSTF $$	[(@(@( '0K'?'?GGYM-:D)-)))C ,"&&s+++F ( 	F ...F 	!!F	:=:J#T3#3A#6#6PT #/G$&65 5/  	 	 	D	 %%)s}Q7G*G*GF$a 	100000y(;;;   	% $ @ @ L L 	% 	% 	% $	% %'=uEE	IZ''4&& (488I..44 ( Y%%'' (
 ?>>>>>Y..00I
 1!4RU:R:RY:R:R:R  #0FFiFFF**,,C''33rD))++F&,;)JVqJ:%%'		2U:

 1'&0
#0 H Hz H H H 	))+15+A."&&'7888-2C'* 0BBBBBB..00:dLLL 77s8}}s22'q1E9HMMMMT$))++->->MM8MM 0;;;;;;;/////""3'''F (#C-1C'** $	3              +*,,C''33rD 4 4 	! ! ! !,+??@QRR+0 "M),,E <%%i00 V",,U,,CC"UUUU,?,?	,J,JUGUUCC;;;;;;;-2C'**++Y+++C-2C'*
 #'***Q1$ ""Kc6Fq6I#JKKKF#&a s#####sU   BB. .
C8CCB5I	 	
I8I33I8)L 
LLM7 7NNc           	         !K   | j         j        sd S | j                            j                  sd S t          t                    dd           }||t          j        u r_j        	                                sD	 j        
                                 n# t          $ r Y nw xY wj        	                                Dd S g  d !j        dk    d}d}t          t                    rj        nt          	 t!          t          dd          pd          }n# t          $ r d}Y nw xY wt          t                    r_	 t!                              j        j                  pd          }                    j        j                  n# t          $ r Y nw xY wt)          d||dk    rd	nd
z
            dj        rh	 t-          j        j                  j        }d|v p*t3          d |                                D                       n# t6          t8          f$ r dY nw xY wdt:          dt:          ffddt<          dt:          fddt<          dt<          t<                   ffdd.fddt:          ffddt>          f !fd}	 	                                  s_j        	                                sD	 j        
                                 n# t          $ r Y nw xY wj        	                                Dd S j        
                                }	 j!        rj!        d
         nd }|,t          |dd          rtE          j#        d
           d {V  n# t          $ r Y nw xY wt          |tH                    rBt          |          dk    r/|d
         dk    r#|\  }	}
} r|
 d|dz    d d<    r d         n|
}net          |tH                    r9t          |          dk    r&|d
         d k    rd !g  d j%        d
<   d
j&        d
<   |} '                    |            |             d {V rotQ          j)                    }tE          j#        d!           d {V                                   r,*                    j        j        j        "           d {V  tQ          j)                    }|||z
  z
  }|d
k    rtE          j#        |           d {V  \                                 sd S rQ!Nd#+                               } !|           d {V }|j,        st          |d$d%          pd%-                                }t          |d&d          r"t\          /                    d'j0                   d(|v sd)|v r4t\          1                    d*j0                   tQ          j)                    }nd2                    j        j        |j3        j        +           d {V }j4        rNt          |d,d          r=t          |dd           r,j5        '                    t;          |j6                             nƉrId#+                               }2                    j        j        |j3        j        +           d {V }n32                    j        j        |j3        j        +           d {V }|j,        rA|j6        r:|j6        !j4        r,j5        '                    t;          |j6                             tQ          j)                    }tE          j#        d!           d {V                                   r,*                    j        j        j        "           d {V  nE# tn          j8        $ r tE          j#        d!           d {V  Y ntD          j9        $ r j        	                                sW	 j        
                                }t          |tH                    rFt          |          dk    r3|d
         dk    r'|\  }	}
} r|
 d|dz    d d<    |             d {V  nt          |tH                    r}t          |          dk    rj|d
         d k    r^ |             d {V  r3 r1!r/            }	  !|           d {V  n# t          $ r Y nw xY wd !g  d j%        d
<   d
j&        d
<   n% '                    |            |             d {V  n# t          $ r Y nw xY wj        	                                Wr r!r |             d {V  r3 r1!r/            }	  !|           d {V  n# t          $ r Y nw xY wY d S t          $ r?}t\          :                    d-|           tE          j#        d           d {V  Y d }~nd }~ww xY wA)/Nedit_messageseparater  g      ?MAX_MESSAGE_LENGTH  rk   r    @   r   Fr   c              3   F   K   | ]}|j         t          j        j        u V  d S r;   kindinspect	ParameterVAR_KEYWORDr?   params     r6   rA   z4TurnRunner.send_progress_messages.<locals>.<genexpr>5  sC        ! 
g&7&CC     rB   
message_idr  c                    K   j         j        | |d}t          dd          rd|d<   r
j        |d<    j        di | d {V S )N)r  r4  r  REQUIRES_EDIT_FINALIZEFTfinalizer   r,  )r  r  r-   _progress_metadatar'  )r4  r  r  _edit_accepts_metadatar  r  s      r6   _edit_progress_messagezATurnRunner.send_progress_messages.<locals>._edit_progress_message=  s      :-(" F
 w 8%@@ *%)z"% <%(%;z"--77777777777rB   linesr'   c                 @    d                     d | D                       S )Nr   c              3   4   K   | ]}t          |          V  d S r;   r  )r?   r#  s     r6   rA   zLTurnRunner.send_progress_messages.<locals>._progress_text.<locals>.<genexpr>J  s(      994SYY999999rB   )rD   )r;  s    r6   _progress_textz9TurnRunner.send_progress_messages.<locals>._progress_textI  s#    99995999999rB   c                     g }g }| D ]=}||gz   }|r1  |                    k    r|                     |           |g};|}>|r|                     |           |S )z>Partition progress lines into platform-sized editable bubbles.)rs   )r;  groupsrf  r#  r.  _PROGRESS_TEXT_LIMIT_progress_len_fnr>  s        r6   _split_progress_groupszATurnRunner.send_progress_messages.<locals>._split_progress_groupsL  s    !#FG ( (#tf,	 (//y0I0IJJMaaaMM'***#fGG'GG 'g&&&MrB   c                     j         rPt          | dd          rAt          | dd           r2j                            t	          | j                             d S d S d S d S )Nr  Fr4  )_cleanup_progressr-   _cleanup_msg_idsrs   rU   r4  )r  r  s    r6   _track_progress_resultzATurnRunner.send_progress_messages.<locals>._track_progress_result[  s    %DFIu55D FL$77D
 $++C0A,B,BCCCCCD D D D D DrB   r   c                    K                        j        j        | j        j                   d {V } |           |S )Nr  r  reply_tor   )r  r  r  _progress_reply_tor8  )r   r  rG  r  r  s     r6   _send_progress_textz>TurnRunner.send_progress_messages.<locals>._send_progress_textc  sl      "<<
*//	 (        F #"6***MrB   c                    K   
r	sdS  
          } t          |           dk    rdS  | d                   }Q |           d{V }|j        s7t          |dd          r"t                              dj                   dS d	dS n& |           d{V }|j        r|j        r|j        | dd         D ]1}  |                     d{V }|j        r|j        r|j        2| d         
dS )	a  Start fresh editable progress bubbles before a bubble exceeds limit.

                Returns True when it delivered/split the current buffer, or when
                a transient edit failure left the buffer and message identity
                intact for a later retry.  In either case the caller should skip
                the normal send/edit path for this tick.
                Frk   r   N	retryableu>   [%s] Transient overflow edit failure — keeping can_edit=TrueTr   )r   r  r-   r/   r0   r   r4  )r@  
first_textr  r   r:  r>  rL  rC  r  can_editprogress_linesprogress_msg_ids       r6   !_roll_progress_overflow_if_neededzLTurnRunner.send_progress_messages.<locals>._roll_progress_overflow_if_neededm  s      "  u++N;;F6{{au'q	22J*55ozRRRRRRRR~ 	!v{E:: $\#L    $t$H 5	!  32:>>>>>>>>> 8f&7 8&,&7O 8 822>>%3H3HIIIIIIII> 8f&7 8&,&7O
 $BZN4rB   Tr  r  r  u    (×)r   	__reset__333333?r  r   r  r   rN  u5   [%s] Transient edit failure — keeping can_edit=Truefloodzretry afterz-[%s] Progress edit flood control, backing offrI  r  zProgress message error: %sr'   N);r  r  r  r	  r  r-   r   r  r'  r  r  r.   progress_groupingrR   message_len_fnr   rF  max_message_length_for_chatr  message_len_fn_for_chatr  r8  r/  	signature
parametersr  valuesrU  rH  rU   r  r   r  r  r  sleeptupler  r  rs   r,   	monotonicsend_typingrD   r  rW   r/   r0   r   r  r  rK  rE  rF  r4  queueEmptyCancelledErrorr  )"r  _adapter_edit_last_edit_ts_PROGRESS_EDIT_INTERVAL_raw_progress_limit_edit_paramsrS  rV  r  r  base_msgr   r|  _now
_remaining	full_textr  _err_flood_result_pending_texterA  r9  r:  rB  r>  rL  rC  rG  r  rP  r  rQ  rR  s"                        @@@@@@@@@@@@@r6   send_progress_messagesz!TurnRunner.send_progress_messages  s     i! 	F,223:>> 	F  W~tDD M5H5U$U$U(..00 &113333    E (..00 
 F(J6"% '#677G"" 	
	'"%gg7KT&R&R&ZVZ"["[ 	' 	' 	'"&	'
 g233 	&)77
8JKKSt' '# $+#B#B3:CU#V#V       #)<s)B)B22J 
  
 "'! 	/
/&01EFFQ,.   %1%8%8%:%:     '& z* / / /).&&&/
	8S 
	83 
	8 
	8 
	8 
	8 
	8 
	8 
	8 
	8	:$ 	:3 	: 	: 	: 	:	$ 	4: 	 	 	 	 	 	 	 		D 	D 	D 	D 	D 	D	C 	 	 	 	 	 	 	 	*	 *	 *	 *	 *	 *	 *	 *	 *	 *	 *	 *	 *	 *	X|	'{'--// !06688 "".99;;;;( " " "!E" "06688 "
 F(3355	BEBR+\3+;A+>+>X\(+7G,.>= =7 &mA.........     D c5)) /c#hh!mmA+@U@U),&Ax% K08-J-Jeai-J-J-Jr*0>L.,,HCCU++ /CA#a&KBWBW '+O%'N/3C)!,*+C$Q'C"))#...::<<<<<<<< $(N$4$4M!-,,,,,,,,,--// g%11#*2DsOe1fffffffff ~''4}8LM
>> "-
333333333--// F <P ; $		. 9 9I#9#9/9#U#UUUUUUUF!> "W ' < < BIIKK #6;>> %"LL W '   %"d??mt.C.C #KK O '   -1N,<,<MM',H.5ll$'J$6$'%(%;%(%;	 /; / / ) ) ) ) ) )  1W 'y% H HW !(|T J JW
  077M<T8U8UVVV $(IIn$=$=	'.||$'J$6$-%(%;%(%;	 (4 ( ( " " " " " " (/||$'J$6$'%(%;%(%;	 (4 ( ( " " " " " " ~ P&*; P*0*;0 P077F<M8N8NOOO $ 0 0 mC((((((((())++ c!--cj.@3Ka-bbbbbbbbb; ) ) )mC((((((((((() ' ' ',2244 !0;;==%c511 Fc#hh!mmAR]H]H]14.Ax- J8@5R5Reai5R5R5Rr 2&G&G&I&I I I I I I I I'U33 FCA#a&T_J_J_ #D"C"E"EEEEEEEE' )N ) )0>~0N0N!)*@*@R_*`*`$`$`$`$`$`$`$`$`'0 !) !) !)$(D!).2O-/N7;C1!423C,Q//*11#666"C"C"E"EEEEEEEE$   5 ,2244 :  > >? >;;=========  ?  .~ > >I44_iPPPPPPPPPP$    ' ' '91===mA&&&&&&&&&&&&&&'u|	'sN  B% %
B21B2 D( (D76D7AF 
F+*F+AH! !H76H7.-^' K6 5^' 6
L ^' L^' !^' ;AN  ?^'  
N
^' NB&^' 5B^' ;^' ^' B^' +G:^' ')g))g)=C	d)cd)
c'$d)&c''Ad)(g))
d63g)5d66Ag);fg)
fg)fg)!	g)*5g$$g)c                    | j         }|j        d         s|j        d         dS |                                sdS d|j        d<   | j        j                            t          j                  }|t          |d          sdS 	 t          |                    |j        d                   |j        t          d           dS # t          $ r&}t                              d|           Y d}~dS d}~ww xY w)z?tool_start_callback: speak a one-time ack in the voice channel.r   NTplay_ack_in_voicezvoice ack scheduling errorr/   log_messagezvoice ack schedule failed: %s)r  _voice_ack_fired_voice_ack_guildr  r  adaptersrT   r  DISCORDr   r   rv  _voice_ack_loopr/   r.   r0   )r  r  r  r  r  _adapter_ack_errs          r6   voice_ack_callbackzTurnRunner.voice_ack_callbackW  s   i" 	c&:1&=&EF%%'' 	F"&Q<(,,X-=>>785H#I#IF	D$**3+?+BCC#8	       	D 	D 	DLL8(CCCCCCCCC	Ds   ;B? ?
C/	C**C/	iteration
prev_toolsc                    | j         }|                                sd S g }|pg D ]d}t          |t                    r+|                    |                    d          pd           B|                    t          |                     et          |j        	                    d|j
        j        r|j
        j        j        nd|j
        j        |j        |||d          |j        t           d           d S )Nr   r   z
agent:step)r_   user_idr%   r  
tool_namestoolsz agent:step hook scheduling errorrw  )r  r  rR   rS   rs   rT   rU   r   
_hooks_refemitr  r_   r   r  r%   _loop_for_stepr/   )r  r  r  r  _names_ts         r6   _step_callback_synczTurnRunner._step_callback_syncl  s   i%%'' 	F # 	' 	'B"d## 'bffVnn23333c"gg&&&& N9<9LTCJ/55RT:-!n&$#/ /   :	
 	
 	
 	
 	
 	
rB   r   c                     | j         }	 t          j        |j                            ||          |j                   d S # t          $ r&}t                              d|           Y d }~d S d }~ww xY w)Nzevent_callback hook error: %s)	r  r  run_coroutine_threadsafer  r  r  r.   r/   r0   )r  r  r   r  _es        r6   _event_callback_synczTurnRunner._event_callback_sync  s    i	>,##J88"      	> 	> 	>LL8"=========	>s   3> 
A.A))A.r  c           
         | j         j        r                                sd S t          j        j        ||          }|`t                              dj        j        rj        j        j        nd|t          t          |pd                    d d                    d S t          t          j        j        ||j                  j        t          d| d          }|d S j        rd
fd	}|                    |           d S d S )Nz(status_callback suppressed for %s/%s: %sr  r      zstatus_callback (z) scheduling errorrw  r'   c                     	 |                                  }n# t          $ r Y d S w xY wt          |dd           }t          |dd          r+|r+j                            t          |                     d S d S d S )Nr4  r  F)r  r.   r-   rF  rs   rU   )futresmidr  s      r6   _track_status_idz:TurnRunner._status_callback_sync.<locals>._track_status_id  s    **,,CC    FFc<663	511 :c :(//C99999: : : :s    
&&rX  )r  _status_adapterr  r  r  r_   r/   r0   r   r   rU   r   r  _status_chat_id_status_thread_metadatar  rE  add_done_callback)r  r  r  prepared_message_futr  r  s         @r6   _status_callback_syncz TurnRunner._status_callback_sync  s`   i" 	#*@*@*B*B 	F:J
 

 #LL:-0Z-@O
#))i3C24F4FGGM	   F''(;S=PR\^nps  qL  M  MJJJJJ	
 
 
 <F  		5: : : : : : ""#344444		5 		5rB   c                 ;   qrstuvwxyz{|  j         {{j        j        t          j        k    rdn{j        j        j        }{j        pd}{j        pd                                }|r|dz   |z                                   } j	        
                    {j        j        {j        j        pdt          {j        dd           t          {j        dd                     }|r|dz   |z                                   }t                      }	  j	                            {j        {j        {j                  \  }}t"                              d||                    d	          {j        pd           n!# t(          $ r}d
| g dg dcY d }~S d }~ww xY w j	        j        }	 j	                            {j        {j        |          }
|
 j	        _         j	                            {j        {j                   j	        _        d vd }{j        d         wt          t           j	        dd           dd           }|ddlm}  |            }{                    {j        |d          }||j        o
|j        dk    ntA          |          }|}{j!        }|}|s|r	 ddl"m#}  j	        $                    {j                  }|r{ j	        %                    {j        ||d          \  }} ||{j        j        |{j&        {j'        {fdnd |{j(        {j)                  v|rdtT          dd fvw{fd}v{j+        d<   n2# t(          $ r%}t"                              d|           Y d }~nd }~ww xY w|wdtT          dd fw{fd}dddtT          dt@          dd fv{fd } j	        ,                    {j-        ||          }{j                            d!          pi                     d"          pi }|                    |          pi }|                    d#          }|tA          |          nd} j	        .                    |d$         |d%         {j/        | j	        0                    {j                  t          {j        d&d           t          {j        d'd           |(          }d zd}t           j	        d)d           } t           j	        d*d           }!d }"| rS|!Q| 5  |!                    {j                  }#d d d            n# 1 swxY w Y   |#rtc          |#          d+k    r|#d+         }"d}$|"E{j2        >|"{j2        k    r3	  j	        j3        4                    |"          }$n# t(          $ r d}$Y nw xY wd }% j	        j5        Z{j2        rS	  j	        j5        j6        7                    {j2                  }&|&r|&                    d,d          }%n# t(          $ r Y nw xY wd }'| r*|!'| 5  |!                    {j                  }(|(r|(d-         |k    rtc          |(          d.k    r|(d.         nd })tc          |(          d+k    r|(d+         nd }*|*d uo{j2        d uo
|*{j2        k    }+|+o|$o|*|"k    },|,rvt"          8                    d/{j        |*            j	        j9        :                    {j        d           }-tw          |-tx                    r
|-r|-d         nd }.|.r|.tz          ur|.}'n|+s|)~|%||%|)k    rvt"          8                    d0{j        |)|%            j	        j9        :                    {j        d           }-tw          |-tx                    r
|-r|-d         nd }.|.r|.tz          ur|.}'n|(d         zt}          |!d1          r,	 |!?                    {j                   n# t          $ r Y nw xY w j	        A                    z{jB                   |z_C        t"                              d2{j                   d3}d d d            n# 1 swxY w Y   |r4z2 j	        D                    z j	        E                                           |'	 t          jG         j	        jH        |'fd3d4tU          {j                  d d5          6          I                                 n<# t(          $ r/ 	  j	        H                    |'           n# t(          $ r Y nw xY wY nw xY wz( {jJ        dd$|d$         i|d%         t          {j                  i d7|d8d3d9dd:{j/        d;{jL        d<|pd d= j	        jM        pd d>|
d? j	        j        d@|                    d@          dA|	                    dB          dC|	                    dD          dE|	                    dF          dG|	                    dH          dI|	                    dJd          dK|	                    dL          dM{j2        dN|d&{j        jN        d'{j        jO        dO{j        jP        dP{j        j        dQ{j        jQ        dR{j        jR        d{j        jS        dS{j        dTt           j	        j5        dU j	        j5                  dV j	        E                                d#|dWd3z| rH|!F| 5  z||%{j2        f|!{j        <    j	        T                                 d d d            n# 1 swxY w Y   t"                              dX{j        |           {jU        s{jV        s{jW        {jX        nd z_Y        {jZ        d         {j[        nd z_\        {j]        j^        r{j_        nd z_`        |z_a        |r|nd z_b        {jc        z_d        d{ fdY}/|/z_e        d z_f        {jg        z_h        |
z_i         j	        j        z_j        |                    d@          pi z_k        dl                     j	        m                    {j                            z_n        t          jo                    tg rt          jp                    sdZtT          dd f{fd[udrstufd\}0dZtT          dd frstu{fd]}1|1z_q        {jr        rt{j        rmt          t          {jr                  d^d           ({jr        t                    {j        |0{ju        _           n"t          {jr        d`d           }2|2
|0|2{j        <   {j                            dai                               db          }3tw          |3t@                    r|3rdcnd}3|3r!tU          |3          v                                ndcz_w        dddtT          det@          dtT          f{fdf}4|4z_x        {jy        z_z        z{j{        d<   {j|        z_}        {j~        z_        t}          zdg          rzj        nd {j        d<   t          {j        {j        t	          {j                  h          \  }5}6|rt          zdMd           {j2        k    rt          |5t          zdid                     }7|7|5ur`t"                              dj{j        tc          |5          tc          |7                     t          |7t          j                    k          }5t          |5          }8ddllm}9m}:m};m}< dmt          dd fq{fdn}={j        }>{j        }?t           j	        doi           }@{j        r|@:                    {j        d           nd }A|Ar|Adz   {j-        z   {_-        t%                      }Bt'          t)          {j                  |Bp          }Cd }D{j        r=	  j	        j3        j                            {j                  }Dn# t(          $ r d }DY nw xY wd}E|D2t          |Ddqd          r!t'          t          |Ddrd           |Bp          }EtA          |Dd uot          |Ddqd          o|Cp|E          }FtA          |5o |5ds                             dt          duk    o|C          }G|Frut          |Ddvd           pdw}H{j-        }> j	        $                    {j                  }ItA          t          |Idxd3                    }Jt-          |H{j-        |Jy          {_-        n|Gr{j-        }>dz{j-        z   {_-        t           j	        d{d           }@|@r?{j        r8{j        |@v r/|@:                    {j        d           }K|Kr|Kdz   {j-        z   {_-        tw          {j-        tT                    r{j-                                        sy|Dwt          |Ddqd          rft          |Ddvd           pdw}L j	        $                    {j                  }Mt-          |LdtA          t          |Mdxd3                    y          {_-        {j        pdq |;q          }N |9q|=           	  j	                            {j                  }O|Or	 dd|lm}P  |P{j-        |O          \  }Q}R|Rr)t"                              d}tc          |R          |R           t5          d~ |QD                       r|Q}Sn{j-        }Sn@# t(          $ r,}Tt"                              d|T           {j-        }SY d }T~Tnd }T~Tww xY w{j-        }St7          |S|6          }U|5{j2        d}V|>|>|Vd<   n|6r
{j-        |Vd<   {j        
{j        |Vd<   |?|?|Vd<    zj        |Ufi |V}W |<q           	 ddlm}X  |Xq           n# t(          $ r Y nw xY w |:|N           n>#  |<q           	 ddlm}X  |Xq           n# t(          $ r Y nw xY w |:|N           w xY w|W{j        d<   vv                                 |W                    d          }Yd}Zd}[d}\d}]{j{        d         }^|^r`t}          |^d          rPt          |^j        dd          }Zt          |^dd          }[t          |^dd          }\t          |^j        dd          pd}]|^rt          |^d$d           nd }_{j{        d         zd}`zrtA          t          zdd                    nd}azrt          zdM{j2                  n{j2        }bzr~{j        rv|b{j2        k    rjd3}`t"          8                    d{j2        |b            j	        j3        j                            {j                  }cd}d|crt          |cdMd           }e{)                                s)t"          8                    d{j        pd{ju                   n|e|bk    rd3}dn|e{j2        k    r*t"          8                    d{j        pd{j2        |e           nR|b|c_2         j	        j3                                          j	        j3                            |b{j        {j                   d3}d|drt          {j        dNd           t          j        k    rt          {j        dRd           dk    rt          {j        dd            j	        j5        	  j	        j5        j6                            |b          }f|fr`|f                    d          rKtU          |fd                   {j        _S        t"                              d{j        jS        {j2        |b           n,# t(          $ r t"                              dd3           Y nw xY w|dr" j	                            {j        |cd           |b| j	                            |z           |`s|ardntc          |5          }g|YstS          |W|Ypdtc          |5                    }YtU          {j        j        |Y          }Y|Ys"|W                    d          rd|Wd          nd}Yi d|Yd|W                    dg           d|W                    dd          d|W                    dd          d|W                    d          d|W                    dd          d|W                    d          d|W                    dd          d|W                    d          d|W                    d          d|W                    dd          d|W                    dd          dg{j        d         pg d|gd|adM|d|Z|[|\|_|]dS d|YvrtW          |W                    dg           tc          |5          |8          \  }h}i|hrwtY                      }jg }k|hD ]0}l|l|jvr*|j                    |l           |k                    |l           1|ir|k                    dd           |Ydz   dl                    |k          z   }Y|Yr j	        j5        r	 ddlm}m {j        d         r!{j        d                             dg           ng }ndtT          dtd          dd fd}ozrt          zd$d           nd xzrt          zd	d           nd y|ozrSt          zd$d           t          zd	d           t          zdd           t          zdd           t          zdd           dnd zrxyzfdnd d}p j	                            {j                  r{| fd|pd<   nH j	                            {j                  s j	                            {j                  r
{| fd|pd<    |mt           j	        j5        dU j	        j5                  |{j-        |Y|nfi |p n# t(          $ r Y nw xY wi d|Yd|W                    d          d{j        d         r!{j        d                             dg           ng d{j        d         r!{j        d                             dd          ndd{j        d         r!{j        d                             dd          ndd{j        d         r {j        d                             d          nd d{j        d         r {j        d                             d          nd d{j        d         r!{j        d                             dd          ndd{j        d         r!{j        d                             dd          ndd{j        d         r {j        d                             d          nd d{j        d         r {j        d                             d          nd d{j        d         r!{j        d                             dd          nddg{j        d         pg d|gd|ad|Zd|[|\|_|]||W                    dd          |W                    dd          {j        d         r!{j        d                             dd3          nd3dS )Nr;  r   r   rd  parent_chat_idrc  r  r  r  z3run_agent resolved: model=%s provider=%s session=%sr  u'   ⚠️ Provider authentication failed: r   r  r  r  r  r  r  r  r  r  rX   	streamingStreamingConfigr  GatewayStreamConsumerraiseon_missing_cursorc                  8     j                             d          S )N)rU  )r  r  )r  s   r6   r   z%TurnRunner.run_sync.<locals>.<lambda>.  s    S%7%;%;N%K%K rB   )r  r  rX   r   on_new_messageon_before_finalizeinitial_reply_to_idrun_still_currentr   r'   c                                                      r.                    |                                |            d S d S d S r;   r  on_delta)r   _stream_consumer_stts_consumer_refr  s    r6   _stream_delta_cbz-TurnRunner.run_sync.<locals>._stream_delta_cb7  sa    "5577 F 0 9 9$ ? ? ?#5#A$6$?$?$E$E$E$E$E	F F $B#ArB   z$Could not set up stream consumer: %sc                 ^                                     r                    |            d S d S r;   r  )r   r  r  s    r6   r  z-TurnRunner.run_sync.<locals>._stream_delta_cbE  s;    ))++ 6&//555556 6rB   F)already_streamedr  c                x                                    sd S | }.|r                                 n                    |           d S |s*j        r#t	          |pd                                          sd S t          j                            j        |j	                  j
        t          d           d S )Nr   r  z+interim_assistant_callback scheduling errorrw  )r  on_segment_breakon_commentaryr  rU   rV   r   r  r  r  r  r/   )r   r  display_textr  r  s      r6   _interim_assistant_cbz2TurnRunner.run_sync.<locals>._interim_assistant_cbI  s    ))++ L+# A$557777$22<@@@ s': #lFXVXBYBYB_B_BaBa $#(('  8 )  
 "I	 	 	 	 	 	rB   r1   r#  skip_context_filesr  r  r  user_id_alt)
cache_keysr  r  r  _agent_cache_lock_agent_cacher  message_countrk   r  u   Agent cache invalidated for session %s: cached agent's session_id %s is ended in state.db (stale self-heal artifact, #54878 x #54947) — discarding instead of reusing across the routing recoveryzfAgent cache invalidated for session %s: message_count changed (%s -> %s), possible cross-process writemove_to_endz#Reusing cached agent for session %sTzagent-xproc-evict-   targetr  daemonr   max_iterations
quiet_modeverbose_loggingenabled_toolsetsdisabled_toolsetsephemeral_system_promptprefill_messagesreasoning_configservice_tierrequest_overridesproviders_allowedonlyproviders_ignoredignoreproviders_orderorderprovider_sortsortprovider_require_parametersrequire_parametersprovider_data_collectiondata_collectionr%   r_   	user_namer  	chat_namer}  gateway_session_keyr3   r*   fallback_modelload_soul_identityz)Created new agent for session %s (sig=%s)c                 <   j         r                                sd S 	 t          |           }n-# t          $ r  t                              dd           Y d S w xY w|sd S t          j                            j	        |          j
        t          d           d S )Nzrender_notice_line failedTr   z)notice_callback delivery scheduling errorrw  )r  r  r	  r.   r/   r0   r   r  _deliver_platform_noticer  r  )r  r#  r  r  s     r6   _notice_callback_syncz2TurnRunner.run_sync.<locals>._notice_callback_sync  s    & c.D.D.F.F )&11   84HHH  $55cj$GG"G	     s   0 &AAr  c           
          j         r                                sd S t          j                             j        | t          j        j        j                            j	        t          d           d S )Nrc   r  z+background_review_callback scheduling errorrw  )r  r  r   r  r  r   r  r  r_   r  r/   )r  r  s    r6   _deliver_bg_review_messagez7TurnRunner.run_sync.<locals>._deliver_bg_review_message  s    & c.D.D.F.F $#(('9#:U`c`j`sttt )  
 "I	 	 	 	 	 	rB   c                                                        5  t                    }                                  d d d            n# 1 swxY w Y   | D ]} |           d S r;   )rt   r  clear)pendingqueued_bg_review_pending_bg_review_pending_lock_bg_review_releaser  s     r6   _release_bg_review_messagesz8TurnRunner.run_sync.<locals>._release_bg_review_messages  s    ""$$$( + +122"((***+ + + + + + + + + + + + + + + " 3 3**622223 3s   $AAAc                 $   j         r                                sd S                                 sR5                                  s#                    |            	 d d d            d S 	 d d d            n# 1 swxY w Y    |            d S r;   )r  r  r  rs   )r  r  r  r  r  r  s    r6   _bg_review_sendz,TurnRunner.run_sync.<locals>._bg_review_send  s   & c.D.D.F.F %,,.. ,  -4466 *11':::                      '&w/////s   +A::A>A>register_post_delivery_callback
generation_post_delivery_callbacksr"  memory_notificationsrN   questionmulti_selectc           
         ddl m} dd l}j        sdS |                                j        d d         }|                    |j        pd| |rt          |          nd t          |                     	 j        
                    j                   n# t          $ r Y nw xY w	 j        rj        d         nd }t          |dd           }t          |          r |d           n,# t          $ r t                               d	d
           Y nw xY wd}t%          j                            j        | |rt          |          nd |j        pdj                  j        t           d          }	|	d}nj	 |	                    d          }
t          t          |
dd                    }n4# t          $ r'}t                               d|           d}Y d }~nd }~ww xY w|s|                    j        pd           dS |                                }|                    |t7          |                    }||dk    rdt9          |dz             dS |S )Nr   clarify_gatewayr   
   )
clarify_idr  r  r   r  flush_pending_syncg      @r  z2Stream-consumer flush before clarify prompt failedTr   F)r  r  r   r  r  r   zClarify send failed to schedulerw     r  zClarify send failed: %sz'[clarify prompt could not be delivered]z[user did not respond within r  zm])r  r  uuidr  uuid4hexregisterr  r  r   pause_typing_for_chatr  r.   stream_consumer_holderr-   r  r/   r0   r   send_clarifyr  r  r  r   clear_sessionget_clarify_timeoutwait_for_responserG  rF  )r  r   r  _clarify_mod_uuidr  _sc_flushsend_okr  r  r5   r  r  r  s                 r6   _clarify_callback_syncz3TurnRunner.run_sync.<locals>._clarify_callback_sync  s   ======    & r*3B3/J!!%O1r!)0:Wd!,// "   #99#:MNNNN   	7:7Q[c033W[ &:DAAF## (F3''''   H!       G*#00/%-4>DMMM$) # 52 8 1   "=  C {$ ZZZ33F"769e#D#DEEGG  $ $ $NN#<cBBB#GGGGGG$  A **3?+@bAAA@@"6688G#55j%PW..5YYH8r>>Ls7R<7H7HLLLLOs=   6B 
B#"B#'AC* *&DD;4F0 0
G!:GG!r  r  _session_messageszPersisted transcript lagged live cached history for session %s (disk=%d, memory=%d); preserving live conversation context (possible FTS write corruption)r  )register_gateway_notifyreset_current_session_keyset_current_session_keyunregister_gateway_notifyapproval_datac                     
j                             
j                   |                     dd          }|                     dd          }t	          |          }t          t          
j                   dd          	 t          
j                             
j        |	|
j	        |                     dd          |                     d	d          |                     d
d                    
j
        t          d          }|t          d          |                    d          }|j        rdS t                              d|j                   n2# t"          $ r%}t                              d|           Y d}~nd}~ww xY wt          
j         dd          }t%          ||||                     dd          |                     d	d          |                     d
d                    }	 t          
j                             
j        |
j	                  
j
        t          d          }||                    d           dS dS # t"          $ r&}t                              d|           Y d}~dS d}~ww xY w)aY  Send the approval request to the user from the agent thread.

                If the adapter supports interactive button-based approvals
                (e.g. Discord's ``send_exec_approval``), use that for a richer
                UX.  Otherwise fall back to a plain text message with
                ``/approve`` instructions.
                r   r   r   zdangerous commandsend_exec_approvalNr   Tr   r   F)r  r   r  r   r   r   r   r   z#send_exec_approval scheduling errorrw  z$send_exec_approval: loop unavailabler  r  zLButton-based approval failed (send returned error), falling back to text: %sz6Button-based approval failed, falling back to text: %styped_command_prefixr;  r   r  z#Approval text-send scheduling errorz#Failed to send approval request: %s)r  r  r  rT   r   r-   r   r   r  r  r  r/   r  r  r  r   r  r.   r   r  )r  r   rZ  _approval_fut_approval_resultr  _pr|  _approval_send_fut_approval_session_keyr  s            r6   _approval_notify_syncz2TurnRunner.run_sync.<locals>._approval_notify_sync  s    55c6IJJJ##Ir22C $$]4GHHD +3//C
 tC/002FMMY$<+>>$'$7$'(=(,%(%@,9,=,=>OQU,V,V*7*;*;OT*R*R)6):):>5)Q)Q ? 	 	 *%$I% % %M %,*+QRRR'4';';B';'G'G$'/ NNf(.    !   NNPRT        ,.DcJJB0 - 1 12CT J J+//FF*..~uEE  CH%=',,+!$!< -  
 &! E	& 	& 	&" &1&--b-99999 21 H H HBBGGGGGGGGGHs8   B1E 4 E 
FE??F/AI 
I=I88I=ro  )rb  resume_pendinglast_resume_marked_atr   r{  r  resume_reasonrl  interactive_resumerh  z[System note: A new message has arrived. The conversation history contains pending tool outputs from an interrupted turn. IGNORE those pending results. Address the user's NEW message below FIRST. Do NOT re-execute old tool calls from the history.]

_pending_skills_reload_notes)build_native_content_partsz:Native image attachment: skipped %d unreadable path(s): %sc              3   H   K   | ]}|                     d           dk    V  dS )r   	image_urlNrT   r  s     r6   rA   z&TurnRunner.run_sync.<locals>.<genexpr>  s1      HHA155==K7HHHHHHrB   z8Native image attachment failed, falling back to text: %s)conversation_historyr  persist_user_message
moa_configpersist_user_timestampr	  r  context_compressorlast_prompt_tokenssession_prompt_tokenssession_completion_tokenscontext_length_last_compaction_in_placeu/   Session split detected: %s → %s (compression)uS   Skipping session split sync for stale run %s — generation %s is no longer currentr  znSkipping session split sync for %s because the session binding moved from %s to %s before compression finishedr~  r%   uG   Restored source.thread_id=%s from binding after session split %s → %sz<Failed to restore thread_id from binding after session splitr   zagent-run-compressionrj  r  r  u   ⚠️ r  r  r  failure_reasonr  r  r  interrupt_messagecompression_exhaustedcompression_deferredr  compacted_in_place)input_tokensoutput_tokensr  r3  r  )r  r  r   r   )maybe_auto_titler   r5   c                 >    t                               d| |           d S )Nz@Gateway auto-title failure suppressed (not user-visible): %s: %s)r/   r0   r   r5   s     r6   _title_failure_cbz.TurnRunner.run_sync.<locals>._title_failure_cb  s*    LLZc    rB   r  r  r  )r  r  r  r  r  c                  X    t          dd            k    ot          dd           k    S )Nr  r  r-   )_title_model_title_providerr   s   r6   r   z%TurnRunner.run_sync.<locals>.<lambda>  s6    w55E P#E:t<<O rB   )failure_callbackmain_runtimeruntime_validatorc                 F    j                             j        |           S r;   )r  %_schedule_telegram_topic_title_renamer  titler  effective_session_idr  s    r6   r   z%TurnRunner.run_sync.<locals>.<lambda>  s.    dl  OA  OA
,O O rB   title_callbackc                 F    j                             j        |           S r;   )r  (_schedule_discord_semantic_thread_renamer  rK  s    r6   r   z%TurnRunner.run_sync.<locals>.<lambda>  s.    dl  OD  OD
,O O rB   last_reasoningr<  response_previewedresponse_transformedagent_persisted)r=  r  r3  r%   rR  rS  rT  r,  rX  F)r  r  r_   r  r<  r   context_promptr  rV   r  _get_system_prompt_for_channelr  r-   rq  _resolve_session_agent_runtimer  r  r/   r0   rT   r.   _provider_routing!_resolve_session_reasoning_config_reasoning_config_resolve_session_service_tier_service_tierstreaming_tts_consumer_holderr  r  r1  r  	transportr   "interim_assistant_messages_enabledgateway.stream_consumerr  r	  _build_stream_consumer_configr  r  r  r  rU   r  _resolve_turn_agent_configr  _agent_config_signaturer  _extract_cache_busting_configr   r%   session_store_is_session_ended_in_dbr)   r*   get_sessionr  r  r$  rR   ra  _AGENT_PENDING_SENTINELr   r  KeyError_init_cached_agent_for_turn_interrupt_depthr  _apply_fallback_chain_to_agent_refresh_fallback_model	threadingThread_release_evicted_agent_softstartAIAgentr]  r  _prefill_messagesr  r  r  r  r}  rd  _enforce_agent_cache_capneeds_progress_queuelog_mode_enabledr  r%  tool_progress_callbackrz  r  tool_start_callbackr  loaded_hooksr  step_callbackstream_delta_callbackinterim_assistant_callbackr  status_callbacknotice_callbacknotice_clear_callbackr  event_callbackr  r  r  rD   #_consume_pending_turn_sidecar_notes_gateway_turn_context_notesEventLockbackground_review_callbackr  r   r  run_generationrW   r  clarify_callbackr  thinking_progressr  process_task_id_gateway_turn_process_task_idr  _gateway_turn_process_baseliner  tools_holderr  r  r  r  r   r  r,   r  tools.approvalr  r  r  r  rS   r+  r-  rQ  rg  r  _entriesrs  #_consume_pending_native_image_pathsagent.image_routingr&  r  r  r,  run_conversationtools.clarify_gatewayr	  result_holderfinishr/  _save_record_gateway_session_peerTELEGRAM%get_telegram_topic_binding_by_session_sync_telegram_topic_binding_sync_session_model_from_agentr  r   r  rt   rv   rs   ry   agent.title_generatorr>  BaseException_is_telegram_topic_lane_is_discord_auto_thread_lane_is_relay_discord_channel_lane)}r  r  combined_ephemeralevent_channel_promptcfg_channel_promptr  r  runtime_kwargsr5   prr  r  _scfgr  _plat_streaming_streaming_enabled_want_stream_deltas_want_interim_messages_want_interim_consumerr  r~  _consumer_cfg_pause_typing_before_finalize_sc_errr  
turn_route_platforms_gw_cfg_plat_gw_cfg_skip_contextr  _sigreused_cached_agent_cache_lock_cache_peek_cached_sid_peek_entry_cached_sid_is_dead_current_msg_count	_sess_row_xproc_evicted_agentcached
_cached_mc_cached_sid_session_id_mismatch_stale_dead_sid_reuseevicted	_ev_agentr  r  r  _pdc
_mem_notifr  r  r  	_selected_history_media_pathsr  r  r  r  r   _persist_user_message_override _persist_user_timestamp_override_pending_notes_msn_freshness_window_interruption_is_fresh_resume_entry_resume_mark_is_fresh_is_resume_pending_has_fresh_tool_tail_reason_resume_adapter_interactive_resume_srn
_sn_reason_sn_adapter_approval_session_token_native_imgsr&  _parts_skipped_run_message_img_exc_api_run_message_conversation_kwargsr  _clear_clarify_sessionr  _last_prompt_toks_input_toks_output_toks_context_length_agent_resolved_model_session_was_split_compacted_in_placeagent_session_idr  _session_split_entry_persistedentry_session_id_binding_effective_history_offsetr  r  r   unique_tagstagr>  all_msgsrA  maybe_auto_title_kwargsr  r  r  r  r  r  r  rD  rE  r   r  rM  s}   `                                                                                                                @@@@@@@@@@@@r6   run_synczTurnRunner.run_sync  s'   i6 !$
 3x~ E Euu3:K^Kd
 !/52 # 2 8b??AA 	^"4v"=@T"T![![!]!]!\HHJJ$"cj+t<<cj*:DAA	 I 
 
  	\"4v"=@R"R!Y!Y![![022	$(L$O$OzOO %P % %!E>
 LLE~))*55s7L"     	 	 	"QC"Q"Q	       	 \+<II: J 
 

 *:&%)\%O%O:3? &P &
 &
"  
 !>qAh=={DQQ=666666#O%%E
 55O\;
 
 & M6eo6o&& 	
 1!$!G!7 "	N"8 "	N!NIIIIII<;;CJGG EBBJx.5 C   AM#@ (='< ( #
 2,!$!<  #1= LKKKK!%+H,/,@*-*@( ( ($ + FF3 F4 F F F F F F F F 5EC.q1 N N NCWMMMMMMMMN #(:(F6s 6t 6 6 6 6 6 6 6 JO 	 	 	 	$ 	SW 	 	 	 	 	 	 	. \<<S[%Q_``
 !_00;;ArFF{SSYWY(,,\::@b$(()=>>4A4MT-000SX
 |33wy! |AA#/RRCJ	488
M4@@1 4 	
 	
 #dl,?FF~t<<    	26- : :$jj99: : : : : : : : : : : : : : : 2s;//!33#.q> #(* CN22,&*l&@&X&X$' '##  , , ,&+###, "<#/CN/ L48DDS^TT	 K)2)J)J&     $ n	36- m3 m3CO44 k3fQi4// /2&kkAoo4J/26{{Q&))DK $4/ :N$6:'3>9 ) - </<'+;; *
 - M3  B
  O[   #',";"?"?QU"V"V2<We2L2L$bQX$bGAJJ^b	$ =:Q)Q)Q
 4=00-3&2.:.*<< ;  OZ9K	   #',";"?"?QU"V"V2<We2L2L$bQX$bGAJJ^b	$ =:Q)Q)Q 4=0 &q	 #6=99 %% & 2 23? C C C C#+ % % % $%@@H\]]] 0>,%JCO\\\.2+[m3 m3 m3 m3 m3 m3 m3 m3 m3 m3 m3 m3 m3 m3 m3l  	5#4L77t|;;==    + <C.0Ic#/.B.B3B3.GII	  
 %''''   L<<=QRRRR    D =CK % % )%Y'% +3?;;% % %  .~	%
  4% !&% "%!5!5% #&"7"7% );(Bd% "&!?!G4% "2!1% "\77% #-..1D"E"E"E% #%&&...% #%&&"2"2"2%  !#w!%" !ffVnnn#%$ -/FF3G,O,O,O%%& *,0A)B)B)B'%( >>)%* &+%, 
**-%.  J22/%0 *..1%2 
**3%4 *..5%6 *..7%8 *..9%: %(OO;%< #4<#;UDLD\]]]=%@  $|CCEEEA%B $6#5C%H $(4I% %EL  
<v1  	< 	< t%7/F3?+ L99;;;	< 	< 	< 	< 	< 	< 	< 	< 	< 	< 	< 	< 	< 	< 	< LLDcoW[\\\ ( ' +7	 !!  	$ '*&:1&=&IC""t 	! :=9T^c55Z^&6#DZ+d+@+@`d( # 9	 	 	 	 	 	 	" !6&*#"7!1!\7",..1D"E"E"K -3KKL<<S_MM-
 -
) '_..(*"+."2"2	 	 	 	 	 	 	 		3 	3 	3 	3 	3 	3 	3 	3 	3	0S 	0T 	0 	0 	0 	0 	0 	0 	0 	0 	0 	0 ,;(  
	H3? 
	HtC/002SUYZZf#CCO/"1 D     s24NPTUU#,GD)
 _((B77;;<RSS
j$'' 	7!+6J@J%TS__%:%:%<%<%<PT"P	 P	S P	 P	Z] P	 P	 P	 P	 P	 P	d "8
 #&"7# /2.A+/2/C,-4UG-D-DNekk$  1MK-9#/JJ1
 1
 1
--  	75,#E#E#W#W4wu.A4HH I --K OS%7%7Y	   !D49;;! ! ! %A$O$O	
 	
 	
 	
 	
 	
 	
 	
 	
 	
 	
 	
Y	H Y	H$ Y	H Y	H Y	H Y	H Y	H Y	H Y	H| 9<8P&<?<V( !/ErJJ<?OU~!!#/4888QU 	6-#+5CK0 <==!?&s{33)"
 "
 "

 ? 	%% $ : C G G X X % % % $%  !&$@PRW)X)X$$B'>EE-% % %! "% B'7??B'@+@
 

  $ 'b!%%f--7'& 
  
  	m_dCCXGXG-0[* #l>>szJJO"&)=tDD# # 52E  CKK " 	-0[*W +	 K !/MtTT 	:co 	:#/^2S2S!%%cot<<D :"Vmck9 s{C((	K%%''	 )'7?? * ==RAR  ,::3:FFK4 K)=tDD   CK !$ 52"9"9:O"P"P 57LMMM;	?
  <KKCO\\L +/NNNNNN'A'A$( ($FH   XMM8   HHHHHHH 3,2 (+{  / / /NNR    $';LLLLLL/  #{J&   
 )6>$ $  .9?]$%;<<' K?B{$%;<~)58^$\2/;Aa$%=>+U+,<UU@TUUF%%&;<<<YYYYYY&&'<====   %%&=>>>> &%&;<<<YYYYYY&&'<====   %%&=>>>>%! '##%%%  $455 !!$ 	[gf&:;; 	[ '(ACWYZ [ [!&*A1EEK"6+FJJL%f&?AQSTUUZYZO<BL'&'4888
  #" [`jd752Mu#U#UVVVejKPd75,GGGVYVd J	S_ J	)9S^)K)K!%KKA 0   L.7;;COLLE-2* :#*5,#E#E --// :KK=.3*	    &)9995922%77KK/ .3(    (8E$L.44666L.KK(
  
 6:2 . 
J559JJJCJT::dBBCJT::BL,8#|7;aa#3  b    H   HLL$=$= /28K3H/I/I
,eJ0N,	   !   LLV!% !     
 . 99J.E :     0334H%PPP %T(;TAA#mBTBT 	"  #	<,"#m:L:L  N >cj>QSabbN! \@F

7@S@S![!<6'?!<!<!<Y[ .FJJz266 VZZQ77 &**Xu55	 !&**-=">"> 6::i77 VZZ44 vzz-?? $VZZ0C%D%D  G,,!" (4KU)S)S#$ '

3I5(Q(Q%& )!,2'( !";)* %&9+, 2-. %&7/0 !,!-("17   d >)).M

:r**"=11$8/ / /+J+  	Puu % 0 0C$#**3///& @&&q*>???!/$!6;9O9O!O  B	dl6 B	ABBBBBBGJGXYZG[c3,Q/33JCCCacC m      AFOwugt<<<4FK"U'%T"B"B"BQU(9 %)!(!>!>$+E:t$D$D$+E:t$D$D#*5)T#B#B$+E:t$D$D% % % %)  ** + + + + + + + &*+ +' <77
CC A A A A A A+,<==
 \>>szJJ L??
KKA A A A A A+,<=
 ! DL4eT\=UVV(K"  .       %
n%
fjj)9::%
 CDUVWDX`)!,00R@@@^`%
 SEVWXEY`*1-11+qAAA_`	%

 3CTUVCWbc'*..x???]b%
 >A>OPQ>R\!!$(()9:::X\%
 #BSTUBV`*1-11+>>>\`%
 SM^_`Mal3,Q/33M5IIIgl%
 SEVWXEYds(+//	5AAA_d%
 #:KA:NXS&q)--g666TX%
  RURcdeRf!p!21!5!9!9:M!N!N!Nlp%
" #$Q'3!!$(()?GGG-2'%
* S%a(.B+%
, 7-%
. !"5/%
0 !"31%
2 K3%
4 *$-."(**-A5"I"I$*JJ/Eu$M$M
 VYUfghUi s 1! 4 8 89JD Q Q QosI%
 %
 %
 %	
s  	A&E0 0
F:	F	F	FB"L: :
M)M$$M)TT	TU! !U0/U0	AW 
WW%F_??^_?
^'$_?&^''A_??``Ab 
c!b<;c<
c	cc		cc-kkk)}= =~~G!AL) G0A)AI IAL) I
AJI$"AJJAL) JAJJAAL) K;AL L
ALLALL)AM$L6AMMAM$M
AMMAM$MAMMAM$X!BAZ) Z)&A[[A[e5F Ak6 k6
AllAlNNN)r   rx  ry  rz  r8  r  rU   rS   r%  rt  r  rF  r  r  r  r  r  r,  rB   r6   r  r    s=       	 	 [ T    C$ C$C C$C C$QT C$cg C$ C$ C$ C$Ja' a' a'FD D D*
S 
d 
t 
 
 
 
6>s >T >d > > > >"5 "5c "5d "5 "5 "5 "5HO
 O
 O
 O
 O
rB   r  c            !       t*   e Zd ZU dZdZeed<   dZeed<   eZ	e
ed<   eZe
ed<   dZee         ed<   d	Zeed
<   d	Zeed<   d	Zeed<   d	Zeed<   d	Zeed<   d	Zeed<   d	Zeed<   dZee         ed<   dZeej                 ed<   dZeej                 ed<   dZeeeee ej        f         f                  ed<   dZ!ee"         ed<   d	Z#eed<    e$d          Z% e$d          Z& e$d          Z' e$d          Z( e)            Z* e$d          Z+ e$d          Z, e$d          Z- e$d          Z. e$d          Z/ e$d           Z0 e$d!          Z1 e$d"          Z2 e$d#          Z3 e$d$          Z4 e$d%          Z5 e$d&          Z6 e$d'          Z7 e$d(          Z8d)eed*f         fd+Z9d,ed)d*fd-Z:d,ed)ed*         fd.Z;d,ed)efd/Z<d)e=e>         fd0Z?dZ@ed1         ed2<   dZAee"         ed3<   dZBee"         ed4<   d5ZCe
ed6<   dZDed7         ed8<   d	ZEeed9<   dZFed1         ed:<   dd;eeG         fd<ZHdd=ZIdd>ZJd)efd?ZKeLd@z  ZMdAe dBed)efdCZNd)eeef         fdDZOddEZPdBedFed)dfdGZQdBedHed)dfdIZRddJZSdKeTe"         dLe
d)efdMZUddNZVddOdPee         d)dfdQZWd)e
fdRZXdd)e
fdSZYd	dTdUed)efdVZZd)efdWZ[e\d)efdX            Z]e\d)efdY            Z^e\d)ee         fdZ            Z_e\d)ee         fd[            Z`d\ed)efd]Zad\ed)efd^Zb ecd_d`h          Zdd\ed)efdaZed\ed)efdbZfdcZgd\ed)efddZhd)efdeZid)efdfZjd\ed)ee         fdgZkd\ed)dfdhZld\edied)dfdjZmd\ed)ee         fdkZnd\ed)efdlZoddddmd\ee         d,ee         dneep         d)e>eepf         fdoZqdpedqedrepd)epfdsZrdtedue"d)dfdvZsdweee"f         d)dfdxZtdyeud)dfdzZvdyeud)dfd{Zwdyeud)dfd|Zxdied)dfd}Zyd)efd~Zzd)efdZ{d)efdZ|d)efdZ}d)efdZ~d)e
fdZd)e>fdZd)efdZddZd)efdZddZd Zdde
d)dfdZd)efdZd)efdZd)efdZd,edddye"d)dfdZd,edye"ded         d)ed         fdZddd,edye"d)efdZede"d)efd            Zd,edye"d)efdZdted)efdZddee         dee         d)dfdZddZddZddZdde
d)dfdZdddddAedee         dee         dee         d)df
dZd_ddied)dfdZd)efdZed)e=eee"f                  fd            Zed)efd            ZdddddAe dBedneep         dee         dee         d)efdZddddAe dBedee         dee         d)ef
dZeddqed)epdz  fd            Zeded)e>eef         fd            Zddd_dd\ee         d,ee         dqed)epdz  fdZd,edeep         d)dfdZ	 	 dd,ee         d)ee         fdZ	 dd,eded)dfdZed)edz  fd            Zed)efd            Zed)efd            Zed)efd            Zed)e
fd            Zed)e
fd            Zed)efd            Zed)epfdÄ            Zed)edz  fdĄ            Zd)edz  fdńZedue"dedz  d)dfdǄ            Zd)eee"f         fdȄZd)ee         fdɄZd,ed)ee         fdʄZd,ed\ed)e>e"ee         f         fd˄Zede"d)efd̈́            Zd,ed)efd΄Zed,efdτ            ZdZd,eded)dfd҄Zded)efdӄZded,ed)efdԄZdLe
d)e>eee"f         ef         fdՄZdied)dfdքZddׄZdeee"f         d)dfdلZd,ee         due"dee"         d)efdۄZdcZdej        due"ded)dfdބZd_dߜdue"ded)dfdZdue"d)dfdZdZdZded)dfdZd)efdZd,ed)dfdZʐddZːddZd)efdZd	d	ddeded)efdZ ech d          Zdyeuded,ed)dfdZded)dfdZd)efdZҐddZedd            Zd)efdZՐdd)efdZd)efdZ	 	 ddyeeu         dAee          d)efdZdej        d)dfdZڐddZd)efdZdZdZސd ddddZߐdde
d)dfdZdeee"f         d)dfdZddefdZd)e
fd	Zd
 Zd,ed)eep         fdZde
d)efdZdde
fdZd)efdZddZddZddZd)efdZddZd	d	d	ddededed)dfdZddZd)efdZdedddee>ef         d)efd ZdyeudedAe d)dfd!ZdedAe d)dfd"ZdedAe dyeud)dfd#ZdedAe d)eeugeTd         f         fd$ZdedAe dyeud)dfd%Zdefd&Zd' Zd( ZedAe dye"d)ee>         fd)            ZedAe dye"d)ee>         fd*            Zedye"d)ee         fd+            ZdAe d;e"d)eeu         fd,Z	 ddAe dee         d)eeee         ee         gef         fd-Zd.ed)dfd/Z d0ed1ed)ee         fd2Zd3d4d5d6Zeeef         ed7<   ded8efd9Zded8efd:Zded8efd;Zded8efd<Zded8efd=Zded8efd>Z	ded8efd?Z
ded8efd@Zded)ee         fdAZddd8ed)dfdBZd,ed)dfdCZddDded\edEe=eee"f                  d,ee         d)ee         f
dFZddDded\edEe=eee"f                  d,ee         d)ee         f
dGZd)efdHZd,ed)e=e         fdIZd,ed)dfdJZe\d)efdK            Zd,efdLZdMedNefdOZd\ed)efdPZd)efdQZd\edRed)ee         fdSZd\edTed)efdUZded)efdVZded)efdWZdefdXZd)efdYZddZZ d\e"d[ed)dfd\Z!d\e"d[ed)dfd]Z"d0e"d\e"d^ed)dfd_Z#eded)ee         fd`            Z$ded)efdaZ%ded)efdbZ&dBed)dfdcZ'ddedeedfed)efdgZ(ddedeedfefdhZ)	 ddediedjedked)ef
dlZ*d)efdmZ+dedned)dfdoZ,dieded)dfdpZ-	 	 	 ddqed\drdsedtee         duee=e                  dvee=e                  d)dfdwZ.	 	 	 ddqed\drdsedtee         duee=e                  dvee=e                  d)dfdxZ/d\ed)epfdyZ0d\ed)dfdzZ1d\ed)dfd{Z2d|ed)efd}Z3d\ed)efd~Z4d\ed)efdZ5d\ed)ee6eef                  fdZ7d|ed)efdZ8	 dd\edted|edee6eef                  d)df
dZ9d\edted|ed)dfdZ:d\edted|ed)dfdZ;d\ed)efdZ<d\edted|ed)dfdZ=dZ>d\ed)efdZ?d)efdZ@d\ed)efdZAd\ed)efdZBdeded)efdZCded)efdZDdeded|eded)eEeddf         f
dZFdeded|ed[ed)ee         f
dZGd)eee"f         fdZH	 ddee         d)eeee"f                  fdZIdddddAee          dBee         dee         dee         dee         dyee"         d)eeee"f                  fdZJeddddAee          dBee         dee         dee         dyee"         d)efd            ZKeded)ee         fd            ZLdZM ece jN        e jO        e jP        e jQ        e jR        e jS        e jT        e jU        e jV        e jW        e jX        e jY        e jZ        e j[        e j\        h          Z]ddZ^	 	 	 d de
de
dLe
d)dfdZ_d)efdZ`d)ee>eeee         f                  fdZadddeee>eeee         f                           d)ee>eeee         f                  fdZbdݐecd)efdZdded)dfdZed Zfd)egjh        ji        fdZjddZkddddddd\ee         d,ee         dneep         dee         dqee         d)efdZldede=e         d)efdZmdede=e         d)e>ee=e         f         fdZnd)e=e         fdZo	 ddee         d)e>edz  e=e         f         fdZpdddde=e         ded)dfdZqerddneded)e>ee=e         f         fdZsdepfdZtdedepd)ee         fdÄZuedepd)ee>eeevf                  fdĄ            Zwded)efdƄZxdedepd)ee         fdǄZydepd)dfdȄZzdde
d)dfdɄZ{depd)dfd˄Z|dZ}d̐Z~e>ed<   dΐZi Zepe>eedz  f         epee"f         f         ed<   ed)epee"f         fdЄ            Zed)epee"f         fdф            Zednepdz  d)epfd҄            Ze	 	 	 	 d!dqedepdededepdz  deedz  dedz  ded)efdل            Zd,ed)dfdڄZd,edqedrepd)e>fdۄZd,ed)epfd܄Zd,edepd)dfdބZd,eded)efdZddd,edNee         d)efdZd,edNed)efdZd,edNeded)efdZd,edied)dfdZd,ed)dfdZd,ed)efdZd_dd,edied)efdZd,eded)efdZdye"d,ededz  d)dfdZd dd,ed\edededed)dfdZd,edtee         d)dfdZd,ede=e         d)dfdZd,ed)e=e         fdZd\ed,ed)ee         fdZded,ee         d)efdZeded)efd            Zd,ed)dfdZedue"ded)dfd            Zdue"ded)dfdZdue"ded)dfdZdue"d)dfd ZddZd)efdZd)ee         fdZd\drde"dye"ded)df
dZ	 	 	 dd[ededEe=eee"f                  d\drdted,edNee         dtee         d)eee"f         fd	Z	 	 	 	 	 	 	 	 	 d"d[ededEe=eee"f                  d\edted,edNee         d
edtee         dee         deep         dee"         dee
         dee         d)eee"f         fdZd\ed)ee         fdZd\ed)dfdZ	 	 	 	 	 	 	 	 	 d"d[ededEe=eee"f                  d\edted,edNee         d
edtee         dee         deep         dee"         dee
         dee         d)eee"f         fdZdS (#  r  z
    Main gateway controller.

    Manages the lifecycle of all platform adapters and routes
    messages to/from the agent.
    	interrupt_busy_input_mode_busy_text_mode_restart_drain_timeout_restart_after_turn_timeoutN
_exit_codeF	_draining_external_drain_active_restart_requested_restart_task_started_restart_detached_restart_via_service _detached_restart_helper_started_restart_command_source
_stop_task_restart_task_profile_failed_platforms_systemd_watchdog_startup_restore_in_progress_running_agents_running_agents_ts_active_session_leases_busy_ack_ts_session_run_generationrk  rl  rm  rn  rp  rq  rs  _pending_messages&_pending_native_image_paths_by_session_session_ephemeral_pin_session_vc_last_pending_approvals_update_prompt_pendingr'   r2  c                 V    | j                             d          }|i }|| j         d<   |S )z~The per-session state map; lazily created so bare test runners
        built via ``object.__new__`` work without ``__init__``.	_sessions__dict__rT   )r  rb  s     r6   _sessions_mapzGatewayRunner._sessions_mapH  s5     =$$[11H)1DM+&rB   r  c                     |                                  }|                    |          }|t                      }|||<   |S )z<Get-or-create the :class:`SessionState` for ``session_key``.)r  rT   r2  )r  r  rb  states       r6   _session_statezGatewayRunner._session_stateQ  sA    %%''[))= NNE$)H[!rB   c                 h    | j                             d          }|sdS |                    |          S )zAReturn the SessionState for ``session_key`` without creating one.r  Nr  )r  r  rb  s      r6   _peek_session_statez!GatewayRunner._peek_session_stateZ  s6    =$$[11 	4||K(((rB   c                 P    |                      |          }|duo|j        j        duS )zDTrue when the session holds a running-turn slot (agent or sentinel).N)r  turnr   )r  r  r  s      r6   _is_session_runningz!GatewayRunner._is_session_runninga  s/    ((55D AUZ%5T%AArB   c                 b    d |                                                                  D             S )z(session_key, agent) pairs for sessions with a running turn
        (including pending sentinels), matching the old ``_running_agents``
        dict contents.c                 H    g | ]\  }}|j         j        ||j         j        f S r;   )r  r   )r?   r  r  s      r6   r  z6GatewayRunner._running_agent_items.<locals>.<listcomp>j  s;     
 
 
Uz+ %*"#+++rB   )r  r  r  s    r6   _running_agent_itemsz"GatewayRunner._running_agent_itemsf  s;    
 
"002288::
 
 
 	
rB   asyncio.Task_loop_heartbeat_task_loop_floor_timer_handle_loop_liveness_watchdogr  _gateway_started_atzthreading.Event_shutdown_watchdog_done _platform_lock_takeover_on_start_reconnect_watcher_taskrX   c                    ||nt                      | _        	 ddlm}  |t	          t          | j        dd                               n,# t          $ r t                              dd           Y nw xY wi | _	        i | _
        |                                  t          j        |           a|                                 | _        |                                 | _        |                                 | _        |                                 | _        |                                 | _        |                                 | _        |                                 | _        |                                 | _        |                                 | _         | !                                | _"        | #                                | _$        ddl%m& t          | j        j'        d	d
          }|r|dk    r|dz  nd tQ          | j        j)        | j        fd          | _*        tW          | j*                  | _,        t[          | j                  | _.        d| _/        d | _0        tc          j2                    | _3        d| _4        d| _5        d | _6        d | _7        d| _8        i | _9        d | _:        d| _;        d| _<        d| _=        d| _>        d| _?        d| _@        d| _A        d | _B        t          jC                    | _D        d| _E        d | _F        d | _G        t          jI                    | _J        d | _K        d| _L        i | _M        t                      | _O        i | _P        d| _Q        d| _R        g | _S        g | _T        t                      | _V        d| _W        t          jI                    | _X        t                      | _Z        t                      | _[        d| _\        dd lH}t                      | _]        |I                                | _^        | _                                | _`        d | _a        d | _b        i | _c        t                      | _d        dd le}|f                    d          | _g        	 ddlhmi}  |d           n# t          $ r Y nw xY w	 ddljmk}  |            }t          t          |ddd          pd          n                                o                                }	t	          t          |ddd                    }
t          |ddd           }|	dk    r|
s|st          p                    d           n,# t          $ r t                              dd           Y nw xY wd | _q        	 ddlrms}mt}  | |                      | _q        n2# t          $ r%}t          p                    d|           Y d }~nd }~ww xY w| jq        	 ddljmk}  |            u                    d           pi }|u                    d!d          rc| jq        jv        w                    t          |u                    d"d#                    t          |u                    d$d
                    %           |u                    d&d          r| jq        jv        z                    t          |u                    d'd(                    t          |u                    d$d
                    t          |u                    d)d*                    t	          |u                    d+d                    | j        j)        ,           n2# t          $ r%}t                              d-|           Y d }~nd }~ww xY w	 ddljmk}  |            u                    d.          pi }|u                    d&d          rxdd/l{m|}  |t          |u                    d'd0                    t          |u                    d$d
                    dt          |u                    d1d2                    3           n2# t          $ r%}t                              d4|           Y d }~nd }~ww xY wdd5l}m~}  |            | _        i | _        dd6lm}  |            | _        |                                 | _        i | _        t                      | _        t          jC                    | _        d | _        d | _        d | _        t          jC                    | _        d7| _        d S )8Nr   )set_multiplex_activer  Fz#could not set multiplex-active flagTr   r  bg_process_max_age_hoursr  rB  c                 2                         |           S )N)max_active_age)has_active_for_session)r  _bg_max_age_secondsr  s    r6   r   z(GatewayRunner.__init__.<locals>.<lambda>  s$    0@0W0W$7 1X 1 1 rB   )has_active_processes_fn   i   rk   )ensure_installed)log_failuresload_config	approvalsmodemanualr@  r  tirith_enabledr  r  a6  Gateway approvals.mode=manual with no automated risk assessor (security.tirith_enabled is false and auxiliary.approval is unset): dangerous commands and execute_code scripts will BLOCK until a human approves them in chat. Enable security.tirith_enabled or configure auxiliary.approval for unattended operation.z$approvals.mode startup check skipped)AsyncSessionDB	SessionDBz&SQLite session store not available: %srb  auto_archiveauto_archive_daysr  min_interval_hours	idle_daysrA  
auto_pruneretention_daysZ   min_vacuum_interval_daysr  vacuum_after_prune)rE  rA  rG  vacuumsessions_dirz%state.db auto-maintenance skipped: %srR  )maybe_auto_prune_checkpoints   rU  rp  )rE  rA  delete_orphansrU  z'checkpoint auto-maintenance skipped: %sPairingStore)HookRegistryr  )r  rX   rT  r-  r   r-   r.   r/   r0   r{  _profile_adapters'_warn_if_docker_media_delivery_is_risky_weakrefrefr  _load_prefill_messagesrt  _load_ephemeral_system_prompt_ephemeral_system_prompt_load_reasoning_configr[  _load_service_tierr]  _load_show_reasoning_show_reasoning_load_busy_input_moder  _load_busy_text_moder  _load_restart_drain_timeoutr   _load_restart_after_turn_timeoutr  _load_provider_routingrY  _load_fallback_model_fallback_modelr  r  default_reset_policyr$  rJ  rf  r"  _async_session_storer-  delivery_router_running_gateway_loopr  r  _shutdown_event_exit_cleanly_exit_with_failure_exit_reasonr  r  r  r  r  r  _signal_initiated_shutdownr  r  r   r  r  r,   _startup_time_booted_from_restartr  r  ro  r  _executor_lock	_executor_executor_closingr  r0  _turn_leasesrr  r  r*  _startup_restore_queue_startup_restore_tasksr   _session_sources_session_sources_max_completion_delivery_lockrt   _completion_deliveries_inflight _completion_deliveries_delivered_completion_delivery_retentionr  r  _active_profile_name_kanban_notifier_profile_teams_pipeline_runtime_teams_pipeline_runtime_error_failed_platforms_fatal_handler_tasks	itertoolsr   _slash_confirm_countertools.tirith_securityr5  rg  r8  rU   r   rV   rW   r   r)   hermes_stater=  r>  rT   r*   maybe_auto_archiverG  rF  maybe_auto_prune_and_vacuumtools.checkpoint_managerrK  gateway.pairingrO  pairing_storepairing_storesgateway.hooksrP  hooks_load_voice_modes_voice_mode_recent_voice_transcripts_background_tasksr(  r%  r&  r'  _last_inbound_at_scale_to_zero_cooldown_until)r  rX   r-  _bg_max_age_hours
_threading
_itertoolsr5  _load_full_config	_appr_cfg
_appr_mode
_tirith_on_aux_approvalr=  r>  rs  	_sess_cfgr5   	_ckpt_cfgrK  rO  rP  r2  r  s                        @@r6   r  zGatewayRunner.__init__z  s	    !' 2ff8V8X8X
	O??????  gdk;OQV&W&W!X!XYYYY 	O 	O 	OLL>LNNNNN	O=? RT44666&l400 "&!<!<!>!>(,(J(J(L(L%!%!<!<!>!>!4466#88:: $ : : < <#88::&*&F&F&H&H#+/+P+P+R+R(!%!<!<!>!>#88:: 	<;;;;;#K,.H"
 
 ):]>ORS>S>S$$Y] 	 *K$dk% % % % %
 
 
 %6d6H$I$I!-dk::BF&}""'+/)-RT&!% ',#"' +0'%*"!&$)!05-@D$ %)IKK +0!2659'n..JN "'
 35 566F 9;$
 -2) 16-:<#:<# DO==$'! *3)9)9&MPUU,^i^k^k-.2+ 	'&&&7B}}!+!2!2 )-(A(A(C(C%'+$<@*
 BD *-! 	'&&&&0&6&6q&9&9#	>>>>>>%00000 	 	 	D		PJJJJJJ))++I	;IIIUX eggeegg  gi=MW[\\\]]J#I{JPTUUUMX%%j%%C    	P 	P 	PLL?$LOOOOO	P  
	H>>>>>>>>-~iikk::D 	H 	H 	H NNCQGGGGGGGG	H 'KNNNNNN..0044Z@@FB	==77 $(;;"'	6I1(M(M"N"N+.y}}=QSU/V/V+W+W <    ==u55 
$(DD'*9==9I2+N+N'O'O+.y}}=QSU/V/V+W+W14%MM*DbII2 2  $IMM2F$M$MNN%)[%= E     K K KDcJJJJJJJJK	IJJJJJJ**,,00??E2I}}\511 QQQQQQ -,#&y}}5Eq'I'I#J#J'*9==9Mr+R+R'S'S#(&))--8KS*Q*Q&R&R	     	I 	I 	ILLBCHHHHHHHH	I 	100000)\^^9; 	/.....!\^^
 ,0+A+A+C+C Z\& '*ee
 +/)++ <@!(,%'+$ (,y{{ 58***s   2A &A76A7Q0 0
Q=<Q=B-T/ /&UU# V 
V3V..V3?E&\& &
]0]]B3` 
`<`77`<c                    t           j        | j        vrdS t                      st                              d           dS 	 ddlm} n3# t          $ r&}t          	                    d|           Y d}~dS d}~ww xY w	  ||           }n3# t          $ r&}t          	                    d|           Y d}~dS d}~ww xY w|rt          
                    d           dS | j        r"t          	                    d| j                   dS dS )	u  Bind the Teams meeting pipeline runtime to Graph webhook ingress.

        No-op when the msgraph_webhook adapter isn't running or the
        teams_pipeline plugin isn't enabled — lets the gateway start cleanly
        whether or not the user has opted into the pipeline.
        Nz:Teams pipeline plugin is disabled; skipping runtime wiringr   )bind_gateway_runtimez(Teams pipeline runtime import failed: %sz(Teams pipeline runtime wiring failed: %sz7Teams pipeline runtime bound to msgraph webhook ingressz&Teams pipeline runtime unavailable: %s)r  MSGRAPH_WEBHOOKr{  rB  r/   r0   plugins.teams_pipeline.runtimer  r.   r   r  r~  )r  r  r5   bounds       r6   _wire_teams_pipeline_runtimez*GatewayRunner._wire_teams_pipeline_runtime  sS    #4=88F-// 	LLUVVVF	KKKKKKK 	 	 	NNEsKKKFFFFF		((..EE 	 	 	NNEsKKKFFFFF	  	KKQRRRRR/ 	NN82    	 	s0   A 
A8A33A8<B 
B8B33B8c                    t          j        dd                                                                          dk    rdS | j                                        }d |D             }|sdS t          j        dd                                          }g }|rc	 t          j        |          }t          |t                    rd |D             }n,# t          $ r t                              dd	
           Y nw xY wd}|D ]A}t                              |          }|s|                    d          }	|	t           v rd	} nB|rdS t                              d           dS )a  Warn when Docker-backed gateways lack an explicit export mount.

        MEDIA delivery happens in the gateway process, so paths emitted by the model
        must be readable from the host. A plain container-local path like
        `/workspace/report.txt` or `/output/report.txt` often exists only inside
        Docker, so users commonly need a dedicated export mount such as
        `host-dir:/output`.
        r  r   dockerNc                 \    g | ])}|t           j        t           j        t           j        hv'|*S r,  )r  r<  
API_SERVERWEBHOOKr  s     r6   r  zIGatewayRunner._warn_if_docker_media_delivery_is_risky.<locals>.<listcomp>'  s3    xxxQqQYQdfnfv@w7w7wq7w7w7wrB   r  c                 V    g | ]&}t          |t                    t          |          'S r,  rR   rU   r?   r  s     r6   r  zIGatewayRunner._warn_if_docker_media_delivery_is_risky.<locals>.<listcomp>1  s-    LLL!As9K9KLs1vvLLLrB   zACould not parse TERMINAL_DOCKER_VOLUMES for gateway media warningTr   F	containeraF  Docker backend is enabled for the messaging gateway but no explicit host-visible output mount (for example '/home/user/.hermes/cache/documents:/output') is configured. This is fine if the model already emits host-visible paths, but MEDIA file delivery can fail for container-local paths like '/workspace/...' or '/output/...'.)rq   r  rV   rW   rX   get_connected_platformsr  r  rR   r  r.   r/   r0   _DOCKER_VOLUME_SPEC_REr9  r   $_DOCKER_MEDIA_OUTPUT_CONTAINER_PATHSr   )
r  	connectedmessaging_platformsraw_volumesvolumesparsedhas_explicit_output_mountspecr9  container_paths
             r6   rR  z5GatewayRunner._warn_if_docker_media_delivery_is_risky  s    9^R((..006688HDDFK7799	xx)xxx" 	Fi 92>>DDFF 	qqK00fd++ MLLvLLLG q q q`kopppppq %*! 	 	D*0066E "[[55N!EEE,0) F % 	FP	
 	
 	
 	
 	
s   5C &C43C4c                 L    	 ddl m}  |d          duS # t          $ r Y dS w xY w)z3Check if the hermes-agent-setup skill is installed.r   )_find_skillzhermes-agent-setupNF)tools.skill_manager_toolr  r.   )r  r  s     r6   _has_setup_skillzGatewayRunner._has_setup_skillM  sQ    	<<<<<<;344D@@ 	 	 	55	s    
##zgateway_voice_mode.jsonr_   r  c                     |j          d| S )z6Return a platform-namespaced key for voice mode state.r  r   )r  r_   r  s      r6   
_voice_keyzGatewayRunner._voice_keyY  s    .,,7,,,rB   c                    	 t          j        | j                            d                    }n$# t          t           j        t          f$ r i cY S w xY wt          |t                    si S h d}i }|	                                D ]>\  }}||vr
t          |          }d|vrt                              d|           9|||<   ?|S )Nr  rJ  >   r  r  
voice_onlyr  z}Skipping legacy unprefixed voice mode key %r during migration. Re-enable voice mode on that chat to rebuild the prefixed key.)r  r  _VOICE_MODE_PATHr   FileNotFoundErrorJSONDecodeErrorru   rR   rS   r  rU   r/   r   )r  datavalid_modesr  r  r:  r  s          r6   r  zGatewayRunner._load_voice_modes]  s    	:d3==w=OOPPDD!4#7A 	 	 	III	 $%% 	I222!ZZ\\ 	 	MGT;&&g,,C#~~U  
 F3KKs   -0 AAc                    	 | j         j                            dd           | j                             t	          j        | j        d          d           d S # t          $ r&}t          	                    d|           Y d }~d S d }~ww xY w)NTrV  exist_okr  indentr  rJ  zFailed to save voice modes: %s)
r  rp   mkdir
write_textr  r  r  ru   r/   r   )r  rs  s     r6   _save_voice_modeszGatewayRunner._save_voice_modesw  s    	@!(..td.KKK!,,
4+A666 -       	@ 	@ 	@NN;Q?????????	@s   AA 
B
$BB
r2  c                 ,   t          |dd          }t          |t                    sdS |rT|                    |           t          |dd          }t          |t                    r|                    |           dS dS |                    |           dS )zBUpdate an adapter's in-memory auto-TTS suppression set if present._auto_tts_disabled_chatsN_auto_tts_enabled_chatsr-   rR   rt   rv   discard)r  r  r  r2  disabled_chatsenabled_chatss         r6   _set_adapter_auto_tts_disabledz,GatewayRunner._set_adapter_auto_tts_disabled  s     *DdKK.#.. 	F 	,w'''#G-FMMM--- /%%g...../ / ""7+++++rB   r  c                 ,   t          |dd          }t          |t                    sdS |rT|                    |           t          |dd          }t          |t                    r|                    |           dS dS |                    |           dS )zUpdate an adapter's per-chat auto-TTS opt-in set if present.

        Used for ``/voice on``/``/voice tts`` where the user explicitly wants
        auto-TTS even when ``voice.auto_tts`` is False globally.
        r  Nr  r  )r  r  r  r  r  r  s         r6   _set_adapter_auto_tts_enabledz+GatewayRunner._set_adapter_auto_tts_enabled  s      )BDII--- 	F 	+g&&&$W.H$OON.#.. 0&&w/////0 0 !!'*****rB   c                 v   t          |dd          }t          |t                    sdS t          |dd          }t          |dd          }t          |t                    st          |t                    sdS 	 ddlm}  |            }t          |                    d          pi                     dd	                    }n# t          $ r d	}Y nw xY wt          |d
          r||_
        |j         dt          |t                    rL|                                 |                    fd| j                                        D                        t          |t                    rN|                                 |                    fd| j                                        D                        dS dS )ae  Restore persisted /voice state into a live platform adapter.

        Populates three fields from config + ``self._voice_mode``:
          - ``_auto_tts_default``: global default from ``voice.auto_tts``
          - ``_auto_tts_enabled_chats``: chats with mode ``voice_only``/``all``
          - ``_auto_tts_disabled_chats``: chats with mode ``off``
        r_   Nr  r  r   r7  voiceauto_ttsF_auto_tts_defaultr  c              3      K   | ]9\  }}|d k    |                                |t                    d         V  :dS )r  Nr   r   r?   r  r:  r  s      r6   rA   zBGatewayRunner._sync_voice_mode_state_to_adapter.<locals>.<genexpr>  sX       " "&/c45==S^^F%;%;= CKKLL! ===" "rB   c              3   ~   K   | ]7\  }}|d v 	|                               |t                    d         V  8dS )>   r  r  Nr  r  s      r6   rA   zBGatewayRunner._sync_voice_mode_state_to_adapter.<locals>.<genexpr>  s_       ! !&/c4000S^^F5K5K0 CKKLL!0000! !rB   )r-   rR   r  rt   rg  r8  r   rT   r.   r   r  r   r  r  r  r  )	r  r  r_   r  r  r  	_full_cfgr  r  s	           @r6   !_sync_voice_mode_state_to_adapterz/GatewayRunner._sync_voice_mode_state_to_adapter  s"    7J55(H-- 	F *DdKK)BDII.#.. 	z-QT7U7U 	F	&JJJJJJ))++I $w''-222:uEE! !  	& 	& 	& %	&7/00 	:(9G%N%%%nc** 	  """!! " " " "373C3I3I3K3K" " "    mS)) 	!!!   ! ! ! !373C3I3I3K3K! ! !     	 	s   9AC CC	awaitabler  c                   K   |dk    r
| d{V  dS t          j        |          }	 t          j        |h|           d{V \  }}nB# t           j        $ r0 |                                 |                    t                      w xY w||v r
| d{V  dS |                                 |                    t                     dS )a~  Wait for adapter cleanup without letting cancellation swallowing hang us.

        ``asyncio.wait_for`` cancels an overdue child but then waits for it to
        exit. An adapter close path that catches ``CancelledError`` can therefore
        block recovery forever. Keep ownership of the old task through its done
        callback, but release the runner at the deadline.
        r   NTr  F)r  ensure_futurer  rf  cancelr  r   )r  r  r  r   done_pendings         r6   #_await_adapter_cleanup_with_timeoutz1GatewayRunner._await_adapter_cleanup_with_timeout  s       a<<OOOOOOO4$Y//	#*<#H#H#HHHHHHHND((% 	 	 	KKMMM""#?@@@	 4<<JJJJJJJ4;<<<us    A	 	?Bc                 \  K   |                                  }	 |                     |                                |           d{V }|s't                              d|||j        nd           dS dS # t          $ r0}t                              d||j        nd|           Y d}~dS d}~ww xY w)u  Call adapter.disconnect() defensively, swallowing any error.

        Used when adapter.connect() failed or raised — the adapter may
        have allocated partial resources (aiohttp.ClientSession, poll
        tasks, child subprocesses) that would otherwise leak and surface
        as "Unclosed client session" warnings at process exit.

        Must tolerate partial-init state and never raise, since callers
        use it inside error-handling blocks.
        NzITimed out after %.1fs while disconnecting %s adapter; continuing shutdownr  z7Defensive %s disconnect after failed connect raised: %s) _adapter_disconnect_timeout_secsr  r  r/   r   r   r.   r0   )r  r  r_   r  r  rs  s         r6   _safe_adapter_disconnectz&GatewayRunner._safe_adapter_disconnect  s      7799	"FF""$$g       I  _&.&:HNN	       	 	 	LLI"*"6I        	s   AA1 1
B+;%B&&B+profiler  c                :  K   |                                  }|rd| dnd}t          j                    }	 |                     |                                |           d{V }|s"t
                              d|j        ||           n9# t          $ r,}t
          	                    d|j        ||           Y d}~nd}~ww xY w	 |                     |
                                |           d{V }	|	r8t
                              d|j        t          j                    |z
  |           dS t
                              d|j        ||           dS # t          $ rB}t
                              d	|j        t          j                    |z
  ||           Y d}~dS d}~ww xY w)
a>  Tear down one adapter on the shutdown path with bounded awaits.

        Both ``cancel_background_tasks()`` and ``disconnect()`` can block
        indefinitely when a platform's network state is half-dead (e.g. a
        wedged Feishu/Lark WebSocket thread waiting on I/O). An unbounded
        await here stalls the entire shutdown sequence past systemd's
        ``TimeoutStopSec``; the resulting SIGKILL skips ``atexit`` PID-file
        cleanup, so the next start dies with "PID file race lost" (#14128).

        Each await uses the existing per-adapter timeout budget
        (``HERMES_GATEWAY_ADAPTER_DISCONNECT_TIMEOUT``). On timeout the old
        task is cancelled and detached, then teardown forces forward progress;
        the loop never hangs even if an adapter swallows cancellation. Never
        raises.
        z (profile: rT  r   NuH   ✗ %s background-task cancel timed out after %.1fs - forcing continue%su)   ✗ %s background-task cancel error%s: %su   ✓ %s disconnected (%.2fs)%su<   ✗ %s disconnect timed out after %.1fs - forcing continue%su)   ✗ %s disconnect error after %.2fs%s: %s)r  r,   rb  r  cancel_background_tasksr/   r   r   r.   r0   r  r  r  )
r  r  r_   r  r  suffix
started_at	cancelledrs  disconnecteds
             r6   _bounded_adapter_teardownz'GatewayRunner._bounded_adapter_teardown  s3     $ 7799-4<)w))))"^%%

	a"FF//117       I  ^NGV    	a 	a 	aLLDhnV\^_````````	a	!%!I!I""$$g" "      L  	3NDN$4$4z$A6    
 RNGV      	 	 	LL; 0 0: =vq        	s7   AB 
B>"B99B>A&E *"E 
F7FFc                     t          j        dd                                          }|rK	 t          |          }t	          d|          S # t
          $ r t                              d|           Y nw xY wt          S )z?Return the per-adapter disconnect timeout used during shutdown.)HERMES_GATEWAY_ADAPTER_DISCONNECT_TIMEOUTr   r  z=Ignoring invalid HERMES_GATEWAY_ADAPTER_DISCONNECT_TIMEOUT=%r)	rq   r  rV   rG  r  rH  r/   r   (_ADAPTER_DISCONNECT_TIMEOUT_SECS_DEFAULT)r  rV  r  s      r6   r  z.GatewayRunner._adapter_disconnect_timeout_secs:  s    iCRHHNNPP 		))** 3(((    S     87   A
 
%A21A2c                 &   t          j        dd                                          }|rK	 t          |          }t	          d|          S # t
          $ r t                              d|           Y nw xY w|t          j	        k    rt          S t          S )zBReturn the per-platform connect timeout used during startup/retry.r  r   r  z;Ignoring invalid HERMES_GATEWAY_PLATFORM_CONNECT_TIMEOUT=%r)rq   r  rV   rG  r  rH  r/   r   r  r  &_TELEGRAM_CONNECT_TIMEOUT_SECS_DEFAULT&_PLATFORM_CONNECT_TIMEOUT_SECS_DEFAULT)r  r_   rV  r  s       r6   _platform_connect_timeout_secsz,GatewayRunner._platform_connect_timeout_secsI  s    iA2FFLLNN 		))** 3(((    Q     x(((9955r  is_reconnectr  c                T  K   |                      |          }|dk    r|                    |           d{V S t          j        |                    |                    }	 t          j        |h|           d{V \  }}nB# t          j        $ r0 |                                 |                    t                      w xY w||v r| d{V }t          |          S |                                 |                    t                     t          |j         d|dd          )u  Connect an adapter without allowing one platform to block others.

        ``is_reconnect`` is forwarded to ``adapter.connect()`` so platform
        adapters can distinguish a cold first boot (drop any stale
        server-side queue) from a watcher reconnect after a prolonged outage
        (preserve the queue so messages sent during the outage are delivered
        rather than silently dropped — #46621).
        r   r  Nr  z connect timed out after gr  )r  connectr  r  r  rf  r  r  r   r   TimeoutErrorr   )	r  r  r_   r  r  r   r  r  r  s	            r6   _connect_adapter_with_timeoutz+GatewayRunner._connect_adapter_with_timeoutZ  sZ      55h??a<< lCCCCCCCCC $OOO66
 
	#*<#H#H#HHHHHHHND((% 	 	 	KKMMM""#?@@@	 4<<ZZZZZZF<<;<<<~DDDDDD
 
 	
s   # B ?Cc                    K   t          | j                  |_        	 |                     ||           d{V 	 d|_        S # d|_        w xY w)aT  Connect one cold-start adapter with tightly scoped replace intent.

        The capability is visible only while this initial connect is awaited.
        Reconnects call ``_connect_adapter_with_timeout`` directly and adapters
        also default to deny, so a later network recovery can never evict a
        healthy token holder.
        NF)r   r*  _platform_lock_takeover_allowedr  )r  r  r_   s      r6   %_connect_initial_adapter_with_timeoutz3GatewayRunner._connect_initial_adapter_with_timeout  sl       3713
 3
/	<;;GXNNNNNNNNN6;G33eG3;;;;s   A 	A
c                     | j         S r;   )ri  r"  s    r6   should_exit_cleanlyz!GatewayRunner.should_exit_cleanly  s    !!rB   c                     | j         S r;   )rj  r"  s    r6   should_exit_with_failurez&GatewayRunner.should_exit_with_failure  s    &&rB   c                     | j         S r;   )rk  r"  s    r6   exit_reasonzGatewayRunner.exit_reason  s      rB   c                     | j         S r;   )r  r"  s    r6   	exit_codezGatewayRunner.exit_code  s
    rB   r  c           	         t          | d          rL| j        E	 | j                            |          }t          |t                    r|r|S n# t
          $ r Y nw xY wt          | dd          }d}t          |dd          r5|j        r|j        }n&	 ddlm	}  |            pd}n# t
          $ r d}Y nw xY wt          |t          |d	d
          t          |dd          |          S )zUResolve the current session key for a source, honoring gateway config when available.rf  NrX   r  Fr   get_active_profile_namer(  group_sessions_per_userTthread_sessions_per_user)r  r  r  )r   rf  _generate_session_keyrR   rU   r.   r-   r  hermes_cli.profilesr  r*  )r  r  r  rX   _profiler  s         r6   _session_key_for_sourcez%GatewayRunner._session_key_for_source  sE   4)) 	d.@.L"0FFvNNk3// 'K '&&   x.. 6/77 	$~ $!>$KKKKKK6688EIHH  $ $ $#HHH$ $+F4Mt$T$T%,V5OQV%W%W	
 
 
 	
s#   2A 
AAB$ $B32B3c                 n   |j         t          j        k    s|j        dk    rdS t	          | dd          }|dS t	          |d|          }	 |                    t          |j                  t          |j                            }n-# t          $ r  t                              dd	           Y dS w xY w|du S )
z>Return whether Telegram DM topic mode is active for this chat.r~  Fr)   Nr*   r  r  z(Failed to read Telegram topic mode stateTr   )r_   r  r  r}  r-   is_telegram_topic_mode_enabledrU   r  r  r.   r/   r0   )r  r  r3   rV  s       r6   _telegram_topic_mode_enabledz*GatewayRunner._telegram_topic_mode_enabled  s    ?h///63Ct3K3K5T=$77
5Z
;;
	;;FN++FN++ <  CC  	 	 	LLCdLSSS55	 d{s   
;B &B0/B0r   rM   c                     |j         t          j        k    s|j        dk    rdS |                     |          sdS t          |j        pd          }|| j        v S )zUTrue for the main Telegram DM (or General topic) when topic mode has made it a lobby.r~  Fr   r_   r  r  r}  r  rU   rd  _TELEGRAM_GENERAL_TOPIC_IDSr  r  tids      r6   _is_telegram_topic_root_lobbyz+GatewayRunner._is_telegram_topic_root_lobby  sb    ?h///63Ct3K3K50088 	5&"(b))d666rB   c                     |j         t          j        k    s|j        dk    rdS |                     |          sdS t          |j        pd          }|r	|| j        v rdS dS )z9True for a user-created Telegram private-chat topic lane.r~  Fr   Tr  r  s      r6   r  z%GatewayRunner._is_telegram_topic_lane  ss    ?h///63Ct3K3K50088 	5&"(b)) 	cT===5trB   r"   c                    t          | d          si | _        t          |j        pd          }|sdS ddl}|                                }| j                            |d          }||z
  | j        k     rdS || j        |<   dS )a+  Rate-limit root-DM lobby reminders to one message per cooldown window.

        A user who forgets multi-session mode is enabled and types several
        prompts in the root DM would otherwise get a reminder for every
        message. Cap it so the first one lands and the rest stay quiet.
        _telegram_lobby_reminder_tsr   Tr   Nr  F)r   r#  rU   r  r,   rb  rT   #_TELEGRAM_LOBBY_REMINDER_COOLDOWN_Sr  r  r  r2   ra  lasts         r6   $_should_send_telegram_lobby_reminderz2GatewayRunner._should_send_telegram_lobby_reminder  s     t:;; 	2/1D,fn*++ 	4oo/33GSAA:@@@547(1trB   c                     	 dS )Na  This main chat is reserved for system commands.

To start a new Hermes chat, open the All Messages topic at the top of this bot interface and send any message there. Telegram will create a new topic for that message; each topic works as an independent Hermes session.r,  r"  s    r6   "_telegram_topic_root_lobby_messagez0GatewayRunner._telegram_topic_root_lobby_message  s    *	
 	
rB   c                     	 dS )Na0  To start a new parallel Hermes chat, open the All Messages topic at the top of this bot interface and send any message there. Telegram will create a new topic for it.

Each topic is an independent Hermes session. Use /new inside an existing topic only if you want to replace that topic's current session.r,  r"  s    r6    _telegram_topic_root_new_messagez.GatewayRunner._telegram_topic_root_new_message  s    W	
 	
rB   c                 6    |                      |          sd S 	 dS )NzStarted a new Hermes session in this topic.

Tip: for parallel work, open All Messages and send a message there to create a separate topic instead of using /new here. /new replaces the session attached to the current topic.)r  r  r  s     r6   _telegram_topic_new_headerz(GatewayRunner._telegram_topic_new_header  s,    ++F33 	49	
 	
rB   c                 &   t          | dd          }||j        r|j        sdS t          |d|          }|                    t	          |j                  t	          |j                  t	          |j        pd          |j        |j                   dS )zEPersist the Telegram topic -> Hermes session binding for topic lanes.r)   Nr*   r   )r  rd  r  r  r%   )r-   r  rd  bind_telegram_topicrU   r  r  r%   )r  r  session_entryr3   s       r6   _record_telegram_topic_bindingz,GatewayRunner._record_telegram_topic_binding  s     T=$77
V^6;KFZ
;;
&&''&*++,"--%1$/ 	' 	
 	
 	
 	
 	
rB   rj  c                    |                      |          sdS 	 |                     ||           dS # t          $ r! t                              d|d           Y dS w xY w)u4  Update the topic binding to point at ``session_entry.session_id``.

        Telegram topic lanes persist a (chat_id, thread_id) -> session_id row
        so reopening a topic in a fresh process resumes the right Hermes
        session. When compression rotates ``session_entry.session_id`` mid-turn,
        the binding goes stale and the next inbound message in that topic
        reloads the oversized parent transcript instead of the compressed
        child, retriggering preflight compression — sometimes in a loop
        (#20470, #29712, #33414).
        Nz*telegram topic binding refresh failed (%s)Tr   )r  r2  r.   r/   r0   )r  r  r1  rj  s       r6   r  z*GatewayRunner._sync_telegram_topic_binding2  s    " ++F33 	F	//FFFFF 	 	 	LL<ft       	s   1 'AAc                    |j         t          j        k    s.|j        dk    s#|j        r|j        r|                     |          sdS t          |j        pd          }| p|| j	        v }|sdS t          | dd          }|dS t          |d|          }	 |                    t          |j                            }n-# t          $ r  t                              dd	           Y dS w xY w|sdS t          |j                  }|D ]]}t          |                    d
          pd          |k    r3t          |                    d          pd          }|r
||k    r|c S  dS ^dS )aO  Pin DM-topic routing to the user's last-active topic.

        Telegram can omit ``message_thread_id`` or surface General (``1``)
        for some topic-mode DM replies. In those lobby-shaped cases, keep the
        conversation attached to the user's most-recent bound topic.

        Do not rewrite a non-lobby, previously-unbound thread id: a newly
        created Telegram DM topic is also "unknown" until the first inbound
        message is recorded, and rewriting it would send that brand-new topic's
        answer into an older lane. Returns None to leave the source alone.
        r~  Nr   r)   r*   r  ztopic-recover: read failedTr   r  rd  )r_   r  r  r}  r  r  r  rU   rd  r  r-   %list_telegram_topic_bindings_for_chatr.   r/   r0   rT   )	r  r  inboundis_lobbyr3   bindingsr  b	recovereds	            r6   !_recover_telegram_topic_thread_idz/GatewayRunner._recover_telegram_topic_thread_idL  s     Ox0004''> (> ( 44V<< (
 4f&,"--;M'T-M"M 	
 4T=$77
4Z
;;
	!GGFN++ H  HH  	 	 	LL5LEEE44	  	4fn%% 	 	A155##)r**g55k 2 2 8b99	 %g!5!5$$$$tt	 6
 ts   (B< <&C&%C&c                     	 |                      |          }n# t          $ r |cY S w xY w||S t          j        ||          S )u  Apply Telegram DM topic recovery to a source for session-key purposes.

        ``_handle_message_with_agent`` rewrites ``source.thread_id`` via
        ``_recover_telegram_topic_thread_id`` *before* deriving the session
        key for a normal message turn (a lobby/stripped reply gets pinned to
        the user's last-active topic).  Session-scoped command handlers like
        ``/model`` and ``/reasoning`` derive their override key from the raw
        inbound ``event.source``, which skips that recovery — so the override
        is stored under a different key than the next message turn reads,
        and the override is silently dropped on Telegram forum topics and
        after compression session splits (#30479).

        Returns a recovery-normalized copy when a rewrite applies, otherwise
        the original source unchanged.  Always derive the override storage key
        from the result so storage and read use an identical key.
        Nrd  )r;  r.   dataclassesrJ  )r  r  r:  s      r6   !_normalize_source_for_session_keyz/GatewayRunner._normalize_source_for_session_key  sa    (	>>vFFII 	 	 	MMM	M"6Y????s    ''r  r  c          
      	   |}|s+|)	 |                      |          }n# t          $ r d}Y nw xY wt          |          }|r|                     |           |r|                     |          nd}|r|j        j        nd}|r7|                    d|          }|                    d          |                    d          |                    d          |                    d          |                    d          |                    d          d	}	|	                    d          rq|	                    d          %t          |                    d                    |	d<   t          
                    d
|pd|||	                    d                     ||	fS t          
                    d|pd||           ndt          
                    d|pd|d t          |                                                                           D             dd         pd           t                      }
|
                    dd          }|rt                              d||           |}t#          | dd          }|r||j        rt'          |j                  nd}t#          |dd          rt'          |j                  nd}t#          |dd          rt'          |j                  nd}t-          ||j        |||          }|rJ|j        r|j        }|j        r5t5          |j                  }
|
                    dd          }|r	|j        s|}|r|r|                     |||
          \  }}
|sb|
                    d          rM	 ddlm}  ||
d                   }|r"t                              d||
d                    n# t          $ r Y nw xY w|sq|r|                     |          nd}|                     d          }|r|j        j        ndp|r|j        j        nd}|r t                              d|pd|           |}nB|r@|r||                      |          j        _        ||                      d          j        _        ||
fS )u   Resolve model/runtime for a session.

        Priority (highest first): session ``/model`` → ``channel_overrides`` →
        global config/env (``_resolve_gateway_model(user_config)`` and default
        provider resolution).
        Nr  r  r  r  r  r|  r  )r  r  r  r  r|  r  zZSession model override (fast): session=%s config_model=%s -> override_model=%s provider=%sr   z[Session model override (no api_key, fallback): session=%s config_model=%s override_model=%szFNo session model override: session=%s config_model=%s override_keys=%sc                 0    g | ]\  }}|j         j        |S r;   )conversationmodel_override)r?   _key_sts      r6   r  z@GatewayRunner._resolve_session_agent_runtime.<locals>.<listcomp>  s2       !c'6B BBBrB   r{  z[]z;Runtime provider supplied explicit model override: %s -> %srX   rd  r  rc  r   )get_default_model_for_provideru8   No model configured — defaulting to %s for provider %sr  u{   Empty model resolved for session=%s — recovering last-known-good model %s (config read likely returned empty; see #35314))!r  r.   rb  !_rehydrate_session_model_overrider  rB  rC  rT   r  r/   r0   r  r  r  r  r$  r  r-   r  rU   rd  r  rn  r_   r  r  r  _apply_session_model_overridehermes_cli.modelsrF  last_resolved_modelr   r  )r  r  r  r  resolved_session_keyr  _override_staterD  override_modeloverride_runtimer  runtime_modelrk  r  rd  re  chch_runtime_modelrF  	_lr_state_lr_star
_recovereds                         r6   rX  z,GatewayRunner._resolve_session_agent_runtime  s     +# 	,(:,'+'C'CF'K'K$$ , , ,'+$$$, '{33 	I223GHHH $D$$%9::: 	 <KTO(77PT 	  $	%\\'599N$LL44#<<	22$LL44$LL44&ll<88#+<<0A#B#B     ##I.. 
8#''(9::B:W Z00; ;$%67 p(.B~$((44  
 &'777 LLm$*E>   
 LLX$*E %)$*<*<*>*>*D*D*F*F%G%G   1"	     788&**7D99 	"KKM  
 "EdHd++ 	16%-3^Cc&.)))G)0d)K)KUF$%%%QU 
 6#3T::F)*** 
 '##  B  18 %HE; 1%O& &N (6'9'9'4'H'H$ ( 1 1 0 	, 	$($F$F$e^% %!E>  
	++J77 
		LLLLLL66~j7QRR KKR~j9        	N ((()=>>> 
 //44H?HP';;b SAIQH)==r   #) ).B
	   # 	N# ; 6; ##( 2HMD$$1En$$s    --<;N8 8
OOuser_messager  r  c                    ddl m} |                    d          |                    d          |                    d          |                    d          |                    d          |                    d          t          |                    d	          pg           |                    d
          |                    d          d	}||||d         |d         |d         |d         |d         t	          |d	                   fd}t          | dd          }|si |d<   |S 	  ||d                   }n# t          $ r d}Y nw xY w|pi |d<   |S )a2  Build the effective model/runtime config for a single turn.

        Always uses the session's primary model/provider.  If `/fast` is
        enabled and the model supports Priority Processing / Anthropic fast
        mode, attach `request_overrides` so the API call is marked
        accordingly.
        r   )resolve_fast_mode_overridesr  r  r  r~  r  r   r  r  r|  r  )r  r  r]  r]  Nr  r  )rI  rW  rT   r  ra  r-   r.   )	r  rU  r  r  rW  r  router  rl  s	            r6   rc  z(GatewayRunner._resolve_turn_agent_configF  s    	BAAAAA &)))44&**:66&**:66"0"4"45I"J"J&**:66%)))44++F339r::-112CDD(,,\::

 

 
#,-
#
#	"gfo&&
 
 t_d;; 	)+E%&L	33E'NCCII 	 	 	III	%._"!"s   &D8 8EEr%   r   c           
        
 |r	|| j         dS t          |dd          }|sdS t          |dd          t          |dd          t          |dd          t          t          |dd                    d}d	 |                                D             }	 | j         j        }|                    |          }|sdS |                    d          }|                    d
          }	 |rt          j        |          ni }	n# t          $ r i }	Y nw xY wt          |	t                    si }	t          |	                    d          pi           
||k    r/t          
fd|                                D                       rdS ||	d<   |                    |t          j        |	          |           dS # t          $ r  t                              dd           Y dS w xY w)uf  Persist the runtime model/provider actually used by a gateway turn.

        Provider fallback can switch ``agent.model``/``agent.provider`` after the
        session row was created. Keep the session DB metadata in sync so session
        lists, desktop/dashboard details, and follow-up session tooling report the
        backend that actually answered the latest turn.

        Called from the ``run_sync`` closure, which executes off the event loop
        in the executor thread — so the synchronous ``SessionDB`` (``_db``) is
        used directly rather than awaiting the AsyncSessionDB forwarder.
        Nr  r  r  r  _fallback_activatedF)r  r  r  fallback_activec                 "    i | ]\  }}|d v	||S ))Nr   r,  r  s      r6   r  z@GatewayRunner._sync_session_model_from_agent.<locals>.<dictcomp>  s(    KKKDAqq
7J7J1a7J7J7JrB   model_configgateway_runtimec              3   P   K   | ] \  }}                     |          |k    V  !d S r;   r)  )r?   r  r  r^  s      r6   rA   z?GatewayRunner._sync_session_model_from_agent.<locals>.<genexpr>  sK       . .041##A&&!+. . . . . .rB   )r  z-Failed to sync gateway session model metadataTr   )r)   r-   r   r  r*   rh  rT   r  r  r.   rR   rS   r  update_session_metar  r/   r0   )r  r%   r   r  r  dbrowcurrent_model
raw_configrX   r^  s             @r6   r  z,GatewayRunner._sync_session_model_from_agentu  s;     	U]d.>.FFw-- 	Fz488z488z488#GE3H%$P$PQQ	
 
 LKGMMOOKKK	Y!%B..,,C GGG,,M00J3=EJ///2   fd++ "6::.?#@#@#FBGGO%%# . . . .8?. . . + +% (/F$%"":tz&/A/A"OOOOO 	Y 	Y 	YLLHSWLXXXXXX	YsC   #F/ 8*F/ #C< ;F/ <DF/ 
DA1F/ >/F/ /&GGr  c                    K   t          |                    d          pd          }	 | j                            ||           d{V  dS # t          $ r  t
                              dd           Y dS w xY w)u  Fan a normalised platform reaction event out to the HookRegistry.

        Adapters call this via ``set_reaction_handler`` for every
        platform-native reaction event they surface. The adapter-supplied
        ``event_name`` ("reaction:added" / "reaction:removed") becomes the
        hook event so user hooks subscribe with the same name scheme as the
        existing ``agent:*`` family. Errors never block the adapter's event
        loop — the hook contract is non-blocking.
        
event_namezreaction:addedNz#[Gateway] reaction hook emit failedTr   )rU   rT   r  r  r.   r/   r0   )r  r  rf  s      r6   _handle_reaction_eventz$GatewayRunner._handle_reaction_event  s       ..B2BCC
	O*//*c22222222222 	O 	O 	OLL>LNNNNNN	Os   !A &A54A5r  c                 :  K   t          | dd          }|t                      x}| _        t          j        |                     |                    }|                    |           |                    |j                   t          j	        |           d{V  dS )a#  React to an adapter failure after startup.

        If the error is retryable (e.g. network blip, DNS failure), queue the
        platform for background reconnection instead of giving up permanently.

        The notification arrives on the failing adapter's own polling task,
        and the disconnect inside the handler can cancel that task mid-flight:
        disconnect()'s current-task guard misses it because
        _safe_adapter_disconnect runs the close in a wrapper task. A cancelled
        handler dies between the fatal log and the reconnect queue, silently
        stranding the platform (observed 2026-07-21: telegram popped from
        adapters but never queued after a travel network outage). Run the real
        work in a detached task that adapter teardown cannot cancel.
        r  N)
r-   rt   r  r  create_task$_handle_adapter_fatal_error_detachedrv   r  r  shield)r  r  tasksr   s       r6   _handle_adapter_fatal_errorz)GatewayRunner._handle_adapter_fatal_error  s       4d;;=035ED-"4#L#LW#U#UVV		$u}--- nT"""""""""""rB   c                 V  K   	 |                      |           d{V  n5# t          $ r( t                              d|j        j                   Y nw xY w|j        }t          | dd          }|j        o4|| j        vo+|t          | di           vo|duo|	                                 }|rRt          
                    d|j                   |j         d| _        d| _        |                                  d{V  dS dS # |j        }t          | dd          }|j        o4|| j        vo+|t          | di           vo|duo|	                                 }|rQt          
                    d|j                   |j         d| _        d| _        |                                  d{V  w w xY w)zRun the fatal handler; if the platform still ends up stranded
        (not reconnected, not queued, not intentionally disabled), exit the
        gateway with failure so the service manager restarts it instead of
        leaving a silent partial outage.Nz/Fatal-error handling for %s raised unexpectedlyrh  r  zp%s adapter was lost without entering the reconnection queue; exiting gateway so the service manager restarts it.z( adapter lost without reconnection queueT) _handle_adapter_fatal_error_implr.   r/   r   r_   r   r-   fatal_error_retryabler{  r  r  rk  rj  stop)r  r  r_   shutdown_eventstrandeds        r6   rj  z2GatewayRunner._handle_adapter_fatal_error_detached  s_     	"77@@@@@@@@@@ 	 	 	A &    	 'H$T+<dCCN- QDM1QGD2Er$J$JJQ (t3O8M8M8O8OP	   
"QN    ~OOO ! +/'iikk!!!!!!!!!
" 
" 'H$T+<dCCN- QDM1QGD2Er$J$JJQ (t3O8M8M8O8OP	   
"QN    ~OOO ! +/'iikk!!!!!!!!
"s'     C? /AC? AC? ?B)F(c                   K   | j                             |j                  }|3||ur/t                              d|j        j        |j        pd           d S t                              d|j        j        |j        pd|j        pd           |j        dk    rd}n|j	        rd}nd}| 
                    |j        j        ||j        |j        	           ||u rR| j                             |j        d            | j         | j        _         |                     ||j                   d {V  |j	        r| j        j                            |j                  }|rk|j        | j        vr]|d
t#          j                    d| j        |j        <   t                              d|j        j                   |                                  | j         st| j        sm|j        pd| _        |j	        r"d| _        t                              d           nt                              d           |                                  d {V  d S | j         s6| j        r1t                              dt3          | j                             d S d S d S )NzDIgnoring stale fatal error from a superseded %s adapter instance: %sr  zFatal %s adapter error (%s): %sr  relay_disabledr2  retryingfatalplatform_state
error_codeerror_messager   )rX   attempts
next_retryz%%s queued for background reconnectionz#All messaging adapters disconnectedTzSNo connected messaging platforms remain. Shutting down gateway for service restart.zGNo connected messaging platforms remain. Shutting down gateway cleanly.u   No connected messaging platforms remain, but %d platform(s) queued for reconnection — gateway staying alive, watcher will retry in background.)r{  rT   r_   r/   r0   r   fatal_error_coder  fatal_error_messagerp  _update_platform_runtime_statusr$  re  r  rX   r#  r  r,   rb  r  !_ensure_reconnect_watcher_runningrk  rj  rq  r   r   )r  r  existingry  r  s        r6   ro  z.GatewayRunner._handle_adapter_fatal_error_impl  s      =$$W%566HG$;$;LLV &(5I  
 F-"$1	':?		
 	
 	
 #'777'NN* 	%'NN$N,,")/!5	 	- 	
 	
 	
 w Mg.555,0MD ) //9IJJJJJJJJJ ( 	9"k3778HIIO 97#34;Q#Q#Q- !"&."2"2< <&w'78
 ;$*   66888} 	T%; 	 ' ; d?dD, h*.'rssssfggg))++ 	4#9 	 NN' D*++	    	 	 	 	rB   c                 T    d| _         || _        | j                                         d S NT)ri  rk  rh  rt   )r  rj  s     r6   _request_clean_exitz!GatewayRunner._request_clean_exitV  s-    !"  """""rB   c                 *    t          | j                  S r;   )r   r  r"  s    r6   _running_agent_countz"GatewayRunner._running_agent_count[  s    4'(((rB   c                 ~    |                                  |                                 z   |                                 z   S )z>All agent work the gateway must expose and drain as one total.)r  _active_cron_job_count_active_api_run_countr"  s    r6   _active_work_countz GatewayRunner._active_work_count^  s@     %%''))++,((**+	
rB   c                 `    	 ddl m} t           |                      S # t          $ r Y dS w xY w)u9  Count of cron jobs currently executing, from the cron scheduler's
        own in-flight tracking (``cron.scheduler._running_job_ids``).

        Cron jobs run through a standalone ``AIAgent`` on the scheduler's own
        thread pool (``cron/scheduler.py::run_job``), entirely outside
        ``self._running_agents`` — the dict every OTHER active-work check on
        this class (``_running_agent_count``, ``_drain_active_agents``) reads.
        Without this, the shutdown drain is structurally blind to in-flight
        cron work: it can report ``active_at_start=0`` and proceed straight
        to killing tool subprocesses while a cron job's terminal command is
        still running (#60432). Best-effort: returns 0 if the cron module
        can't be imported (e.g. a minimal test double for this class).
        r   )get_running_job_ids)r2  r  r   r.   )r  r  s     r6   r  z$GatewayRunner._active_cron_job_countf  sS    	::::::**,,--- 	 	 	11	s    
--c                    	 t          | di                               t          j                  }t          |dd          }t	          |          r%t          dt           |                                ndS # t          $ r Y dS w xY w)a/  Count API-server work that is outside ``_running_agents``.

        The primary API server owns the sole HTTP listener. Secondary multiplex
        profiles cannot create an ``api_server`` adapter because it binds a port,
        so only the primary registry is a supported source of this work.
        r{  active_agent_work_countNr   )r-   rT   r  r  r  r  rF  r.   )r  r  helpers      r6   r  z#GatewayRunner._active_api_run_countz  s    	dJ33778KLLGW&?FFF,4V,<,<C3q#ffhh--(((!C 	 	 	11	s   A4A7 7
BBc                 t   t          d | j        D                       rdS 	 ddlm}  |            dk    rdS n,# t          $ r t
                              dd           Y nw xY w	 ddlm} |	                                rdS |j
        rdS n,# t          $ r t
                              dd           Y nw xY wd	S )
an  Live background work that must block a suspend (D3/F7).

        Backgrounded delegate_task / kanban / terminal(background=true) are NOT
        counted by _running_agent_count(), but suspending mid-flight loses them.
        Checks the runner's own tracked tasks + the process registry's running
        processes + any pending process-completion watchers.
        c              3   6   K   | ]} |j                      V  d S r;   )r  )r?   r   s     r6   rA   zHGatewayRunner._scale_to_zero_has_live_background_work.<locals>.<genexpr>  s,      <<61688|<<<<<<rB   Tr   )active_countz+scale-to-zero async-delegation check failedr   r  z"scale-to-zero bg-work check failedF)r  r  tools.async_delegationr  r.   r/   r0   r  r  has_any_activepending_watchers)r  r  r  s      r6   '_scale_to_zero_has_live_background_workz5GatewayRunner._scale_to_zero_has_live_background_work  s"    <<T%;<<<<< 	4	W;;;;;;|~~!!t " 	W 	W 	WLLFQULVVVVV	W	N??????..00 t0 t 	N 	N 	NLL=LMMMMM	Nus'   9 &A"!A"&B B &B54B5c                 p   ddl m} d }	 t                      }t          |t                    r|                    d          nd }t          |t                    r|                    d          nd }t          |t                    r|                    d          }n# t          $ r d }Y nw xY w ||          S )Nr   )parse_idle_timeout_secondsr1   scale_to_zeroidle_timeout_minutes)gateway.scale_to_zeror  rQ   rR   rS   rT   r.   )r  r  rV  user_cfgr  stzs         r6   #_scale_to_zero_idle_timeout_secondsz1GatewayRunner._scale_to_zero_idle_timeout_seconds  s    DDDDDD	+--H,6x,F,FPi(((DB-7D-A-AK"&&)))tC#t$$ 6gg455 	 	 	CCC	))#...s   BB B*)B*c                 $   ddl m} |j        }|j        }	 t	                      }t          |t                    r|                    d          nd}t          |t                    r|                    d          nd}t          |t                    rlt          |                    d          t                    r|d         }t          |                    d          t                    r|d         dk    r|d         }n# t          $ r Y nw xY w||fS )a  Return ``(max_restarts, window_seconds)`` for the auto-resume
        restart-loop breaker (#30719, defense-3), read from
        ``gateway.restart_loop_guard`` in config.yaml with the module defaults
        as fallback. ``max_restarts <= 0`` disables the breaker.
        r   restart_loop_guardr1   Nr  max_restartswindow_seconds)
r1   r  DEFAULT_MAX_RESTARTSDEFAULT_WINDOW_SECONDSrQ   rR   rS   rT   rF  r.   )r  _rlgr  r  r  r  rlgs          r6   _restart_loop_guard_configz(GatewayRunner._restart_loop_guard_config  s"    	76666604
	+--H,6x,F,FPi(((DB2<R2F2FP"&&-...DC#t$$ ;cggn55s;; 7#&~#6Lcgg&677== ;#FVBWZ[B[B[%()9%:N 	 	 	D	^++s   C'C> >
D
Dc                 &   ddl m} ddlm}m}m} 	 | j        r(d | j        j                                        D             ng }n# t          $ r g }Y nw xY w	  |            }n# t          $ r d}Y nw xY w | |             ||          |          S )u4   Whether to start the idle watcher (D1/D11/§3.4(1)).r   relay_wake_url)!messaging_is_relay_only_or_absentscale_to_zero_enabled
should_armc                 :    g | ]\  }}t          |d d          |S )r  FrC  r?   r  pcs      r6   r  z;GatewayRunner._scale_to_zero_should_arm.<locals>.<listcomp>  s.    ___uq"YX]A^A^____rB   N)r  relay_only_or_absentwake_url)
gateway.relayr  r  r  r  r  rX   r#  r  r.   )r  r  r  r  r  r#  r  s          r6   _scale_to_zero_should_armz'GatewayRunner._scale_to_zero_should_arm  s   000000	
 	
 	
 	
 	
 	
 	
 	
 	
 	
	 ;__ 5 ; ; = =____ I
  	 	 	III		%~''HH 	 	 	HHH	z))++!B!B9!M!M
 
 
 	
s#   1A AA
A" "A10A1c                    ddl m} ddlm}m} 	  |            }|sdS 	 | j        r(d | j        j                                        D             ng }n# t          $ r g }Y nw xY w ||          }	  |            }n# t          $ r d}Y nw xY wt          
                    d||pd|rdnd	           dS # t          $ r  t                              d
d           Y dS w xY w)u  Log why the idle watcher did NOT arm — but only for an OPTED-IN instance.

        A non-opted instance (no HERMES_SCALE_TO_ZERO stamp) not arming is the normal
        case and must stay silent. When the Labs stamp IS set but the watcher still
        didn't arm, that's the surprising case worth one INFO line so "why won't it
        suspend/wake?" is a log grep, not a box-dive.
        r   r  )r  r  Nc                 X    g | ]'\  }}t          |d d          t          |d|          (S )r  Fr   rC  r  s      r6   r  zEGatewayRunner._log_scale_to_zero_not_armed_reason.<locals>.<listcomp>  sJ       !Ar"2y%887A..  rB   u   scale-to-zero: NOT armed despite opt-in — relay_only_or_absent=%s (enabled platforms=%s), wake_url=%s. Need relay-only messaging + a registered wake URL.nonert   MISSINGz.scale-to-zero: not-armed reason logging failedTr   )r  r  r  r  r  rX   r#  r  r.   r/   r  r0   )r  r  r  r  r  active
relay_onlyr  s           r6   #_log_scale_to_zero_not_armed_reasonz1GatewayRunner._log_scale_to_zero_not_armed_reason  s    	100000	
 	
 	
 	
 	
 	
 	
 	

	Z++--G  {  %)[%:%@%@%B%B         ::6BBJ )>++       KKE  &!0y      	Z 	Z 	ZLLITXLYYYYYY	ZsX   B1 1A B1 A B1 A  B1 /
A: 9B1 :B	B1 B		&B1 1&CCc                     ddl m}  ||                                 t          j                    | j        z
  |                                 |                                           S )Nr   )is_idle)running_agent_countseconds_since_last_inboundidle_timeout_secondshas_live_background_work)r  r  r  r,   r  r  r  )r  r  s     r6   _scale_to_zero_is_idlez$GatewayRunner._scale_to_zero_is_idle!  sk    111111w $ 9 9 ; ;'+y{{T5J'J!%!I!I!K!K%)%Q%Q%S%S	
 
 
 	
rB   c                     t          j                     | _        t          | dd          dk    rL	 |                     d           n,# t          $ r t
                              dd           Y nw xY wd| _        dS dS )	a  Stamp real inbound and restore lifecycle after a dormant wake.

        The watcher marks runtime status `draining` as it quiesces the relay, but
        dormancy is not the stop/restart drain path: the process remains alive and
        should present as running once real traffic wakes it and re-enters the
        gateway. Internal completion/replay events intentionally do not call this
        helper, so they do not keep an otherwise idle gateway awake.
        r  r  r   runningz$scale-to-zero: status restore failedTr   N)r,   r  r-   _update_runtime_statusr.   r/   r0   r  r"  s    r6    _scale_to_zero_note_real_inboundz.GatewayRunner._scale_to_zero_note_real_inbound+  s     !%	48#>>BBT++I6666 T T TCdSSSSST14D... CBs   A &A.-A.c                 r    	 ddl m} n# t          $ r Y dS w xY w| j                            |j                  S )zHReturn the connected RELAY adapter, if any (the one go_dormant targets).r   r  N)gateway.platforms.baser  r.   r{  rT   RELAY)r  r  s     r6   _relay_adapter_for_dormancyz)GatewayRunner._relay_adapter_for_dormancy<  sV    	7777777 	 	 	44	}  000s   	 
intervalc                   K   t          j        t          |d                     d{V  | j        r	 t          j        |           d{V  | j        sdS t	          j                    | j        k     rI|                                 s^|                                 }|ut          |dd          }t          |          st                              d|                                            	 |                     d           n,# t          $ r t                              dd           Y nw xY w	  |            }t          j        |          r| d{V  n,# t          $ r t                              d	d           Y nw xY wt	          j                    t#          |d
          z   | _        n;# t           j        $ r  t          $ r t                              dd           Y nw xY w| j        dS dS )u>  Watch for idle and drive the relay dormant so the platform can suspend.

        Started ONLY when _scale_to_zero_should_arm() (opted in via the Labs
        HERMES_SCALE_TO_ZERO stamp + relay-only/absent messaging + a wakeUrl).
        On a sustained idle window it runs the DORMANT sequence (D12/F12/F14):
          - mark runtime status `draining` (composes with the existing state
            machine, §3.4(6); does NOT set _running=False),
          - relay adapter.go_dormant() — going_idle->ack + supervisor-preserving
            socket close (NOT disconnect(), NOT the run.py stop path),
          - deliberately NO mark_resume_pending (D13 — suspend preserves RAM).
        The process stays alive; the platform (Fly autostop:"suspend") suspends
        the now-traffic-idle machine and autostart wakes it on the wakeUrl poke,
        at which point the preserved reconnect supervisor re-dials and the
        connector drains the buffered backlog. After driving dormant we set a
        re-arm cooldown so a wake's drained backlog isn't immediately re-quiesced.
        r"   N
go_dormantuu   scale-to-zero: gateway idle for >= %.0fs — going dormant (relay buffered, socket closed, awaiting platform suspend)drainingz!scale-to-zero: status mark failedTr   z scale-to-zero: go_dormant failedg      N@z%scale-to-zero watcher iteration error)r  r`  r  rf  r,   r  r  r  r-   r  r/   r  r  r  r.   r0   iscoroutiner  rf  )r  r  r  r  r  s        r6   _scale_to_zero_watcherz$GatewayRunner._scale_to_zero_watcherD  st     " mC$//000000000m %	U$UmH---------} F9;;!CCC2244 ::<<?$WlDAA

++ Q<<>>  
U//
;;;;  U U ULL!DtLTTTTTUT'Z\\F*622 %$  T T TLL!CdLSSSSST
 6:Y[[3xQUCVCV5V22)    U U UDtTTTTTUI m %	U %	U %	U %	U %	Usw   !F/ F/ 4F/ 	F/   F/ -F/ /D F/ &D.+F/ -D..F/ 2&E F/ &F?F/ F,F/ /5G'&G'c                     | j         rdndS )Nrestartshutdownr  r"  s    r6   _status_action_labelz"GatewayRunner._status_action_label}  s     3CyyCrB   c                     | j         rdndS )N
restartingshutting downr  r"  s    r6   _status_action_gerundz#GatewayRunner._status_action_gerund  s    #6K||OKrB   c                 "    | j         o| j        dv S )N>   rd  steer)r  r  r"  s    r6   _queue_during_drain_enabledz)GatewayRunner._queue_during_drain_enabled  s     &V4+@DV+VVrB   queued_eventr:  c                     |dS t          |dd          }|dS ||v r4|                     |          j        j                            |           dS |||<   dS )z6Append a /queue event to the FIFO chain for a session.Nr  )r-   r  rB  queued_eventsrs   )r  r  r  r  pending_slots        r6   _enqueue_fifozGatewayRunner._enqueue_fifo  s    ?Fw(;TBBF,&&,,9GNN     )5L%%%rB   pending_eventc                     |                      |          }|r|j        j        nd}|s|S |                    d          }||S |t	          |d          r||j        |<   n|                    d|           |S )aY  Promote the next overflow item after the slot was drained.

        Called at the drain site after _dequeue_pending_event consumed
        (or failed to consume) the slot.  If there's an overflow item:
          - When pending_event is None (slot was empty), return the
            overflow head as the new pending_event.
          - When pending_event already exists (slot was populated by an
            interrupt follow-up or similar), stage the overflow head in
            the slot so the NEXT recursion picks it up.
        Returns the (possibly updated) pending_event for drain to use.
        Nr   r  )r  rB  r  r$  r   r  ry   )r  r  r  r  _q_stateoverflownext_queueds          r6   _promote_queued_eventz#GatewayRunner._promote_queued_event  s    " ++K88:BL8(66 	!  ll1oo 774G#H#H5@G%k22 OOA{+++rB   r  c                    |                      |          }|rt          |j        j                  nd}||t	          |di           v r|dz  }|S )u=   Total pending /queue items for a session — slot + overflow.r   Nr  rk   )r  r   rB  r  r-   )r  r  r  r  r   s        r6   _queue_depthzGatewayRunner._queue_depth  s^    ++K88<DKH)7888!;''CVXZ2[2[#[#[QJErB   event_or_textc                 l    t          | d|           pd}t          |                              d          S )zReturn True for synthetic /goal continuation turns.

        Goal continuations are normal queued user-role events, so pause/clear
        must distinguish them from real user /queue messages before removing or
        suppressing them.
        r   r   z,[Continuing toward your standing goal]
Goal:)r-   rU   r   )r  r   s     r6   _is_goal_continuation_eventz)GatewayRunner._is_goal_continuation_event  s5     }fm<<B4yy##$STTTrB   c                    d}|t          |dd          nd}t          |t                    rE|                    |          }|                     |          r|                    |d           |dz  }|                     |          }|r|j        j        ng }|rCg }|D ]2}	|                     |	          r|dz  }|	                    |	           3||j        _        |S )a  Remove queued synthetic /goal continuations for one session.

        User-issued /goal pause/clear can race with a continuation already
        queued by the judge.  Remove only synthetic goal continuations while
        preserving normal /queue and user follow-up events.
        r   Nr  rk   )
r-   rR   rS   rT   r  r$  r  rB  r  rs   )
r  r  r  removedr  r  r  r  keptr  s
             r6   !_clear_goal_pending_continuationsz/GatewayRunner._clear_goal_pending_continuations  s
    FMFYww(;TBBB_clD)) 	(,,[99M//>>   d3331++K88:BJ8(66 	7D ( . .33LAA .qLGGKK----26H!/rB   c                     |sdS 	 ddl m}  ||                                          S # t          $ r&}t                              d|           Y d}~dS d}~ww xY w)z@Best-effort fresh DB check before running a queued continuation.Fr   GoalManagerr5  z2goal continuation: active-state recheck failed: %sN)hermes_cli.goalsr  	is_activer.   r/   r0   )r  r%   r  r5   s       r6   _goal_still_active_for_sessionz,GatewayRunner._goal_still_active_for_session  s     	5	444444;*555??AAA 	 	 	LLMsSSS55555	s   #* 
AAAgateway_stater  c                     	 ddl m}  |||| j        |                                            d S # t          $ r Y d S w xY w)Nr   write_runtime_status)r  r  restart_requestedactive_agents)gateway.statusr  r  r  r.   )r  r  r  r  s       r6   r  z$GatewayRunner._update_runtime_status  s|    		;;;;;;  +'"&"9"5577	       	 	 	DD	s   ,0 
>>c                 r    	 ddl m}  ||                                            dS # t          $ r Y dS w xY w)u]  Persist the live in-flight agent count to ``gateway_state.json``.

        Called at every turn boundary (a running-agent slot is claimed or
        released) so the dashboard ``/api/status`` readout reflects in-flight
        gateway turns in near-real-time.  Without this the file is only
        rewritten on lifecycle transitions, so any ``active_agents`` read
        between transitions is stale (a turn could start and finish without the
        file ever moving).

        Deliberately passes ONLY ``active_agents`` — ``gateway_state`` and the
        other fields stay ``_UNSET`` so ``write_runtime_status``'s
        read-merge-write preserves the current lifecycle state (``running`` /
        ``draining`` / …).  Passing ``gateway_state=None`` here would clobber it.
        Best-effort: a failed status write must never disrupt a turn.
        r   r  )r  N)r 	  r  r  r.   )r  r  s     r6   _persist_active_agentsz$GatewayRunner._persist_active_agents  sa     	;;;;;;  t/F/F/H/HIIIIII 	 	 	DD	s   $( 
66c                     | j         rdS d| _         t                              d|                                            |                     d           dS )u)  Begin external drain: stop accepting new turns, flip state.

        Idempotent — re-entering while already draining is a no-op beyond a
        best-effort status re-write. In-flight turns are NOT interrupted (the
        whole point is to let them finish); only NEW turns are refused.
        NTu   External drain ENGAGED (.drain_request.json present) — refusing new turns; %d in-flight turn(s) will finish. Process stays up.r  )r  r/   r  r  r  r"  s    r6   _enter_external_drainz#GatewayRunner._enter_external_drain&  sc     & 	F&*#M##%%	
 	
 	
 	##J/////rB   c                     | j         sdS d| _         | j        s| j        st                              d           dS t                              d           |                     d           dS )u  Cancel external drain: revert state, re-accept new turns.

        Idempotent. Only reverts to ``running`` when we are actually mid-drain
        AND not also shutting down (a real shutdown ``_draining`` must win —
        never resurrect a stopping gateway to ``running``).
        NFug   External drain marker cleared during shutdown — not reverting to running (shutdown takes precedence).uk   External drain RELEASED (.drain_request.json removed) — re-accepting new turns; gateway_state -> running.r  )r  r  rf  r/   r  r  r"  s    r6   _exit_external_drainz"GatewayRunner._exit_external_drain:  s     * 	F&+#> 	 	 KK:   F@	
 	
 	
 	##I.....rB         ?c                   K   ddl m} | j        r	  |            r)|                                  |                                  n|                                  nC# t          j        $ r  t          $ r'}t          
                    d|d           Y d}~nd}~ww xY wt          j        |           d{V  | j        dS dS )uN  Background task: reconcile gateway accept-state with the drain marker.

        Polls ``.drain_request.json`` (presence-based contract,
        gateway/drain_control.py). Marker present -> ``_enter_external_drain``;
        marker absent -> ``_exit_external_drain``. The 1s cadence bounds the
        observe-the-marker latency the live-validation gate checks (point a).
        Reconciles once at startup. A marker stamped with a PRIOR
        instantiation epoch (one that survived a machine restart on the durable
        HERMES_HOME volume — NS-570) is treated as absent by ``drain_requested``
        and is NOT honoured; only a marker from the current instantiation flips
        the gateway into drain. Best-effort: any tick error is logged and the
        loop continues (a transient stat() failure must not wedge the gateway).
        r   )drain_requestedz$Drain-control watcher tick error: %sTr   N)gateway.drain_controlr		  rf  r	  r	  r	  r  rf  r.   r/   r0   r`  )r  r  r		  r5   s       r6   _drain_control_watcherz$GatewayRunner._drain_control_watcherR  s      	:99999m 	*Y"?$$ 0..000 //1111--///)    Y Y YCSSWXXXXXXXXY-))))))))) m 	* 	* 	* 	* 	*s   AA B2BBrx  ry  rz  r{  c                T    	 ddl m}  |||||           d S # t          $ r Y d S w xY w)Nr   r  )r_   ry  rz  r{  )r 	  r  r.   )r  r_   ry  rz  r{  r  s         r6   r  z-GatewayRunner._update_platform_runtime_statusr  sm    		;;;;;;  !-%+	       	 	 	DD	s    
''r6  c                   t          | di                               |          }|dS |                    d          rdS d|d<   |pd|d<   t          d          |d<   	 |                     |j        dd|d         	           n# t
          $ r Y nw xY wt                              d
|j        |                    dd          |d         |j                   dS )u"  Mark a queued platform as paused — keep it in ``_failed_platforms``
        but stop the reconnect watcher from hammering it.

        Used by ``/platform pause <name>`` for manual operator intervention.
        Paused platforms are surfaced in ``/platform list`` and resumed with
        ``/platform resume <name>``.  Note: the reconnect watcher does NOT
        auto-pause — retryable (network/DNS) failures keep retrying at the
        backoff cap indefinitely so a transient outage self-heals without
        manual intervention.
        r  NpausedTz#auto-paused after repeated failurespause_reasoninfr}  rx  u   %s paused after %d consecutive failures (%s) — fix the underlying issue then run `/platform resume %s` to retry, or `hermes gateway restart` to restart the gateway.r|  r   )r-   rT   rG  r  r   r.   r/   r   )r  r_   rj  r  s       r6   _pause_failed_platformz$GatewayRunner._pause_failed_platform  s    t0"5599(CC<F88H 	FX%N)N^ #5\\\	00'">2	 1      	 	 	D	L NDHHZ33 (.	
 	
 	
 	
 	
s   $B 
BBc                    t          | di                               |          }|dS |                    d          sdS d|d<   |                    dd           d|d<   t          j                    |d<   	 |                     |j        d	dd
           n# t          $ r Y nw xY wt          	                    d|j                   dS )u   Unpause a platform — reset its attempt counter and schedule an
        immediate retry.  Returns True if the platform was paused and is
        now queued; False if it wasn't paused (or wasn't in the queue).
        r  NFr	  r	  r   r|  r}  rv  rx  u,   %s resumed — retrying on next watcher tickT)
r-   rT   r$  r,   rb  r  r   r.   r/   r  )r  r_   r  s      r6   _resume_paused_platformz%GatewayRunner._resume_paused_platform  s    
 t0"5599(CC<5xx!! 	5X&&&Z!^--\	00)"	 1      	 	 	D	BHNSSSts   7B 
B#"B#c                     t          j        dd          } | sWt                      }t          |                    dd          pd          } | s"t          t          |ddd          pd          } | sg S t          |                                           }|                                s
t          |z  }|
                                st                              d|           g S 	 t          |dd	          5 }t          j        |          }d
d
d
           n# 1 swxY w Y   t!          |t"                    st                              d|           g S |S # t$          $ r(}t                              d||           g cY d
}~S d
}~ww xY w)a\  Load ephemeral prefill messages from config or env var.
        
        Checks HERMES_PREFILL_MESSAGES_FILE env var first, then falls back to
        the top-level prefill_messages_file key in ~/.hermes/config.yaml.
        agent.prefill_messages_file is accepted as a legacy fallback.
        Relative paths are resolved from ~/.hermes/.
        HERMES_PREFILL_MESSAGES_FILEr   prefill_messages_filer   r@  z#Prefill messages file not found: %srI  r  rJ  Nz3Prefill messages file must contain a JSON array: %sz+Failed to load prefill messages from %s: %s)rq   r  r  rU   rT   r   r   
expanduseris_absoluter;  rw   r/   r   ra  r  loadrR   r  r.   )	file_pathrk  rx   rP  r  rs  s         r6   rU  z$GatewayRunner._load_prefill_messages  s    I<bAA	 	b.00CCGG$;R@@FBGGI bW6MWY Z Z Z `^`aa	 	II))++!! 	'$&D{{}} 	NN@$GGGI		dC'222 $ay||$ $ $ $ $ $ $ $ $ $ $ $ $ $ $dD)) TVZ[[[	K 	 	 	NNH$PQRRRIIIIII	sH   $E 6DE DE D4E E 
F F=FFc                      t          j        dd          } | r| S t                      }t          t	          |ddd          pd                                          S )zLoad ephemeral system prompt from config or env var.
        
        Checks HERMES_EPHEMERAL_SYSTEM_PROMPT env var first, then falls back to
        agent.system_prompt in ~/.hermes/config.yaml.
        HERMES_EPHEMERAL_SYSTEM_PROMPTr   r   r   r@  )rq   r  r  rU   r   rV   )promptrk  s     r6   rV  z+GatewayRunner._load_ephemeral_system_prompt  s^     ;R@@ 	M*,,73"EEEKLLRRTTTrB   )r  rd  re  rd  re  c                    ddl m} d}t          | dd          }|rt          |||||          } |d|t	          |                    S )u  Resolve model for this channel: channel_overrides else global default.

        Delegates the precedence rule to
        :func:`hermes_cli.model_switch.resolve_effective_model` (session
        override > channel override > global default) — the single owner
        shared with the API server, so the two surfaces cannot diverge
        again (see 7dd00bb47d).  This call site has no session tier: session
        /model overrides are applied later by
        ``_apply_session_model_override`` on the resolved runtime.
        r   )resolve_effective_modelNrX   rc  )hermes_cli.model_switchr	  r-   rn  rb  )	r  r_   r  r  rd  re  r	  rD  rX   s	            r6   _resolve_model_for_channelz(GatewayRunner._resolve_model_for_channel  s    & 	DCCCCCx.. 	,##  H '&";//
 
 	
rB   rc  c                    t          | dd          }|r8t          |||||          }|r"|j        r|j        pd                                S t          | dd          pdS )aE  Ephemeral system prompt for this channel/thread.

        Uses ``channel_overrides`` when set, else the global gateway prompt.
        Legacy ``channel_prompts`` are applied separately via ``event.channel_prompt``
        in ``run_sync`` (adapter ``resolve_channel_prompt``), so they are not
        duplicated here.
        rX   Nrc  r   rW  )r-   rn  r   rV   )r  r_   r  rd  re  rX   rD  s          r6   rW  z,GatewayRunner._get_system_prompt_for_channel  s     x.. 		>,##  H  >H2 > .4";;===t7>>D"DrB   c                 B    ddl m} t                      } |||           S )a  Load reasoning effort from config.yaml, respecting per-model overrides.

        Thin wrapper over the shared chokepoint
        :func:`hermes_constants.resolve_reasoning_config` (per-model override >
        global ``agent.reasoning_effort``; YAML boolean False = disabled).
        Closes #21256.

        Args:
            model: The effective model for the calling session. When empty,
                   the config's ``model.default`` is used.
        r   )resolve_reasoning_config)r  r$	  r  )r  r$	  rk  s      r6   rX  z$GatewayRunner._load_reasoning_config:  s4     	>=====*,,''U333rB   raw_argsc                    ddl }t          | pd                                                              dd          }|sdS 	  |j        |          }n$# t
          $ r |                                }Y nw xY wd}g }|D ] }|dk    rd	}|                    |           !d
                    |                                                                          |fS )zParse `/reasoning` args into `(value, persist_global)`.

        `/reasoning <level>` is session-scoped by default. `--global` may be
        supplied in any position to persist the change to config.yaml.
        r   Nr   u   —z--)r   FFz--globalTrn  )	shlexrU   rV   rJ  rC   rH  rs   rD   rW   )r%	  r'	  r   tokenspersist_globalvalue_tokensr  s          r6   _parse_reasoning_command_argsz+GatewayRunner._parse_reasoning_command_argsK  s     	8>r""((**225$?? 	9	" U[&&FF 	" 	" 	"ZZ\\FFF	"  	+ 	+E
""!%##E****xx%%++--3355~EEs   A A32A3r  c                    |}|s+|)	 |                      |          }n# t          $ r d}Y nw xY w|r/|                     |          }||j        j        |j        j        S |                     |          S )u  Resolve reasoning effort for a session, honoring session overrides.

        Priority: session-scoped ``/reasoning --session`` override >
        per-model override (``agent.reasoning_overrides``) > global
        ``agent.reasoning_effort``. ``model`` should be the session's
        *effective* model (session ``/model`` override included) so
        per-model overrides track what the session actually runs — when
        empty, the config's ``model.default`` is used.
        N)r  r.   r  rB  reasoning_overriderX  )r  r  r  r  rK  _r_states         r6   rZ  z/GatewayRunner._resolve_session_reasoning_confige  s       +# 	,(:,'+'C'CF'K'K$$ , , ,'+$$$,   	@//0DEEH#(=(P(\,??**5111    --r  c                 n    |sdS |dnt          |          |                     |          j        _        dS )z3Set or clear the session-scoped reasoning override.N)rS   r  rB  r-	  )r  r  r  s      r6   _set_session_reasoning_overridez-GatewayRunner._set_session_reasoning_override  sG      	F
 %,DD$7G2H2H 	K((5HHHrB   c                     |}|s+|)	 |                      |          }n# t          $ r d}Y nw xY w|r6|                     |          }||j        j        t
          ur|j        j        S |                                 S )u  Resolve the effective service tier for a session.

        A session-scoped /fast override wins over the config default. The
        override dict stores "priority" or None (explicit normal), so key
        presence — not value truthiness — decides whether it applies.
        N)r  r.   r  rB  service_tier_override_SERVICE_TIER_UNSETrY  )r  r  r  rK  _t_states        r6   r\  z+GatewayRunner._resolve_session_service_tier  s      +# 	,(:,'+'C'CF'K'K$$ , , ,'+$$$,   	C//0DEEH$)?*+ +  ,BB&&(((r/	  r  c                 ^    |sdS |rt           n||                     |          j        _        dS )zSet or clear the session-scoped /fast override.

        ``service_tier`` is "priority" or None (explicit normal). Pass
        ``clear=True`` to remove the override entirely (fall back to config).
        N)r4	  r  rB  r3	  )r  r  r  r  s       r6   "_set_session_service_tier_overridez0GatewayRunner._set_session_service_tier_override  s@      	F $):l 	K((5KKKrB   c                     t                      } t          t          | ddd          pd                                          }|                                }|r|dv rdS |dv rdS t
                              d	|           dS )
a  Load Priority Processing setting from config.yaml.

        Reads agent.service_tier from config.yaml. Accepted values mirror the CLI:
        "fast"/"priority"/"on" => "priority", while "normal"/"off" disables it.
        Returns None when unset or unsupported.
        r   r  r   r@  >   r  r  normalr(  standardN>   rN   fastpriorityr<	  z#Unknown service_tier '%s', ignoring)r  rU   r   rV   rW   r/   r   )rk  rV  r   s      r6   rY  z GatewayRunner._load_service_tier  s     +,,'#wCCCIrJJPPRR		 	!QQQ4...:<cBBBtrB   c                  ^    t                      } t          t          | dd          d          S )z<Load show_reasoning toggle from config.yaml display section.r"  show_reasoningFr@  )r  rJ  r   rk  s    r6   rZ  z"GatewayRunner._load_show_reasoning  s9     +,,C$455
 
 
 	
rB   c                  D   t          j        dd                                                                          } | sTt	                      }t          t          |ddd          pd                                                                          } | dk    rdS | dk    rdS dS )	z<Load gateway drain-time busy-input behavior from config/env.r  r   r"  r  r@  rd  r  r  )rq   r  rV   rW   r  rU   r   )r:  rk  s     r6   r\  z#GatewayRunner._load_busy_input_mode  s     y92>>DDFFLLNN 	e.00CwsI/@"MMMSQSTTZZ\\bbddD7??77??7{rB   c                     t          j        dd                                                                          } | sTt	                      }t          t          |ddd          pd                                                                          } | dk    rdS | dk    rdS t                                          }|dk    rdndS )a  Resolve normal busy TEXT follow-up behavior.

        ``busy_input_mode`` is the single source of truth (default
        ``interrupt``). The legacy ``busy_text_mode`` knob is honored only
        when a user explicitly set it, so existing queue setups keep
        working; new installs follow ``busy_input_mode``. Returns one of
        ``interrupt`` | ``queue`` (``steer`` is handled upstream by
        ``busy_input_mode`` and maps to non-queue text handling here).
        r  r   r"  r  r@  r  rd  )	rq   r  rV   rW   r  rU   r   r  r\  )legacyrk  
input_modes      r6   r]  z"GatewayRunner._load_busy_text_mode  s     :B??EEGGMMOO 	f.00Ci1A2NNNTRTUU[[]]cceeF[  ;W7"88::
$//ww[@rB   c                     t          j        dd                                          } | sBt                      }t	          t          |ddd          pd                                          } t          |           }| rT|t          k    rI	 t          |            n8# t          t          f$ r$ t                              d| t                     Y nw xY w|S )z<Load graceful gateway restart/stop drain timeout in seconds.r  r   r   r  r@  z7Invalid restart_drain_timeout '%s', using default %.0fs)rq   r  rV   r  rU   r   rL  rH  rG  rU  rH  r/   r   )rV  rk  r   s      r6   r^  z)GatewayRunner._load_restart_drain_timeout   s     i6;;AACC 	`.00Cgc7,CRPPPVTVWW]]__C+C00 	5AAAc



z*   M9     s   	B 2CCc                     t          j        d          } | (t          |                                           dk    r| }n!t	                      }t          |ddd          }t          |          }|nt          |                                          dk    rI	 t          |           n8# t          t          f$ r$ t                              d|t                     Y nw xY w|S )z?Load in-band restart wait-for-idle timeout in seconds (#77184).!HERMES_RESTART_AFTER_TURN_TIMEOUTNr   r   restart_after_turn_timeoutr@  z<Invalid restart_after_turn_timeout '%s', using default %.0fs)rq   r  rU   rV   r  r   rK  rG  rU  rH  r/   r   rG  )env_rawrV  rk  r   s       r6   r_  z.GatewayRunner._load_restart_after_turn_timeout   s     )?@@3w<<#5#5#7#72#=#=!CC.00C#w(DdSSSC055 ?s3xx~~//255c



z*   R>     s   B' '2CCc                  @   t          j        dd          } | s9t                      }t          |dd          }|du rd} n|dvrt	          |          } | pd                                                                } h d	}| |vrt                              d
|            dS | S )u  Load background process notification mode from config or env var.

        Modes:
          - ``all``    — push running-output updates *and* the final message (default)
          - ``result`` — only the final completion message (regardless of exit code)
          - ``error``  — only the final message when exit code is non-zero
          - ``off``    — no watcher messages at all
        HERMES_BACKGROUND_NOTIFICATIONSr   r"   background_process_notificationsFr  >   Nr   r  >   r  r  r  r  zBUnknown background_process_notifications '%s', defaulting to 'all')	rq   r  r  r   rU   rV   rW   r/   r   )r:  rk  rV  valids       r6   #_load_background_notifications_modez1GatewayRunner._load_background_notifications_mode-   s     y:B?? 	 .00C#y*LMMCe||J&&3xx$$&&,,..111uNNT   5rB   c                  t    	 t                      } |                     di           pi S # t          $ r Y nw xY wi S )z>Load OpenRouter provider routing preferences from config.yaml.provider_routing)r  rT   r.   r?	  s    r6   r`  z$GatewayRunner._load_provider_routingI   sS    	 /00C77-r228b8 	 	 	D		s   %( 
55c                  l    	 t                      } t          |           }|r|S n# t          $ r Y nw xY wdS )zLoad fallback provider chain from config.yaml.

        Returns the merged effective chain from ``fallback_providers`` plus any
        legacy ``fallback_model`` entries. ``fallback_providers`` stays first
        when both keys are present.
        N)r  r   r.   )rk  fbs     r6   ra  z"GatewayRunner._load_fallback_modelU   sX    	 /00C#C((B 	 	 	 	D	ts    $ 
11c                    	 ddl m} t          dz  }|                                sd| _        | j        S  ||          }	 ddlm}  |j        |          }n# t          $ r Y nw xY w	 ddl m	}  ||          }t          |t                    r|}n# t          $ r Y nw xY wn3# t          $ r& t                              dd	           | j        cY S w xY wt          |          pd| _        | j        S )
a  Re-read fallback_providers from disk for the next agent create/reuse.

        Cron already does this per job via ``get_fallback_chain``; the gateway
        previously froze ``self._fallback_model`` at process start, so a chain
        configured (or changed) after ``hermes gateway`` was running never
        reached messaging sessions even though the same process's cron jobs
        fell back correctly. Fixes #60955.

        A TRANSIENT read/parse failure (user mid-edit of config.yaml with a
        non-atomic write) keeps the last known-good chain instead of wiping a
        cached agent's working fallback for that turn.  Only a successful read
        that genuinely lacks the key clears the chain.
        r   )r]  rZ  Nr^  r_  zRfallback_providers refresh: config.yaml read failed; keeping last known-good chainTr   )rg  r]  r;  rw   rb  rh  r_  ri  r.   r\  rR   rS   r/   r0   r   )r  r]  cfg_pathrk  r_  r\  r`  s          r6   rn  z%GatewayRunner._refresh_fallback_modelh   sr   	(>>>>>>#m3H??$$ ,'+$++
 '&x00C4444449m9#>>   >>>>>>++C00h-- #"C    	( 	( 	(LL0:>     ''''	(  2#66>$##s^   1B" B"  A B" 
A$!B" #A$$B" ((B B" 
BB" BB" "-CCchainc                    | dS t          |pg           }t          | dd          pd}t          | dd          r|t          j                    k    rdS t          t          | dg           pg           }|| _        |r|d         nd| _        t          | dd          sd| _        ||k    r)t          | dd          }|r|                                 dS dS dS )u  Keep a cached agent's fallback chain aligned with current config.

        Skips rewrite while a cooldown is holding the agent on an already-
        activated fallback provider — ``restore_primary_runtime`` owns that
        turn-scoped lifecycle. When primary is active (or cooldown expired),
        replace the chain so mid-uptime ``fallback_providers`` edits take
        effect without requiring a gateway restart (#60955).
        N_rate_limited_untilr   rZ  F_fallback_chain_unavailable_fallback_keys)r  r-   r,   rb  rW	  rb  _fallback_indexr  )r   rT	  	new_chainrate_limited_until	old_chainunavailables         r6   rm  z,GatewayRunner._apply_fallback_chain_to_agent   s    =F"%%	$U,A1EEJE0%88	"T^%5%555F(92>>D"EE	 )09 C	!tu3U;; 	&$%E! 	!!!%)EtLLK $!!##### "!$ $rB   c                 >    d |                                  D             S )Nc                 ,    i | ]\  }}|t           u||S r,  )ri  )r?   r  r   s      r6   r  z:GatewayRunner._snapshot_running_agents.<locals>.<dictcomp>   s4     
 
 
"U333 333rB   )r#  r"  s    r6   _snapshot_running_agentsz&GatewayRunner._snapshot_running_agents   s/    
 
&*&?&?&A&A
 
 
 	
rB   c                 f    	 ddl m}  |t          | dd                    S # t          $ r Y dS w xY w)z:Return the configured active chat session cap, if enabled.r   )resolve_max_concurrent_sessionsrX   N)hermes_cli.active_sessionsrb	  r-   r.   )r  rb	  s     r6   _get_max_concurrent_sessionsz*GatewayRunner._get_max_concurrent_sessions   sX    	RRRRRR227443P3PQQQ 	 	 	44	s   " 
00c                     |                                  }|dS |                     |          rdS |                                 }||k     rdS ddlm}  |||          S )zKReturn a user-facing rejection when starting a new session exceeds the cap.Nr   )active_session_limit_message)rd	  r  r  rc	  rf	  )r  r  max_sessionsr  rf	  s        r6   _active_session_limit_messagez+GatewayRunner._active_session_limit_message   s    88::4##K00 	40022,&&4KKKKKK++L,GGGrB   c                    |                      |          rdS |                     |          }|d|fS 	 ddlm} |r|j        r|j        j        nd} ||d| t          | dd          |t          |dd	          pd	t          |d
d	          pd	d          S # t          $ r&}t          	                    d|           Y d}~dS d}~ww xY w)zAClaim a cross-process active-session slot for a new gateway turn.r  Nr   )try_acquire_active_sessionr1   gateway:rX   r  r   r  )r_   r  r  )r%   surfacerX   r   z'Failed to claim active session slot: %s)
r  rh	  rc	  rj	  r_   r   r-   r.   r/   r   )r  r  r  local_limit_messagerj	  r_   r5   s          r6   _claim_active_session_slotz(GatewayRunner._claim_active_session_slot   s'    ##K00 	:"@@MM*,,,	MMMMMM06Y6?Yv,,PYH--&-8--tXt44 (&vy"==C&vy"==C 		 	 	 	  	 	 	NNDcJJJ:::::	s   A#B 
C"CCrunning_agentc                 H   | 	| t           u rdS t          | dd          }t          |t          t          t
          f          sdS |sdS t          | dd          }	 |)|5  t          |          cddd           S # 1 swxY w Y   t          |          S # t          $ r Y dS w xY w)aL  Return True when *running_agent* is currently driving subagents
        via the ``delegate_task`` tool.

        Background (#30170): ``AIAgent.interrupt()`` cascades through the
        parent's ``_active_children`` list and calls ``interrupt()`` on
        every child synchronously, which aborts in-flight subagent work
        and produces a fallback cascade with no actionable signal.
        Demoting ``busy_input_mode='interrupt'`` to ``queue`` semantics
        whenever this helper returns True protects subagent work from
        conversational follow-ups while leaving the explicit ``/stop``
        path (which goes through ``_interrupt_and_clear_session``)
        untouched. Safe-by-default: returns False on any attribute or
        lock error so a missing/broken parent never blocks the existing
        interrupt path.
        NF_active_children_active_children_lock)ri  r-   rR   r  ra  rt   r   r.   )ro	  childrenlocks      r6   _agent_has_active_subagentsz)GatewayRunner._agent_has_active_subagents   s   "  M5L$L$L5=*<dCC (T5#$677 	5 	5}&=tDD	 * *>>* * * * * * * * * * * * * * * *>>! 	 	 	55	s6   B A9,B 9A==B  A=B 
B! B!c                 L  K   t          | dd          }|r|dS 	 t          j        | j        ||           d{V }nA# t          t
          f$ r Y dS t          $ r! t                              d|d           Y dS w xY w|sdS t          | dd          }|dS t          |d|          }	 t          j        |j	        t          |                     d{V }t          |          S # t          t
          f$ r Y dS t          $ r! t                              d	|d           Y dS w xY w)
u  Return True when a compression lock is held for this session's id.

        Context compression is interrupt-protected (#23975) but gateway
        ``interrupt`` busy-input mode can still start a follow-up turn against
        the pre-rotation parent while compression is mid-flight, producing
        orphaned compression siblings (#56391). Callers demote interrupt to
        queue when this returns True.

        Both blocking sources — the ``session_store`` lock + JSON load, and the
        SQLite ``get_compression_lock_holder`` SELECT — are offloaded to a
        worker thread so a large state.db never freezes the event loop (#5).
        rf  NFzCompression in-flight check failed while reading session %s; treating compression as active to avoid interrupting a possible parent-session rotationTr   r)   r*   zCompression in-flight check failed while reading lock holder for session %s; treating compression as active to avoid interrupting a possible parent-session rotation)r-   r  r  #_lookup_session_id_under_store_lockAttributeErrorrU  r.   r/   r   get_compression_lock_holderrU   r   )r  r  rf  r%   r3   raw_dbholders          r6   "_session_has_compression_in_flightz0GatewayRunner._session_has_compression_in_flight!  s       ot<< 	m35	&08-         JJ 	* 	 	 	55 	 	 	NN*      44	  	5T=$77
5UJ77	",2C
OO       F <<	* 	 	 	55 	 	 	NNB      44	s-   != A;&A;:A;);C% %D#9&D#"D#c                     | j         5  |                                  | j                            |          }ddd           n# 1 swxY w Y   |t	          |dd          ndS )zISync helper run in the thread pool: read session_id under the store lock.Nr%   )_lock_ensure_loaded_lockedr  rT   r-   )rf  r  r  s      r6   rw	  z1GatewayRunner._lookup_session_id_under_store_lockR!  s       	< 	<//111!*..{;;E	< 	< 	< 	< 	< 	< 	< 	< 	< 	< 	< 	< 	< 	< 	< 6;5FwulD111DPs   /AA
A    r  c                    |                      |j                  }|sd S t          |dd           }t          |t                    r|                    |          nd }|t          |dd           t          j        k    sQ|j        t          j        k    s<t          t          |dd                     st          t          |dd                     r-t          |j        |||j        t          j        k               d S |                     ||          | j        k    r#t                              d|| j                   d S |                     |||           d S )Nr  r  r  
merge_textr  uJ   Dropping busy-mode follow-up for session %s — pending queue at cap (%d).)r	  r  r-   rR   rS   rT   r;  r  r  r   r?  r  TEXTr  _BUSY_QUEUE_MAX_PENDINGr/   r   r  )r  r  r  r  r  r  s         r6   _queue_or_replace_pending_eventz-GatewayRunner._queue_or_replace_pending_eventc!  sk   **5<88 	F w(;TBB4>|T4R4R\<##K000X\Hnd33{7HHH![%666GHlD99:: 7GE<6677 7
 () -1AA	    F['::d>ZZZNN\,  
 F;w77777rB   c                 "  K   |j         pd                                }|                     |          s|S |                     |j                  }|                     |||j        |d           d{V \  }}|s|S |p|                                S )u  Return steerable text for a busy follow-up, transcribing voice first.

        Fresh and queued voice messages reach the normal inbound STT pipeline,
        but successful steer messages intentionally bypass that queue. Without
        preprocessing here, a media-only voice follow-up has an empty text
        payload and steer mode silently degrades to queue mode.

        Audio file attachments remain files; only voice-message media follows
        the automatic STT contract used by ``_prepare_inbound_message_text``.
        If transcription fails, preserve any caption and let the existing
        steer fallback handle an otherwise empty event without losing it.

        Routes through ``_transcribe_and_echo_pending_voice`` — the single
        out-of-band transcription choke point shared with the interrupt
        monitor and the pending-drain path — so the STT call is made at most
        once per platform message (cached on the event) and the transcript
        echo respects the count-based ledger.  If steering later falls back
        to queue mode, the drain path reuses the cached transcript instead of
        paying for a second STT call or re-echoing the same line.
        r   z
Busy-steerlog_contextN)r   rV   _pending_event_audio_pathsr	  r  "_transcribe_and_echo_pending_voice)r  r  r   r  enriched_textsuccessful_transcriptss         r6   _prepare_busy_steer_textz&GatewayRunner._prepare_busy_steer_text!  s      * 
 b''))..u55 	K**5<886:6]6]L$ 7^ 7
 7
 1
 1
 1
 1
 1
 1
-- & 	K%,,...rB   c           	        K   |                      |j                  sQt                              d|j        j        |j        j        |j        j        r|j        j        j        nd|           dS | j        r9| 	                    |j                  }|sdS | 
                    |          }|                     |j        |          }|                                 r/|                     ||           d|                                  d}nd|                                  d}|                    |j        j        ||j        j        t"          j        k    r|j        j        dk    r|j        j        r|n.|j        j        t"          j        k    r|j        j        rd n|j        |	           d {V  dS 	 d
dlm}  ||          rO|j        pd                                                                }h d}	h d}
d }d}||	v r| j        }n'||
v r| j        }n|dv r
| j        }d}n|dv r	| j        }d}||| j        u rdnd}d| }|r| d| }||_         ||           d {V }t                              d|||           | 	                    |j                  }|rs|rq|                    |          \  }}|rW| 
                    |          }|                    |j        j        |||                     |j        |          	           d {V  dS n-# t>          $ r  t                              d|d           Y nw xY w| 	                    |j                  }|sdS tA          |dd          rdS | !                    |          }|r|j"        j#        nd }| j$        }tA          | dd          }|j%        tL          j'        k    r|dk    r|dk    rdS |dk    o| (                    |          }|rt                              d |           d}|dk    o| )                    |           d {V }|rt                              d!|           d}d}d}|dk    r| *                    |           d {V }tA          |d"d           pg }tW          |          o2tY          | -                    |                    tY          |          k    }|oC|j%        tL          j'        k    o|j.         o|j/         p|o|d uo|t`          uotc          |d          }|rY	 tW          |2                    |                    }n5# t>          $ r(} t                              d#||            d}Y d } ~ nd } ~ ww xY w|sd}n|dk    r|j%        tL          j'        k    r|j.        s|j/        s||t`          urtA          |d$d          du rtc          |d%          rr	 tW          |3                    |j        pd                                                    }n5# t>          $ r(} t                              d&||            d}Y d } ~ nd } ~ ww xY w|s|s|                     ||           |dk    }!|dk    }"|dk    o|}#|dk    r|s|r|t`          ur	 |j        }$tA          |d"d           pg }%| -                    |          r0| 4                    |||j        |j        pdd'(           d {V \  }$}&n|$s|%rtk          |          }$|6                    |$           n# t>          $ r Y nw xY wtn          j8        9                    d)d*                                          d*k    }'|'st          :                    d+|           dS d,}(tw          j;                    })|r|j"        j<        nd
}*|)|*z
  |(k     rdS d
d-l=m>}+ t          |j        j                  },|"rtn          j8        9                    d.          }-|-)|-                                                                d/v }.n'tW           |+t                      |,d0d                    }.|.st          :                    d1|           dS |)| A                    |          j"        _<        g }/tW           |+t                      t          |j        j                  d2d                    }0|0r|r|t`          ur	 |B                                }1|19                    d3d
          }2|19                    d4d
          }3|19                    d5          }4|r|j"        jC        nd
}5|5r3t          |)|5z
  d6z            }6|6d
k    r|/E                    |6 d7           |3r|/E                    d8|2 d|3            |4r|/E                    d9|4            n# t>          $ r Y nw xY w|/rd:d;F                    |/           d<nd}7|"rd=|7 d>}n.|#rd?|7 d@}n%|!r	|rdA|7 dB}n|!r	|rdC|7 dB}n|!rdD|7 dE}ndF|7 dG}	 d
dHlGmH}8mI}9mJ}:mK}; t                      }< |:|<|8          s5|"rd}=n|!rd}=n|#rd%}=nd}=| dI |9|=           } |;t          dJz  |8           n2# t>          $ r%}>t          :                    dK|>           Y d }>~>nd }>~>ww xY w| 
                    |          }|                     |j        |          }	 |                    |j        j        ||j        j        t"          j        k    r|j        j        dk    r|j        j        r|n.|j        j        t"          j        k    r|j        j        rd n|j        |	           d {V  n2# t>          $ r%}?t          :                    dL|?           Y d }?~?nd }?~?ww xY wdS )MNz`Dropping message from unauthorized user in active session: user=%s (%s), platform=%s, session=%sr  T   ⏳ Gateway 2    — queued for the next turn after it comes back.   ⏳ Gateway is - and is not accepting another turn right now.r~  rI  r   has_blocking_approvalr   >      👍yokrO   okayapproveconfirm>      👎nnodenyr  reject>   approve alwaysalwaysalways approver	  >   approve sessionsession approvesessionr	  r	  r	  r;  rn  z<Approval response via plain text: session=%s verb=%s args=%rzSPlain-text approval routing failed for session %s; falling through to busy handlingr   Finternalr  r  rd  r  zvDemoting busy_input_mode 'interrupt' to 'queue' for session %s because the running agent has active subagents (#30170)zpDemoting busy_input_mode 'interrupt' to 'queue' for session %s because context compression is in flight (#56391)r  z'Gateway steer failed for session %s: %s_supports_active_turn_redirectredirectz*Gateway redirect failed for session %s: %szVoice-busy-interruptr	  r  rP   z"Busy ack suppressed for session %sr  r0  r  >   rM   rN   rO   rP   r  z(Busy steer ack suppressed for session %sbusy_ack_detailapi_call_countr  current_toolr  z min elapsed
iteration z	running:  (r   rT  u   ⏩ Steered into current runz0. Your message arrives after the next tool call.u   ↪ Redirected current runz$. I'll adjust using your correction.u   ⏳ Subagent workinguR    — your message is queued for when it finishes (use /stop to cancel everything).u   ⏳ Compressing contextu   ⏳ Queued for the next turnz.. I'll respond once the current task finishes.u   ⚡ Interrupting current taskz'. I'll respond to your message shortly.)BUSY_INPUT_FLAGbusy_input_hint_gatewayr  r  r   rZ  z.Failed to apply busy-input onboarding hint: %szFailed to send busy-ack: %s)M_is_user_authorizedr  r/   r   r  r  r_   r   r  r	  r=  _thread_metadata_for_sourcer  r	  r  _send_with_retryr  r  r  r}  rd  r4  r  r	  r   rV   rW   _handle_approve_command_handle_deny_commandr  _unwrap_ephemeralr.   r-   r  r  r   r  r  r;  r	  ru	  r|	  r	  r   r   r	  r  r  ri  r   r  r	  r	  r  r  rq   rr   rT   r0   r,   busy_ack_tsr2  r1  r=  rQ   r  r	  
started_tsrF  rs   rD   r  r	  r	  r  r  r;  )@r  r  r  r  reply_anchorthread_metar  r	  	_raw_text_approve_words_deny_words_approval_handler_normalized_argsr$  _synth_replyr~  _text_eph_ttl_anchor_busy_statero	  effective_moder  demoted_for_subagentsdemoted_for_compressionsteered
redirected
steer_text_steer_media_urls_steer_all_voice	can_steerr5   is_queue_modeis_steer_modeis_redirect_mode_interrupt_text_media_urlsr  r  _BUSY_ACK_COOLDOWNra  last_ackr1  r  steer_ack_envsteer_ack_enabledstatus_partsbusy_ack_detail_enabledsummaryr  max_iterr	  start_tselapsed_minstatus_detailr	  r	  r  r  	_user_cfg
_hint_mode_onb_errrs  s@                                                                   r6   #_handle_active_session_busy_messagez1GatewayRunner._handle_active_session_busy_message!  s      ''55 		NN8$&/4|/DS%++)   4 > 	..u|<<G t77>>L::5<VVK//11 x44[%HHHy)C)C)E)EyyywD,F,F,H,Hwww**, |,0AAA.$66. 7 !L #(,"78;L"L"LQVQ]Qg"L$$mrm}$ +          4.4	<<<<<<$$[11 , "Z-24466<<>>	!Y!Y!YMMM$(!#% ..(,(D%%+--(,(A%%"PPP(,(D%'/$$"SSS(,(D%'0$$0 *;d>Z)Z)ZII`fE([[F' @$*!?!?-=!?!?!'EJ#4#4U#;#;;;;;;;FKKV#U,<    $77EEH 	F 	*2*D*DV*L*Lx  &*&B&B5&I&IG"*";";(-(<(-)0)-)I)I%,X_)`)`	 #< # #         4 	 	 	NN3d      	 **5<88 	5 5*e,, 	5..{;;2=G(..4. '8+FF+"222'))'))5 k) @00?? 	 ! 	%KKJ  
 %Nk) K==kJJJJJJJJ 	  # 	%KKD  
 %N
W$$#<<UCCCCCCCCJ
 !(|T B B Hb#$566  D33E::;;sCT?U?UU   4 *k.>> 2 % 002 % 11(
 (4 "-4 ")@@4 M733   $$"=#6#6z#B#BCCGG  $ $ $NN#Lk[^___#GGGGGG$  )!(k))"k&666$ 7% 7 )%<<<'GOOSWWWz22 X#!-"8"8%*:J9Q9Q9S9S"T"TUU

 # # #K[Z]^^^"





#&  	Ez 	E00eDDD&'1&'1)[8GZ k)) * * %<<<"'*%e\4@@FB22599 	F/3/V/V
(b$: 0W 0 0 * * * * * *&OQQ ) F[ F&>u&E&EO''8888    :>>*KVTTZZ\\`ff 	LL={KKK4
  ikk3>E;#//A>...4BBBBBB+EL,ABB  	JNN+RSSM($1$7$7$9$9$?$?$A$AE_$_!!$(++,..$0	 % %! % GUUUt<?K((-9
 "&##$&&$U\%:;;!	 #
 #
 # 	} 	Ne9e9e'<<>>#KK(8!<<	";;'7;;&{{>:::EL;+661 J"%sX~&;"<"<K"Q$++{,H,H,HIII M ''(KY(K(K(K(KLLL D ''(BL(B(BCCC    <HO7TYY|447777R  	B} B B B G  	6] 6 6 6 G  	4 	
F} F F F G  	6 	F- F F F G  		@} @ @ @ G9 9 9 9 	U            -..I79o66 I  -!(JJ" -!(JJ% -!+JJ!,J = =..z::= =  	,6HHH 	U 	U 	ULLI8TTTTTTTT	U 33E::66u|\RR	;**, |,0AAA.$66. 7 !L #(,"78;L"L"LQVQ]Qg"L$$mrm}$ +            	; 	; 	;LL6::::::::	; ts   0EL 'L<;L<"T1 1
U#;UU#;W? ?
X1	X,,X16B[> >
\
\1Cf 
ff(Ai 
i3i..i3'Bl6 6
m% m  m%c                 `   	K                                     }                                                                                                   d	d
dt          dd f	 fd} j        sdk    rdk    r |d           |dfS  |d           |dk    r|dfS t          j                                                    |z   }t           j                  s(                                 s                                 rt          j                                                    |k     r |             t          j
        d	           d {V  t           j                  s(                                 s                                 r)t          j                                                    |k     t	          t           j                            pAt	                                                     p t	                                                     } |d           ||fS )Nr  Fr   r'   c                 B   t          j                                                    }	                                }	                                }	                                }| s|k    s|k    s|k    s	|z
  dk    r	                    d           ||||d S d S )Nr	  r  )r  get_running_loopr,   r  r  r  r  )
r   ra  r  
cron_count	api_countlast_active_countlast_api_countlast_cron_countlast_status_atr  s
        r6   _maybe_update_statusz@GatewayRunner._drain_active_agents.<locals>._maybe_update_statusp#  s    *,,1133C4466L4466J2244I%#44400...(S00++J777$0!",!*!$ 10rB   r   Tr   皙?rU  )r`	  r  r  r  r   r  r  r	  r,   r   r`  )
r  r  snapshotr	  deadline	timed_outr	  r	  r	  r	  s
   `     @@@@r6   _drain_active_agentsz"GatewayRunner._drain_active_agentsi#  s     0022 557755773355	% 	% 	% 	% 	% 	% 	% 	% 	% 	% 	% 	% 	%2 # 	#1(<(<STATAT  t,,,,U?"4((((a<<T>!+--2244w> D())		% ..00		% --//			% (**//11H<<  """-$$$$$$$$$ D())		% ..00		% --//			% (**//11H<<
 T)**++ 2D//11222D..0011 	
 	4((((""rB   c                 .   t          | j                                                  D ]m\  }}|t          u r	 t	          ||           t
                              d|           <# t          $ r%}t
                              d|           Y d }~fd }~ww xY wd S )Nz8Interrupted running agent for session %s during shutdownz-Failed interrupting agent during shutdown: %s)r  r  r  ri  r   r/   r0   r.   )r  rj  r  r   rs  s        r6   _interrupt_running_agentsz'GatewayRunner._interrupt_running_agents#  s    "&t';'A'A'C'C"D"D 	Q 	QK///Q&uf555WYdeeee Q Q QLaPPPPPPPPQ	Q 	Qs   +A##
B-BBc                 :  K   |                                  }| j        r| j        nd}| j        rdnd}| j        rdnd}d| d| }t                      }|D ]}d}	 t	          | dd          S| j                                         d{V  | j        j        	                    |          }	|	rt	          |	d	d          nd}n3# t          $ r&}
t                              d
||
           Y d}
~
nd}
~
ww xY w||                     |          }|(|j        j        }t!          |j                  }|j        }n7t'          |          }|s|d         }|d         }|	                    d          }|||rt!          |          ndf}||v r2	 t)          |          }| j        	                    |          }|s`| j        j        	                    |          }|$|j        st                              d|           |t	          |dd          nd}|k|i	 |j        j        }t!          |j                  }|j        rt!          |j                  nd}|||f|k    rt	          |dd          }n# t          $ r Y nw xY w|                     ||||t	          |dd          nd||          }|                    |||           d{V }|At	          |dd          du r.t                              d||t	          |dd                     |                    |           t                              d||           # t          $ r(}
t                              d|||
           Y d}
~
d}
~
ww xY w| j        r|t                              d           dS 	 ddlm}  |            rt                              d           dS n2# t          $ r%}
t                              d|
           Y d}
~
nd}
~
ww xY wt?          | j                                                   D ]\  }}| j        !                    |          }|r|j        s*| j        j        	                    |          }|(|j        s!t                              d|j                   s|j        t!          |j                  |j        rt!          |j                  ndf}||v r	 |                     ||j        |j        |           }|r1|                    t!          |j                  ||           d{V }n.|                    t!          |j                  |           d{V }|Kt	          |dd          du r8t                              d!|j        |j        t	          |dd                     |                    |           t                              d"|j        |j                   # t          $ r2}
t                              d!|j        |j        |
           Y d}
~
d}
~
ww xY wdS )#u4  Send shutdown/restart notifications to active chats and home channels.

        Called at the very start of stop() — adapters are still connected so
        messages can be delivered. Best-effort: individual send failures are
        logged and swallowed so they never block the shutdown sequence.
        Nr  r  zpYour current task will be interrupted. Send any message after restart and I'll try to resume where you left off.z&Your current task will be interrupted.u   ⚠️ Gateway     — rf  originz>Failed to load session origin for shutdown notification %s: %sr_   r  rd  z^Shutdown notification suppressed for active session: %s has gateway_restart_notification=falser4  r}  r}  reply_to_message_idr  r  r  TFz1Failed to send shutdown notification to %s:%s: %sr  send returned success=Falsez/Sent shutdown notification to active chat %s:%sz@Skipping home-channel shutdown notifications for in-chat restartr   )drain_notification_suppressedzWHome-channel shutdown broadcast suppressed by drain marker (suppress_notification=true)z.drain_notification_suppressed check failed: %sz\Shutdown notification suppressed for home channel: %s has gateway_restart_notification=falser  z>Failed to send shutdown notification to home channel %s:%s: %sz0Sent shutdown notification to home channel %s:%s)"r`	  r  r  rt   r-   async_session_store_ensure_loadedrf  r  rT   r.   r/   r0   _get_cached_session_sourcer_   r   rU   r  rd  r  r  r{  rX   r#  gateway_restart_notificationr  _thread_metadata_for_targetr  rv   r
	  r	  r  r  get_home_channel)r  r  restart_sourceactionhintr|  notifiedr  r  r  rs  platform_strr  rd  _parsed	dedup_keyr_   r  r%  r	  restart_platformrestart_chat_idrestart_thread_idr   r  r	  rX  s                              r6   #_notify_active_sessions_of_shutdownz1GatewayRunner._notify_active_sessions_of_shutdown#  s      ..009=9PZ55VZ!%!8Mo &: X X :	 	 433T338;! [	 [	KF
4$77C2AACCCCCCCCC .7;;KHHE?DNWUHd;;;$F   T        ~88EE!%4fn--",		 -[99 &z2!),#KK44	
 &w)0UIQUVIH$$5#L11-++H55 #{488BB+L4]+KKx$   MSM_gflD&I&I&Iei#&.>3M+9+B+H(*-n.D*E*EM[Me,oC0H,I,I,Iko),o?PQU^^^29.,X\2]2]/$     ;;DJDVgfk4@@@\`(;# <    '||GS8|LLLLLLLL%'&)T*J*Je*S*SLLK$1NOO	   Y'''E '       G '1        " 	~'ALL[\\\F	NKKKKKK,,.. 3     	N 	N 	N LLI1MMMMMMMM	N "&dm&9&9&;&;!<!< 1	 1	Hg;//99D t| ;044X>>L'0Y'rN   !T\):):SWSa<kC<O<O<OgklIH$$ ;;LN#	 <    H#*<<DL0A0A3QY<#Z#ZZZZZZZFF#*<<DL0A0A3#G#GGGGGGGF%'&)T*J*Je*S*SLLX 1NOO	   Y'''FNL   
    TNL	       W1	 1	s   A$C  
C0
C++C0+L>5AL>:L>AI,+L>,
I96L>8I99BL>1L>>
M0M++M0*O 
O5O00O5CW;W
X&'XXr  c           	      .  K   |                                 D ]|}	 t          |dd           }t          |dd           }t          |          rt          |t                    r|rt          |dd           }t          |          r	  ||           n# t
          $ r Y nw xY w	  ||           na# t
          $ rT}t                              d|t          |                     ddl	m
}  |t          |dd           |           Y d }~nd }~ww xY wn2# t
          $ r%}t                              d|           Y d }~nd }~ww xY w	 dd	lm}	  |	t          |dd           d
d           n# t
          $ r Y nw xY w|                     |d           d {V  ~d S )N_flush_messages_to_session_dbr  )_drop_trailing_empty_response_scaffoldingz^Shutdown transcript flush failed (%s); preserving %d in-memory message(s) to recovery snapshotr   )flush_agent_history_to_filer%   z$Shutdown transcript flush failed: %sfinalize_sessionr1   r  r%   r_   rj  zshutdown finalizer   )r_  r-   r  rR   r  r.   r/   r   r   gateway.shutdown_flushr
  r0   hermes_cli.lifecycler
  !_cleanup_agent_resources_off_loop)
r  r  r   r  r  _strip
_flush_errr
  r  r
  s
             r6   _finalize_shutdown_agentsz'GatewayRunner._finalize_shutdown_agentsu$  s     "))++ E	 E	E 'I (GNN$+E3F$M$M!F## "
3Dd(K(K "Pa "
 %JD F  '' !!"F#45555( ! ! ! D!01111$    K& 122	   WVVVVV33#E<>>-       !(  I I ICRHHHHHHHHIAAAAAA  &ulDAA&%    
     882 9          GE	 E	sy   A(DBD
BDBD!B-,D-
D7A
DDDD
D>D99D>#E&&
E32E3executor_taskc                     |dS ||                                 rdS |r)|                     |          }|r|j        j        nd|urdS dS )a  Only emit the heartbeat while this task still owns the live run.

        Guards against a stale ``running: delegate_task`` heartbeat outliving the
        run that started it: stop once the executor finishes, the agent is gone,
        or the session key has been rebound to a different live agent (e.g. the
        user sent ``/new`` and a fresh agent took the slot mid-run, #12029).
        NFT)r  r  r  r   )r  r  r   r
  	_hb_states        r6   &_should_emit_long_running_notificationz4GatewayRunner._should_emit_long_running_notification$  si     =5$););)=)=$5 	00==I(1;	$$tEIIutrB   r   r   c                    d fd}t          j         |                      }t           dd          }|t                      }| _        |                    |           |                    |j                   dS )a}  Clean up ``agent`` only after its executor future has finished.

        A timed-out executor call keeps running in its worker thread. Closing
        the agent before that thread exits can tear down clients or providers
        it is still using. Keep a strong task reference and wait for the real
        future before invoking the normal bounded, off-loop cleanup path.
        r'   Nc                    K   	 t          j                   d {V  nL# t           j        $ r Y d S t          $ r.} t                              drd dnd|            Y d } ~ nd } ~ ww xY w                               d {V  d S )Nz2Deferred agent worker%s finished with an error: %sr	  rT  r   r
  )r  rk  rf  r.   r/   r0   r
  )r5   r   r   r   r  s    r6   _cleanup_when_donezPGatewayRunner._defer_agent_cleanup_until_future_done.<locals>._cleanup_when_done$  s      nV,,,,,,,,,,)       H'.6OOOOOB        888PPPPPPPPPPPs     A)	A)$A$$A)_deferred_agent_cleanup_tasksrX  )r  ri  r-   rt   r!
  rv   r  r  )r  r   r   r   r 
  r   rl  s   ````   r6   &_defer_agent_cleanup_until_future_donez4GatewayRunner._defer_agent_cleanup_until_future_done$  s    	Q 	Q 	Q 	Q 	Q 	Q 	Q 	Q 	Q "#5#5#7#788=tDD=EEE16D.		$u}-----rB   r
  c                  K   |dS |                     d          s|dk    r	 d|_        n# t          $ r Y nw xY w	 t          j        |                     | j        |          | j                   d{V  dS # t          j        $ r- t          
                    d|rd| dnd	| j                   Y dS t          $ r/}t          
                    d
|rd| dnd	|           Y d}~dS d}~ww xY w)u  Run _cleanup_agent_resources in a worker thread with a bounded wait.

        Safe to await from coroutines on the gateway event loop: a slow or
        wedged teardown (memory provider IO, subprocess close) can no longer
        block message processing. On timeout the await is cancelled and the
        worker thread is left to finish (or leak) on its own — the caller
        proceeds regardless, exactly as the /new reset path does (#35994).
        Nr  session expiryFr  zAgent resource cleanup%s exceeded %ss; proceeding without blocking the event loop (the worker thread is left to finish on its own). (#53175)r	  rT  r   z,Agent resource cleanup%s failed: %s (#53175))r   _end_session_on_closer.   r  r  _run_in_executor_with_context_cleanup_agent_resources_CLEANUP_TIMEOUT_Sr  r/   r   )r  r   r   cleanup_excs       r6   r
  z/GatewayRunner._cleanup_agent_resources_off_loop%  s      =Fj)) 	W8H-H-H.3++   	"2215  /	            # 	 	 	NN( $+2W'       	 	 	NN>#*2W        	s)   + 
88:A8 88C+3	C+<$C&&C+c                 8   |dS 	 t          |d          rt          |dd          }|8t          |d          r(	 |                    d           n# t          $ r Y nw xY wt          |dd          }t	          |t
                    r|                    |           n|                                 n# t          $ r Y nw xY w	 t          |d          r|                                 n# t          $ r Y nw xY w	 d	d
lm	}  |             dS # t          $ r Y dS w xY w)z<Best-effort cleanup for temporary or cached agent instances.Nshutdown_memory_provider_memory_managerflush_pendingr  r  r  closer   )cleanup_stale_async_clients)
r   r-   r-
  r.   rR   r  r+
  r.
  agent.auxiliary_clientr/
  )r  r   _mmsession_messagesr/
  s        r6   r'
  z&GatewayRunner._cleanup_agent_resources-%  s   =F$	u899 !5 e%6==?wsO'D'D?))")5555$    $+52Et#L#L .55 5223CDDDD22444 	 	 	D	
	ug&&  	 	 	D		JJJJJJ''))))) 	 	 	DD	sY   3B2 A B2 
AB2 AAB2 2
B?>B?$C( (
C54C59D 
DDr  z.restart_failure_countsactive_session_keysc                 V   ddl }t          | j        z  }	 |                                r$ |j        |                    d                    ni }n# t          $ r i }Y nw xY wi }|D ]}|                    |d          dz   ||<   	 t          ||d           dS # t          $ r Y dS w xY w)a  Increment restart-failure counters for sessions active at shutdown.

        Persists to a JSON file so counters survive across restarts.
        Sessions NOT in active_session_keys are removed (they completed
        successfully, so the loop is broken).
        r   Nr  rJ  rk   r  )	r  r;  _STUCK_LOOP_FILErw   r  r   r.   rT   rI  )r  r3
  r  rx   counts
new_countsr  s          r6   !_increment_restart_failure_countsz/GatewayRunner._increment_restart_failure_countsk%  s     	d33	EI[[]]ZZTZ @ @AAAXZFF 	 	 	FFF	 
& 	5 	5C$jja0014JsOO	dJt<<<<<< 	 	 	DD	s#   :A AAB 
B('B(c                     ddl }t           j        z  }|                                sdS 	  |j        |                    d                    }n# t          $ r Y dS w xY wd} fd|                                D             }|D ]i}	  j        j	        
                    |          }|r5|j        s.d|_        |dz  }t                              d|||                    Z# t          $ r Y fw xY w|r+	  j                                         n# t          $ r Y nw xY w	 |                    d	           n# t          $ r Y nw xY w|S )
u,  Suspend sessions that have been active across too many restarts.

        Returns the number of sessions suspended.  Called on gateway startup
        AFTER suspend_recently_active() to catch the stuck-loop pattern:
        session loads → agent gets stuck → gateway restarts → repeat.
        r   Nr  rJ  c                 0    g | ]\  }}|j         k    |S r,  )_STUCK_LOOP_THRESHOLD)r?   r  r  r  s      r6   r  z>GatewayRunner._suspend_stuck_loop_sessions.<locals>.<listcomp>%  s*    VVVDAqa4;U6U6Ua6U6U6UrB   Trk   u_   Auto-suspended stuck session %s (active across %d consecutive restarts — likely a stuck loop)rB  )r  r;  r5
  rw   r  r   r.   r  rf  r  rT   	suspendedr/   r   r  rD  )r  r  rx   r6
  r<
  
stuck_keysr  r  s   `       r6   _suspend_stuck_loop_sessionsz*GatewayRunner._suspend_stuck_loop_sessions%  s    	d33{{}} 	1	TZ @ @AAFF 	 	 	11	 	VVVVFLLNNVVV
% 	 	K*377DD  &*EONINNH#VK%8  
      	"((****   	KK4K(((( 	 	 	D	 sH   $A 
AA	AC  
C-,C-3D 
DDD5 5
EEc                 .   ddl }t          | j        z  }|                                sdS 	  |j        |                    d                    }||v r1||= |rt          ||d           dS |                    d           dS dS # t          $ r Y dS w xY w)zClear the restart-failure counter for a session that completed OK.

        Called after a successful agent turn to signal the loop is broken.
        r   Nr  rJ  r  TrB  )	r  r;  r5
  rw   r  r   rI  rD  r.   )r  r  r  rx   r6
  s        r6   _clear_restart_failure_countz*GatewayRunner._clear_restart_failure_count%  s    
 	d33{{}} 	F		TZ @ @AAFf$$;' 1%dF4@@@@@@KK4K00000 %$  	 	 	DD	s   ?B ,B 
BBc           	        K   dd l }dd l}t                      }|st                              d           d S | j        rd S d| _        t          j                    }t          t          t          | dd          pd          dz   d          }t          j        dk    rydd l}ddlm}m} g |d	d
}	|                    d                                          }
ddlm}  |dd          }|                    dd            t-          t.                                                    j        j        }t          j        }t-          |                    d          p|dz            }|dz  dz  }|                                rt;          |          |d<   t;          |          t;          |          g}|                    d          r|                    |d                    t          j                             tB          "                    |                    |d<   |d|
t;          |          t;          |          g|	}	  |j#        |f|j$        |j$        |d |             n# tJ          $ r 	 |#                    ||j$        |j$        | |                       ns# tJ          $ rf}t          |dd           }||n|j&        }|dnd}t          '                    dt          j(        )                    |          ||           Y d }~nd }~ww xY wY nw xY wd S d                     d |D                       }dtU          |           d| d| d }ddlm}  |dd          }|                    dd            |+                    d!          }|r*|#                    |d"d#|g|j$        |j$        |d$           d S |#                    d"d#|g|j$        |j$        |d$           d S )%Nr   z4Could not locate hermes binary for detached /restartTr  r  r#   rf   )&windows_detach_flags_without_breakawaywindows_detach_popen_kwargsr1   r  u  
                import os, subprocess, sys, time
                from hermes_cli._subprocess_compat import windows_detach_flags_without_breakaway
                pid = int(sys.argv[1])
                restart_after_s = float(sys.argv[2])
                cmd = sys.argv[3:]
                deadline = time.monotonic() + restart_after_s

                def _alive(p):
                    # On Windows, os.kill(pid, 0) is NOT a no-op — it maps to
                    # GenerateConsoleCtrlEvent(0, pid) (bpo-14484). Use the
                    # Win32 handle-based existence check instead.
                    if os.name == 'nt':
                        import ctypes
                        k32 = ctypes.windll.kernel32
                        k32.OpenProcess.restype = ctypes.c_void_p
                        k32.WaitForSingleObject.restype = ctypes.c_uint
                        k32.GetLastError.restype = ctypes.c_uint
                        h = k32.OpenProcess(0x1000 | 0x100000, False, int(p))
                        if not h:
                            return k32.GetLastError() != 87
                        try:
                            return k32.WaitForSingleObject(h, 0) == 0x102
                        finally:
                            k32.CloseHandle(h)
                    try:
                        os.kill(int(p), 0)
                        return True
                    except ProcessLookupError:
                        return False
                    except PermissionError:
                        return True
                    except OSError:
                        return False

                while time.monotonic() < deadline:
                    if not _alive(pid):
                        break
                    time.sleep(0.2)
                subprocess.Popen(
                    cmd,
                    stdout=subprocess.DEVNULL,
                    stderr=subprocess.DEVNULL,
                    creationflags=windows_detach_flags_without_breakaway(),
                )
                build_subprocess_envF)scrub_secretsinherit_profile_homerF  rg   rh   ri   rj   rl   -cr  r  env)r  r  rJ
  creationflagswinerrorerrnozDetached restart watcher was not started after the no-breakaway retry (%s; %s=%r). The gateway will not be respawned by this restart attempt.rn  c              3   >   K   | ]}t          j        |          V  d S r;   )r'	  quoter>   s     r6   rA   zAGatewayRunner._launch_detached_restart_command.<locals>.<genexpr>g&  s,      @@Tu{4((@@@@@@rB   zdeadline=$(( $(date +%s) + z )); while kill -0 zC 2>/dev/null && [ $(date +%s) -lt $deadline ]; do sleep 0.2; done; z gateway restartsetsidbash-lc)r  r  rJ
  start_new_session),rq  r  ry  r/   r  r  rq   getpidr  rG  r-   rm   r_   textwraphermes_cli._subprocess_compatrB
  rC
  dedentrV   tools.environments.localrE
  r$  r   rn   ro   rp   rv  rT   rw   rU   rs   r}   rD   rS   r~   PopenDEVNULLru   rM
  r   rx   basenamerF  rr  )r  rq  r  
hermes_cmdcurrent_pidrestart_after_srU
  rB
  rC
  cmd_argvwatcherrE
  watcher_envr   watcher_pythonr   r   r   watcher_argvr5   rL
  rz  error_fieldr   	shell_cmd
setsid_bins                             r6    _launch_detached_restart_commandz.GatewayRunner._launch_detached_restart_command%  s     (**
 	LLOPPPF0 	F04-ikkeGD2JC$P$P$WTWXX[^^`cdd <7""OOO       
 ;:Y:	:Hoo-/ /^ egg_ ` FEEEEE..UY]^^^K OO-t444>>1133:AL !^NKOOM::SlV>STTH$u,>M##%% W-0]]M*!,//]1C1CD
??<00 A%%k,&?@@@,.JOODMM*<U<U,V,VL)K  O$$ L$$ 
  %-%-#	 
 2133       $$$)1)1'&L&L&N&N %          'sJ==H-5-AsyJ080D**'KNN@ ((88#"       : Fhh@@Z@@@@@%#o*>*> % %(% %% % % 	 	BAAAAA**UYZZZ)4000\\(++
 	VUI6!)!)"&       	*!)!)"&      s=   =$I" "
L-,JL
L
$AL LL

LLc           
      |   t           j        dk    st          j                            d          sdS 	 ddl}ddl|                    d          }|                    d          |rsdS 	 ddlm	}  |            n# t          $ r dY nw xY wt          j                    }fd	} |g           } |d
g          }t          |          |k    rg }d}	nt          |          |k    rd
g}d}	ndS t          j                  }
d| d|	 d|
 d|	 d|
 
} d|                     dd          }                    |g|dd|dd|j        j        d           t$                              d||rdnd           dS # t          $ r&}t$                              d|           Y d}~dS d}~ww xY w)a  Best-effort helper to bypass systemd's automatic restart delay.

        For planned in-chat restarts, the gateway exits cleanly so systemd does
        not record a failure.  However, units with RestartSteps still count
        automatic restarts and can delay repeated /restart tests.  A transient
        user service survives our cgroup teardown and explicitly starts the
        gateway as soon as this PID exits, while the unit keeps its normal
        backoff for real crash loops.
        linuxINVOCATION_IDNr   zsystemd-run	systemctl)get_service_namehermes-gatewayc                     	                      g| dddddddd          }|j        pd	                                S # t          $ r Y d	S w xY w)
Nshowz--property=MainPIDz--valueTr  rJ  r  )capture_outputr   r  r  r  r   )runr  rV   r.   )scope_flagsoutservice_namer  rk
  s     r6   
_query_pidzBGatewayRunner._launch_systemd_restart_shortcut.<locals>._query_pid&  s    $.." :[ :& :, :-:/8:'+$QZde )  C
  J,"33555    22s   A A 
AAz--userzsystemctl --userzwhile kill -0 z" 2>/dev/null; do sleep 0.2; done; z reset-failed ; z	 restart z-planned-restart-r   r  z	--collectz--unitz/bin/shrR
  T)r  r  rS
  zALaunched systemd planned-restart helper for %s (pid=%s, scope=%s)r  r  z3Failed to launch systemd planned-restart helper: %s)rm   r_   rq   rr   rT   rq  r  rr  hermes_cli.gatewayrl
  r.   rT
  rU   r'	  rO
  rJ  rY
  rZ
  r/   r  r0   )r  rq  systemd_runrl
  r]
  ru
  
system_piduser_pidrr
  systemctl_scopeservice_argre
  	unit_namers  rt
  r  rk
  s                 @@@r6    _launch_systemd_restart_shortcutz.GatewayRunner._launch_systemd_restart_shortcut&  s    <7"""*..*I*I"FP	SMMM ,,}55K[11I i 0??????//11 0 0 0/0 )++K	 	 	 	 	 	 	 $BJ!z8*--H;:-- "-[!!X--'j"4
 +l33K; ; ;"; ;2=; ;"; ;-8; ; 
 (GG+GGOOPSUXYYI	 	  	 		
 	 	 	 	 ")!)"&     KKS%38	      	S 	S 	SLLNPQRRRRRRRRR	SsC   6F /B  ?F  BF BA%F 6BF 
F;F66F;c                   K   |                                  }|dk    rdS t          t          | dd          pd          }|dk    rt                              d|           dS t                              d||           	 |                     d           n# t          $ r Y nw xY wt          j                    }|	                                |z   }d}|                                  dk    r|	                                }||k    r0t          
                    d	||                                             dS ||z
  d
k    rZt                              d|                                  ||z
             	 |                     d           n# t          $ r Y nw xY w|}t          j        d           d{V  |                                  dk    t                              d           dS )a  Wait for in-flight work to finish before entering ``stop()``.

        In-band restart used to call ``stop()`` immediately, which folded the
        requesting turn into the drain wait set and force-interrupted it at
        ``restart_drain_timeout`` (#77184). Instead we refuse new turns and
        wait here for active agents/cron/api work to reach zero, then let
        ``stop()`` run against an idle gateway (drain is instant).

        Returns True when work drained to zero, False when the safety cap
        elapsed with work still active (caller proceeds to ``stop()``, which
        may then interrupt remaining runs under ``restart_drain_timeout``).
        r   Tr  r  uq   Restart requested with %d active work unit(s); restart_after_turn_timeout=0 — entering stop()/drain immediatelyFzRestart requested with %d active work unit(s); deferring stop() until they finish (cap=%.0fs) so in-flight turns are not amputated (#77184)r  zRestart after-turn wait timed out after %.0fs with %d still active; proceeding to stop()/drain which may interrupt remaining work (#77184)r"   zXRestart deferred: waiting on %d active work unit(s) (%.0fs remaining before force drain)r	  NuL   Restart deferred wait complete — active work drained; proceeding to stop())r  rG  r-   r/   r  r  r.   r  r	  r,   r   r`  )r  r  r  r   r	  r	  ra  s          r6   !_await_active_work_before_restartz/GatewayRunner._await_active_work_before_restart&  s?      ((**Q;;4&CSIIPSQQa<<KKU  
 5/ 	
 	
 	
	''
3333 	 	 	D	 '))99;;(%%''!++))++Ch8 ++--   un$--;++--sN	  //
;;;;    D!$-$$$$$$$$$/ %%''!++2 	#	
 	
 	
 ts$   ?B 
B"!B".F 
FFdetachedvia_servicer
  r
  c                      j         rdS d _         _         _        d _         d _        d fd}t          j         |                       _        dS )NFTr'   c                  P  K                                     d {V  rN	                                  d {V  n2# t          $ r%} t                              d|            Y d } ~ nd } ~ ww xY wt          j        d           d {V                      d           d {V  d S )Nz4Failed to launch detached gateway restart helper: %s皙?Tr  detached_restartservice_restart)r
  rg
  r.   r/   r  r  r`  rq  )rs  r
  r  r
  s    r6   _run_restartz3GatewayRunner.request_restart.<locals>._run_restart:'  s      88:::::::::
  \\??AAAAAAAAAA  \ \ \LL!WYZ[[[[[[[[\-%%%%%%%%%))D8U`)aaaaaaaaaaas   < 
A+A&&A+rX  )r  r  r  r   r  r  ri  r  )r  r
  r
  r
  s   ``` r6   request_restartzGatewayRunner.request_restart.'  s    % 	5"&!)$/!%)" 	b 	b 	b 	b 	b 	b 	b 	b4 %0@@trB   >   rl  rm  restart_interruptedc                   K   	 |                     |           d{V  t          |di           }t          |t                    r|                    |          nd}|t          j        |           d{V  |                     |          }|r|j        j	        ndt          u r|                     |           dS dS # |                     |          }|r|j        j	        ndt          u r|                     |           w w xY w)a  Dispatch one synthetic startup resume and wait for its agent turn.

        ``BasePlatformAdapter.handle_message()`` returns after it installs the
        adapter-level guard and spawns the background processing task.  Startup
        restore needs a stronger boundary: inbound messages must stay queued
        until the resumed agent turn itself has finished, otherwise a user
        message can race the restore turn immediately after ``handle_message``
        returns.
        N_session_tasks)handle_messager-   rR   rS   rT   r  rk  r  r  r   ri  _release_running_agent_state)r  r  r  r  session_tasksr   
_pre_states          r6   _run_startup_resume_eventz'GatewayRunner._run_startup_resume_event`'  s7     	?((/////////#G-=rBBM5?t5T5T^=$$[111Z^DnT********* 11+>>J)3=
%%BYYY11+>>>>> ZY 11+>>J)3=
%%BYYY11+>>>> Zs   A4B= =ADc                    t          | dd           }|	g }|| _         |j        |           	 |j        }t                              d|r|j        r|j        j        nd|r|j        nd           d S # t          $ r Y d S w xY w)Nrs  zJQueued inbound message during gateway startup restore: platform=%s chat=%sr  )
r-   rs  rs   r  r/   r  r_   r   r  r.   )r  r  rd  r  s       r6   _queue_startup_restore_eventz*GatewayRunner._queue_startup_restore_event~'  s    6===E*/D'U	\FKK\)/RFOR%%"(7i    
  	 	 	DD	s   AA1 1
A?>A?c           
        K   d}t          | dd          }|dS |r |j        d          }t          |dd          }|                     |          }|:t                              dt          t          |dd          dd                     t	 t          |dd	           n# t          $ r Y nw xY w|                    |           d{V  |d
z  }||S )z=Replay inbound messages queued while startup auto-resume ran.r   rs  Nr  zCDropping startup-restore queued message: adapter unavailable for %sr_   r   _hermes_startup_restore_replayTrk   )r-   r$  r	  r/   r0   setattrr.   r
  )r  drainedrd  r  r  r  s         r6   _drain_startup_restore_queuez*GatewayRunner._drain_startup_restore_queue'  s     6===1 	EIaLLEUHd33F..v66GYGFJ==wMM   ?FFFF   ((/////////qLG#  	$ s   B! !
B.-B.c                   K   t          t          | dg           pg           }|rt                      }|dk    rjt          j        ||           d{V \  }}|rHt
                              d|t          |                     |D ]}|                    | j	                   n&t          j
        |ddi d{V  t          |          }|D ]^}|                                r|                                }|1t
                              dt          |          ||j        f	           _g | _        |                                  d{V }d
| _        |rt
                              d|           dS dS )u	  Wait (BOUNDED) for startup auto-resume, then release + drain inbound.

        The wait is bounded by ``_startup_restore_drain_timeout_secs`` so that
        a single pathologically long boot-resume turn cannot hold the inbound
        gate shut for every channel.  On timeout we release the gate and let
        the still-running resume turn(s) finish in the background — they are
        NOT cancelled.  This is safe because duplicate-agent protection does
        not depend on the wait: ``_schedule_resume_pending_sessions`` claims
        each session's ``_running_agents`` slot SYNCHRONOUSLY before this gate
        runs, so any inbound message drained while a resume turn is still in
        flight queues behind that slot instead of spawning a second agent.
        rt  r   r  NzStartup-restore gate released after %.0fs with %d boot auto-resume turn(s) still running; draining inbound queue now (resume slots already claimed, so no duplicate agents). Slow turn(s) continue in the background.return_exceptionsTzstartup auto-resume task failedr   Fz;Drained %d inbound message(s) queued during startup restore)r  r-   rW  r  r  r/   r   r   r  _log_background_resume_resultgatherrt   r  r   r0   r   r   rt  r
  r  r  )r  rl  r  r  r  r   r5   r
  s           r6   _finish_startup_restorez%GatewayRunner._finish_startup_restore'  s      WT#;R@@FBGG %	9;;G{{ '.l5'&J&J&J J J J J J Jg SNN&
  G   !( S S..t/QRRRR neDtDDDDDDDDD5zz  >>## nn&&?LL9"&s))S#2C!D !    ')#99;;;;;;;;,1) 	`KKUW^_____	` 	`rB   r   c                     |                                  rdS |                                 }|3t                              dt	          |          ||j        f           dS dS )a  Done-callback for a boot-resume turn that outlived the
        startup-restore gate.  Logs a late failure that would otherwise be
        swallowed once the task is discarded from ``_background_tasks``.
        Cancellation is expected (shutdown) and is not an error.Nz=background startup auto-resume task failed after gate releaser   )r  r   r/   r0   r   r   r@  s     r6   r
  z+GatewayRunner._log_background_resume_result'  sq     >> 	Fnn?LLOs))S#*;<       ?rB   c                   K   	 ddl m}m}m}m}m} t          j        |           d{V sdS d | j        D             }t          j        |d|           d{V }n-# t          $ r  t                              dd           Y dS w xY w|sdS d}|D ]h}		 t          |	d	                   }
nE# t          $ r8 t                              d
|	d         |	                    d	                     Y [w xY w| j                            |
          }|||	d         }|	                    d          r||z   }|	                    d          r
d|	d         ind}	 |                    |	d         ||           d{V }n;# t          $ r.}t                              d|	d         |           d}Y d}~nd}~ww xY w	 |nt!          |dd          r]t          j        ||	d                    d{V  |dz  }t                              d|	d	         |	d         |	d         |	d                    n@t          j        ||	d         t%          t!          |dd          pd                     d{V  n,# t          $ r t                              dd           Y nw xY w|	                    d          pd}|rQ	 | j                            |           d{V  :# t          $ r! t                              d|d           Y dw xY wj|S )u  Redeliver final responses recorded in the delivery ledger by a
        previous (now dead) gateway process.

        Runs at startup BEFORE ``_schedule_resume_pending_sessions``. A
        session with a recoverable obligation already produced its answer —
        the turn completed and only delivery is owed — so this method sends
        the stored text and clears ``resume_pending`` for that session,
        preventing the resume path from re-running (and re-paying for) a
        turn whose output we hold.

        Crash-ambiguity contract (see gateway/delivery_ledger.py):
        rows that were mid-send or previously rejected carry a visible
        recovered-reply marker so a possible duplicate is labeled, never
        silent. Returns the number of redeliveries attempted.
        r   )RECOVERED_MARKERledger_enabledmark_deliveredmark_failedsweep_recoverableNc           	      J    h | ] }t          |d t          |                    !S r  )r-   rU   r  s     r6   r/  z?GatewayRunner._redeliver_pending_obligations.<locals>.<setcomp>(  s7       017CFF++  rB   )deliverable_platformszdelivery ledger sweep failedTr   r_   z"obligation %s: unknown platform %robligation_idr  needs_markerrd  r  r  r  r   z)obligation %s: redelivery send raised: %sr  Frk   zIRedelivered recovered final response to %s:%s (obligation %s, attempt %d)r|  r  r   zsend failedzdelivery ledger update failedr  z"clear_resume_pending failed for %s)gateway.delivery_ledgerr
  r
  r
  r
  r
  r  r  r{  r.   r/   r0   r  rT   r  r   r-   r  rU   r	  clear_resume_pending)r  r
  r
  r
  r
  r
  _deliverableclaimedredeliveredrb  r_   r  r  r   r  send_errr  s                    r6   _redeliver_pending_obligationsz,GatewayRunner._redeliver_pending_obligations'  s      	              !*>:::::::: q 59]  L $-!4|        GG  	 	 	LL7$LGGG11	  	1 =	 =	C#C
O44   8(#''**=*=    m''11G )nGww~&& 5*W43677;3G3GQc+.//T &||	N#%  ,          
    ?((   M%'&)U*K*K%!+NC<PQQQQQQQQQ1$KKK6JYO,c*o	    "+#O,GFGR88IMJJ        
  M M M<tLLLLLM
 ''-006BK 2GGTTTTTTTTTT    LL<k!% !      se   (A .A &BBB,,?C.-C.$E77
F/$F**F/3B0I$$&JJ* K'K76K7c           
          t                      }	  j        j        5   j                                          fd j        j                                        D             }ddd           n# 1 swxY w Y   n3# t          $ r&}t                              d|           Y d}~dS d}~ww xY w|ri	 ddl	m
}                                  \  }}|                    ||          rdS n2# t          $ r%}t                              d|           Y d}~nd}~ww xY wt          j                    }d}	|D ];}
|
j        p|
j        }|||z
                                  |k    r/                     |
j                  rJ|
j        }                     |          }|;t                              d|
j        t/          |j        d|j                             	                      |          s!t                              d	|
j                   n9# t          $ r,}t                              d
|
j        |           Y d}~d}~ww xY w                     |
j                  }t6          |j        _        t=          j                    |j        _                                           tC          dtD          j#        |d          }tI          j%         &                    |||
j                            } j'        (                    |           |)                     j'        j*                   t/           dd          r1t/           dd          }|	g }| _+        |,                    |           |	dz  }	=|	rt          -                    d|	           |	S )u  Auto-continue fresh restart-interrupted sessions after startup.

        ``resume_pending`` already preserves the transcript AND the existing
        ``_is_resume_pending`` branch in ``_handle_message_with_agent``
        injects a reason-aware recovery system note on the next turn.  This
        method closes the UX gap by synthesizing that next turn once
        adapters are back online — the event text is empty so the existing
        injection path owns the wording and we never double up.

        Adapters that are not yet ready (adapter missing from
        ``self.adapters``) are skipped silently; their sessions stay
        ``resume_pending`` and will auto-resume on the next real user
        message, or when the platform reconnects — the reconnect watcher
        calls this again scoped to that ``platform``.

        ``platform`` (a ``Platform``) restricts the pass to sessions that
        originated on that platform.  The reconnect path passes it so a
        platform coming back online retries only its own sessions and never
        re-touches another platform's in-flight recoveries.  Sessions whose
        agent is already running are skipped regardless, so a session
        scheduled at startup is never resumed a second time.
        c                 ~    g | ]9}|j         r0|j        s)|j        "|j        j        v r|j        j        k    7|:S r;   )r!  r<
  r	  r#  _AUTO_RESUME_REASONSr_   )r?   r  r_   r  s     r6   r  zCGatewayRunner._schedule_resume_pending_sessions.<locals>.<listcomp>w(  sm       #+ "O 0+t/HHH!)U\-Bh-N-N 
 .O-N-NrB   Nz/Failed to enumerate resume-pending sessions: %sr   r  z$Restart-loop guard check skipped: %sz5Skipping auto-resume for %s: adapter not ready for %sr   z^Skipping auto-resume for %s: session owner is no longer authorized under the current allowlistz;Skipping auto-resume for %s: authorization check failed: %sr   T)r   r  r  r	  r  Frt  rk   z;Scheduled auto-resume for %d restart-interrupted session(s)).rQ  rf  r~	  r	  r  r_  r.   r/   r   r1   r  r  check_and_recordr0   r   ra  r"  
updated_attotal_secondsr  r  r	  r	  r-   r_   r	  r  ri  r  r   r,   r	  r	  r:  r;  r	  r  ri  r
  r  rv   r  r  rt  rs   r  )r  r_   re  r   r5   r  _max_restarts_windowra  	scheduledr  markerr  r  _resume_stater  r   rl  s   ``                r6   !_schedule_resume_pending_sessionsz/GatewayRunner._schedule_resume_pending_sessions\(  s]   . 122	#) 	 	"88:::    '+'9'B'I'I'K'K  
	 	 	 	 	 	 	 	 	 	 	 	 	 	 	  	 	 	NNLcRRR11111	  	JJ>>>>>>)-)H)H)J)J&w((@@ 1 J J JCSIIIIIIIIJ lnn	 G	 G	E0DE4DF!sV|&B&B&D&Dv&M&M ''(9:: \F..v66GK%FOWfoFF  
 //77 NNH)  
     Q%s    !//0ABBM'>M$,0IKKM)'')))
 !(-	  E &..wu?PQQ D "&&t,,,""4#9#ABBBt;UCC #&>EE=E27D/T"""NII 	KKM   sk   A; AA/#A; /A33A; 6A37A; ;
B+B&&B+13C' '
D1DD5H
I!H<<Ic                 P    | j         p| j        p| j                                        S r;   )r  r  rh  r  r"  s    r6   _startup_should_abortz#GatewayRunner._startup_should_abort(  s.    # -~-#**,,	
rB   c                   K   |                                  sdS |r|p	 |                                 d{V  n8# t          $ r+}t                              d|j        |           Y d}~nd}~ww xY w|                     ||           d{V  | j        }t          j	                    }|||ur	| d{V  nF| j
                                        s-|                     | j        | j        | j                   d{V  dS )zCClean up and exit startup when restart/shutdown begins mid-startup.FNu'   ✗ %s background-task cancel error: %sr
  T)r
  r  r.   r/   r0   r   r  r  r  current_taskrh  r  rq  r  r  r   )r  r  r_   rs  	stop_taskr
  s         r6   $_abort_startup_if_shutdown_requestedz2GatewayRunner._abort_startup_if_shutdown_requested(  sn      ))++ 	58#7[557777777777 [ [ [FXYZZZZZZZZ[//BBBBBBBBBO	+-- Yl%B%BOOOOOOOO%,,.. 	))/!%!7 $ 9          
 ts   9 
A.!A))A.r   c                    t          | dd          }|t          |dd          sdS t          | dd          B	 t          |          | _        n,# t          $ r t                              dd           Y nw xY wt          | dd          }||                                sD	 t          |          | _        dS # t          $ r  t                              d	d           Y dS w xY wdS )
u   Arm the selector floor and out-of-loop watchdog before adapters.

        Disabled entirely with ``gateway.loop_watchdog: false`` in config.yaml
        (no env override — config-only knob, #69089).
        rX   Nloop_watchdogTr&  z&Failed to arm gateway loop floor timerr   r'  z.Failed to start gateway loop liveness watchdog)	r-   rB  r&  r.   r/   r0   is_aliverF  r'  )r  r   rX   watchdogs       r6   _start_loop_liveness_guardsz)GatewayRunner._start_loop_liveness_guards	)  s)    x..gfot&L&LF43T::BV0Ed0K0K-- V V VEPTUUUUUV 4!:DAA8#4#4#6#6^/KD/Q/Q,,, ^ ^ ^MX\]]]]]]^ s#   A &A76A7"B8 8&C"!C"c                 z   t          | dd          }d| _        |B	 |                                 n,# t          $ r t                              dd           Y nw xY wt          | dd          }d| _        |D	 |                                 dS # t          $ r  t                              dd           Y dS w xY wdS )zBDisarm lifetime liveness guards before shutdown can load the loop.r'  Nz-Failed to stop gateway loop liveness watchdogTr   r&  z)Failed to cancel gateway loop floor timer)r-   r'  rq  r.   r/   r0   r&  r  )r  r
  floor_timers      r6   _stop_loop_liveness_guardsz(GatewayRunner._stop_loop_liveness_guards)  s    4!:DAA'+$] ] ] ]LW[\\\\\] d$>EE(,%"Y""$$$$$ Y Y YHSWXXXXXXY #"s!   1 &AA8B &B87B8c           
      2   LK   t                               d           	 t          j                     n# t          t
          t          f$ r 	 t           j        dd          p8t          j
                            t          t                                d          }t          j        |d           t          j
                            |d          }t          |dd	
          }t          j        |d           n,# t           $ r t                               dd           Y nw xY wY nw xY wt          t$          dd          }|t'          t          d          r	 t           j        dd          p8t          j
                            t          t                                d          }t          j
                            |d          }t          j        |d           t          |dd	
          }t          j        ||dd           n,# t           $ r t                               dd           Y nw xY w	 t+          j                     _        n# t          $ r
 d _        Y nw xY w j                              j                   t                               d j        j                   	 ddlm}  | j                  }	|	Y|	                    d          rDt                               d|	                    dd          |	d         |	d         |	d                    n2# t           $ r%}
t                               d|
           Y d}
~
nd}
~
ww xY w	 t?          t          j         dd                    }t                               d|           n# t           $ r Y nw xY w	 t          j         d d!          }|!                                d"v }|rt                               d#           nt                               d$|           n# t           $ r Y nw xY w	 dd%l"m#}  |            }|r!|d&k    rt                               d'|           n# t           $ r Y nw xY w	 dd(l$m%}  |d)d*           n# t           $ r Y nw xY w	 dd+l&m'} dd,l(m)}  | |                       _*        t           j*        d-d.          rt                               d/           n,# t           $ r t                               d0d           Y nw xY w	 dd1l+m,}m-}  |            } ||          }|r5t                               d2|           t                               d3           n,# t           $ r t                               d4d           Y nw xY w .                                 d{V rdS d5}d6}d7}d7}	 dd8l/m0} tc          d9 |2                                D                       }tc          d: |2                                D                       }n# t           $ r Y nw xY wtg          d; ||z   D                       }t          j         d<d=          !                                d>v ptg          d? ||z   D                       }|s|st                               d@           ti           j                  }|r|5                    dAdB          d         }d} tl          7                                D ]\  }!}"|!j8        |k    r
|"dC         }  nt           9                    dD|| pdE           	 dd(l$m%}  |dF|*           n# t           $ r Y nw xY w :                    |           dS 	 ddGl;m<}#  |#             n,# t           $ r t                               dHd           Y nw xY w	 ddIl=m>}$m?}%m@}&mA}'  |&              |$            r-t                               dJ |%                        |'             n,# t           $ r t                               dKd           Y nw xY w	 dd+l&m'} ddLlBmC}(  |            }) |(|)d.M           ddLlDmC}*  |*|)           n,# t           $ r t                               dNd           Y nw xY w jE        F                                 	 ddOlGmH}+ |+I                                },|,rt                               dP|,           n2# t           $ r%}-t                               dQ|-           Y d}-~-nd}-~-ww xY wt          dRz  }.|.K                                r@t                               dS           	 |.L                                 n# t           $ r Y ntw xY w	  jM        N                                 d{V }/|/rt                               dT|/           n2# t           $ r%}-t                               dU|-           Y d}-~-nd}-~-ww xY w	  O                                }0|0rt                               dV|0           n2# t           $ r%}-t                               dW|-           Y d}-~-nd}-~-ww xY wd _P        g  _Q        g  _R        d}1d}2g }3g }4t          t           j        dXd.                    }5g }6 j        jT        7                                D ]u\  }!}7 .                                 d{V r dS |7jU        s+|5rFt          |!|7          s6t                               dY|!j8                   |6W                    |!           s|2dBz  }2 X                    |!|7          }8|8sk|!j8        }9dZ t          jZ        [                                D             }:|9|:vrt                               d[|9           nt                               d\|9           |8\                     ]                                           |8^                     j_                   |8`                     ja                   |8b                     jc                   t          |8d]d          };t          |;          r |; je                   |8f                     jg                   |8h                     i                    |8jj                              jk        |8_k        t                               d^|!j8                    l                    |!j8        d_dd`           	  m                    |8|!           d{V }< .                    |8|!           d{V r dS |<r|8 jn        |!<    o                    |8           t'          |8da          r jp        |8_q        |1dBz  }1 l                    |!j8        dbdd`           t                               dc|!j8                   n~t                               dd|!j8                    r                    |8|!           d{V  |8js        r l                    |!j8        |8jt        rdendf|8ju        |8jv        `           |8jt        r|4n|3}=|=W                    |!j8         dg|8jv                    |8jt        rL|7dBt          jx                    dhz    y                    |!|8           z                    |!|8          di j{        |!<   n l                    |!j8        deddj`           |4W                    |!j8         dk           |7dBt          jx                    dhz    y                    |!|8           z                    |!|8          di j{        |!<   n# t           $ r}-t           9                    dl|!j8        |-            r                    |8|!           d{V   l                    |!j8        dedt          |-          `           |4W                    |!j8         dg|-            |7dBt          jx                    dhz    y                    |!|8           z                    |!|8          di j{        |!<   Y d}-~-nd}-~-ww xY w .                                 d{V r dS w	  |                                 d{V }>|1|>z  }1n# t          $ r}-t          |-          }t           9                    dm|           	 dd(l$m%}  |dF|*           n# t           $ r Y nw xY wt           _         :                    |           d. _P        Y d}-~-d. _        dS d}-~-wt           $ r'}-t           9                    dn|-d           Y d}-~-nd}-~-ww xY wd. _        n# d. _        w xY w|6D ]VLtg          Lfdo j        [                                D                       }?|?s t                               dpLj8                   W|1dk    r|3r|4sdq                    |3          }t           9                    dr|           	 dd(l$m%}  |dF|*           n# t           $ r Y nw xY wt           _         :                    |           d. _P        dS |3r=t           9                    dst          |3          dq                    |3                     |2dk    r|4ridq                    |4          }t                               dtt           j{                  |           	 dd(l$m%}  |dud*           n# t           $ r Y nw xY wt                               dv|2           n4t                               dw           t                               dx            .                                 d{V rdS  jn         j        _n                                          d _                             dy           	 t           dzd          }@|@|@                                rt+          j        t          t          t           d{d|          }                     _        t           d~d          }A|A9|A                     j                    j                            |Aj                   n,# t           $ r t                               dd           Y nw xY wt           jE        j                  }B|Brt                               d|B            jE                            ddd  jn                                        D             i           d{V  |1dk    rt                               d|1           	 ddlm}C  |C jn                   d{V }Dt)          d |D                    di           [                                D                       }Et                               d|E           n2# t           $ r%}-t                               d|-           Y d}-~-nd}-~-ww xY w                                  d{V }F|Fs?tg          d t          dz  t          dz  fD                       r                                  |1dk    rt+          j        d           d{V  t1                      }Gt3                      }H|Grd _                                          d{V  |HrA	                      d           d{V  t;                       n# t;                       w xY w                                  d{V                                                                      d{V  	 ddOlGmH}+ |+j        }Ig |+_        tE          |I          D ]\  }J}K                     |Kf fd	d|K                    d           d.           t                               d|K                    d                     |Jdz  dk    rt+          j        d           d{V  n2# t           $ r%}-t           9                    d|-           Y d}-~-nd}-~-ww xY w                      j        d                                 j        d                                 j        d                                 j        d            j{        rQt                               dt           j{                  d                    d  j{        D                                                        j        d fd           _                              j        d                                 j        d           	                                  rIt                               d                                                                  j        d           n                                  n,# t           $ r t                               dd           Y nw xY w                      j        d           t                               d           dS )z
        Start the gateway and all configured platform adapters.
        
        Returns True if at least one adapter connected successfully.
        zStarting Hermes Gateway...log_dirNlogsT)r  zgateway_faulthandler.logar  rJ  )r  all_threadsz!faulthandler.enable() unavailabler   SIGUSR2r  )r  r
  rT	  z*Could not set up faulthandler file loggingzSession storage: %sr   )check_systemd_timing_alignmentmismatchzStale systemd unit detected: %s has TimeoutStopSec=%.0fs but drain_timeout=%.0fs (expected >=%.0fs). systemd may SIGKILL the gateway mid-drain. Run `hermes gateway install --force` to regenerate the unit, or shorten agent.restart_drain_timeout.unitz	(unknown)timeout_stop_secdrain_timeoutexpected_minz)check_systemd_timing_alignment failed: %sra  ro  zvAgent budget: max_iterations=%d (agent.max_turns from config.yaml, or HERMES_MAX_ITERATIONS from .env, or default 500)r  rP   >   rM   rN   rO   rP   z^Secret redaction: ENABLED (tool output, logs, and chat responses are scrubbed before delivery)zSecret redaction: DISABLED (HERMES_REDACT_SECRETS=%s). API keys and tokens may appear verbatim in chat output, session JSONs, and logs. Set security.redact_secrets: true in config.yaml to re-enable.r  r(  zActive profile: %sr  starting)r  r  r7  )start_gateway_health_exportr  Fz#Gateway health OTLP export: enabledz)gateway health OTLP export startup failed)detect_compromisedgateway_log_message%szCRun `hermes doctor` on the gateway host for full remediation steps.z1security advisory check failed at gateway startup)TELEGRAM_ALLOWED_USERSDISCORD_ALLOWED_USERSWHATSAPP_ALLOWED_USERSWHATSAPP_CLOUD_ALLOWED_USERSSLACK_ALLOWED_USERSSIGNAL_ALLOWED_USERSSIGNAL_GROUP_ALLOWED_USERSTELEGRAM_GROUP_ALLOWED_USERSTELEGRAM_GROUP_ALLOWED_CHATSEMAIL_ALLOWED_USERSSMS_ALLOWED_USERSMATTERMOST_ALLOWED_USERSMATRIX_ALLOWED_USERSDINGTALK_ALLOWED_USERSFEISHU_ALLOWED_USERSWECOM_ALLOWED_USERSWECOM_CALLBACK_ALLOWED_USERSWEIXIN_ALLOWED_USERSBLUEBUBBLES_ALLOWED_USERSQQ_ALLOWED_USERSYUANBAO_ALLOWED_USERSGATEWAY_ALLOWED_USERS)TELEGRAM_ALLOW_ALL_USERSDISCORD_ALLOW_ALL_USERSr\  WHATSAPP_CLOUD_ALLOW_ALL_USERSSLACK_ALLOW_ALL_USERSSIGNAL_ALLOW_ALL_USERSEMAIL_ALLOW_ALL_USERSSMS_ALLOW_ALL_USERSMATTERMOST_ALLOW_ALL_USERSMATRIX_ALLOW_ALL_USERSDINGTALK_ALLOW_ALL_USERSFEISHU_ALLOW_ALL_USERSrR  WECOM_CALLBACK_ALLOW_ALL_USERSrU  BLUEBUBBLES_ALLOW_ALL_USERSrY  rX  r,  platform_registryc              3   2   K   | ]}|j         	|j         V  d S r;   )allowed_users_envr?   rs  s     r6   rA   z&GatewayRunner.start.<locals>.<genexpr>)  sB       ) )()&)#) ) ) ) ) )rB   c              3   2   K   | ]}|j         	|j         V  d S r;   )rg  r  s     r6   rA   z&GatewayRunner.start.<locals>.<genexpr> *  s@       + +$%?++ + + + + +rB   c              3   >   K   | ]}t          j        |          V  d S r;   )rq   r  r  s     r6   rA   z&GatewayRunner.start.<locals>.<genexpr>*  s;       
 
BIaLL
 
 
 
 
 
rB   rb  r   >   rM   rO   rP   c              3   h   K   | ]-}t          j        |d                                           dv V  .dS )r   >   rM   rO   rP   N)rq   r  rW   r  s     r6   rA   z&GatewayRunner.start.<locals>.<genexpr>	*  s\       e
 e
 Ia""$$(<<e
 e
 e
 e
 e
 e
rB   a4  No env user allowlists configured. Messaging platforms default to pairing/allowlist policies and will deny unknown senders unless you configure platform allowlists (e.g., TELEGRAM_ALLOWED_USERS=your_id) or explicitly opt in with GATEWAY_ALLOW_ALL_USERS=true plus dm_policy/group_policy: open on the platform.r  rk   r  zuRefusing to start: %s has dm_policy/group_policy set to 'open' but neither GATEWAY_ALLOW_ALL_USERS nor %s is enabled.za platform allow-all flagstartup_failed)discover_pluginsz*plugin discovery failed at gateway startup)register_relay_adapter	relay_urlself_provision_relaysend_relay_policyz*relay adapter registered (connector at %s)z4relay adapter registration failed at gateway startup)register_from_config)accept_hooksz1shell-hook registration failed at gateway startupr  z5Recovered %s background process(es) from previous runzProcess checkpoint recovery: %s.clean_shutdownu?   Previous gateway exited cleanly — skipping session suspensionz=Marked %d in-flight session(s) as resumable from previous runz(Session suspension on startup failed: %sz'Auto-suspended %d stuck-loop session(s)zStuck-loop detection failed: %sr  zSkipping %s on default profile: no bot credential in this profile's secrets. Secondary multiplexed profiles that provide the token will still connect.c                     h | ]	}|j         
S r,  r  r?   r   s     r6   r/  z&GatewayRunner.start.<locals>.<setcomp>*  s    !Q!Q!Qa!'!Q!Q!QrB   uq   No adapter for '%s' — is the plugin installed? (platform is enabled in config.yaml but no plugin registered it)zNo adapter available for %sset_reaction_handlerzConnecting to %s...
connectingrx  _voice_input_callbackr  u   ✓ %s connectedu   ✗ %s failed to connectrv  rw  r  r  )rX   r|  r}  credential_claimlistener_claimzfailed to connectz: failed to connectu   ✗ %s error: %sz$Gateway multiplexer config error: %sz,Secondary-profile adapter startup failed: %sc              3       K   | ]}|v V  	d S r;   r,  )r?   _profile_mapr  s     r6   rA   z&GatewayRunner.start.<locals>.<genexpr>+  s<       ' '  L(' ' ' ' ' 'rB   u   %s is enabled but no profile (default or secondary) provided a bot credential for it — the platform is not being served. Add its token to the profile that should own it, or disable the platform.rv
  z0Gateway hit a non-retryable startup conflict: %szf%d platform(s) fatally misconfigured and parked: %s. Staying alive so retryable platforms can recover.uS   Gateway started with no connected platforms — %d platform(s) queued for retry: %sdegradedzNo adapter could be created for any of the %d configured platform(s). Check that required dependencies are installed and credentials are set. Gateway will continue for cron job execution.zNo messaging platforms enabled.z5Gateway will continue running for cron job execution.r  r%  r(  r  )
interval_s
start_timer  z&Failed to start gateway loop heartbeatz%s hook(s) loadedzgateway:startupr#  c                     g | ]	}|j         
S r,  r  r  s     r6   r  z'GatewayRunner.start.<locals>.<listcomp>+  s    @@@a!'@@@rB   z#Gateway running with %s platform(s)build_channel_directoryc              3   4   K   | ]}t          |          V  d S r;   )r   )r?   chss     r6   rA   z&GatewayRunner.start.<locals>.<genexpr>,  s(      WW3s88WWWWWWrB   z%Channel directory built: %d target(s)z"Channel directory build failed: %sc              3   >   K   | ]}|                                 V  d S r;   )rw   )r?   rx   s     r6   rA   z&GatewayRunner.start.<locals>.<genexpr>,  s>        
  
 KKMM 
  
  
  
  
  
rB   .update_pending.json.update_pending.claimed.jsonr	  skip_targetsc                 .                         |           S r;   )_run_process_watcher)wr  s    r6   r   z%GatewayRunner.start.<locals>.<lambda>Q,  s    d&?&?&B&B rB   zprocess_watcher:r%   )r  z(Resumed watcher for recovered process %sd   c   z!Recovered watcher setup error: %ssession_expiry_watchersession_stall_watcherkanban_notifier_watcherkanban_dispatcher_watcherz;Starting reconnection watcher for %d failed platform(s): %sr   c              3   $   K   | ]}|j         V  d S r;   r  r  s     r6   rA   z&GatewayRunner.start.<locals>.<genexpr>r,  s$      BBa!'BBBBBBrB   platform_reconnect_watcherc                 &    t          d|           S Nr+  r
  r   r  s    r6   r   z%GatewayRunner.start.<locals>.<lambda>,      wt-FJJ rB   on_spawnhandoff_watcherasync_delegation_watcheru?   scale-to-zero: armed (idle timeout %.0fs) — watching for idlescale_to_zero_watcherz*scale-to-zero: arm check failed at startupdrain_control_watcherzPress Ctrl+C to stop)r/   r  faulthandlerenabler  rH  ru   r-   rX   rq   rx   rD   rU   rG  makedirsra  r.   r0   signalr   r  r  r	  rg  r
  rJ  gateway.shutdown_forensicsr
  r  rT   r   rF  r  rW   r  r  r 	  r  rg  r8  &agent.monitoring.gateway_health_exportr
  _gateway_health_export_runtimehermes_cli.security_advisoriesr
  r
  r
  gateway.platform_registryr  ra  plugin_entriesr  rj  rC   rc  r  r   r  r  hermes_cli.pluginsr
  r  r  r  r  r  agent.shell_hooksr  agent.outbound_webhooksr  discover_and_loadr  r  recover_from_checkpointr;  rw   rD  r	  suspend_recently_activer>
  r  rs  rt  r   r#  r  r  rs   _create_adapterr  __members__r_  set_message_handler_primary_message_handlerset_fatal_error_handlerrm  set_session_storerf  set_busy_session_handlerr	  r  rg  set_topic_recovery_fnr;  set_authorization_check_make_adapter_auth_checkr_   r  r  r  r{  r  _handle_voice_channel_inputr  r  has_fatal_errorrp  r~  r  r,   rb  _adapter_credential_claim_adapter_listener_claimr  !_start_secondary_profile_adaptersrv  rI  r  r*  rQ  r   re  r  rf  r  r  ri  rD  rA  r%  rv   r  r  rz  r  rg  gateway.channel_directoryr   sum_send_update_notification#_schedule_update_notification_watchr`  r<  r@  rn  _send_restart_notification(_send_home_channel_startup_notificationsrE  r
  r
  r
  r  r  _spawn_supervised_session_expiry_watcher_session_stall_watcher_kanban_notifier_watcher_kanban_dispatcher_watcher_platform_reconnect_watcherr+  _handoff_watcher_async_delegation_watcherr  r  r  r  r	  )Mr  _fh_log_dir_fh_enable_path_fh_enable_file_sigusr2_log_dir_faulthandler_path_fhr
  
_alignmentr  _effective_max_iter_redact_raw
_redact_onr  r  r  r8  r
  r
  r
  	_adv_hits_adv_msg_builtin_allowed_vars_builtin_allow_all_vars_plugin_allowed_vars_plugin_allow_all_varsr  _any_allowlist
_allow_allrj  r  rg  r_   rd  r
  r  r  r  r  r  
_hooks_cfgregister_outbound_webhooksr  r:  rs  _clean_markerr<
  stuckconnected_countenabled_platform_countstartup_nonretryable_errorsstartup_retryable_errors_multiplex_on_multiplex_skipped_platformsr  r  _pval_builtin_names_set_reactionr  r  _secondary_connected_served_by_secondary_existing_hb_bg
hook_countr   	directorych_countr
  !chat_restart_notification_pending$planned_restart_notification_pendingwatchersr  r`
  r  sM   `                                                                           @r6   rr  zGatewayRunner.start1)  s       	0111
	Q!!!!j'2 	Q 	Q 	Q
Q%dk9dCC rw||))**H H K$7777"$',,{<V"W"W"&g"N"N"N#dKKKKK Q Q Q@4PPPPPQ	Q$ 69d33GL*$E$EZ"4;	4@@ BGLL))**E E &(W\\(<V%W%W"Ht4444-sWEEE% $	      Z Z ZITXYYYYYZ	&!(!9!;!;D 	& 	& 	&!%D	&),,T-?@@@)4;+CDDD	JQQQQQQ778STTJ%*..*D*D%V NN6;7712/~.	 	 	  	J 	J 	JLLDbIIIIIIII	J
	"%bi0G&O&O"P"PKKF#   
  	 	 	D		)$;VDDK$**,,0JJJ >   
 3      	 	 	D		CCCCCC..00H <H	110(;;; 	 	 	D		;;;;;;  ztLLLLL 	 	 	D		U555555ZZZZZZ2M2Mkkmm2\2\D/t:IuMM CABBB 	U 	U 	ULLDtLTTTTT	U	        +*,,I**955H tX...)    	 	 	LLC      	
 ::<<<<<<<< 	4!
&#
$ ')(*	CCCCCC#( ) )->-M-M-O-O) ) ) $ $  &+ + +):)I)I)K)K+ + + & &""  	 	 	D	 
 
"7:N"N
 
 
 
 
 Y8"==CCEEI]] 
ad e
 e
,/EEe
 e
 e
 b
 b

  	j 	NN@   4DK@@ 	#\\#q11!4N M&:&@&@&B&B  "(>^33$,QKME 4 LLI<!<	  ??????$$3CQWXXXXX   $$V,,,4	;;;;;; 	 	 	NN<t      		            ! """%%'' $H))++VVV
 "!### 	 	 	NNFQU      		555555>>>>>>$J  %@@@@      '&z2222 	 	 	LLC      	 	
$$&&&	A??????(@@BBI `SU^___ 	A 	A 	ANN<a@@@@@@@@	A %'88!! 	NKKYZZZ$$&&&&   N"&":"R"R"T"TTTTTTT	 lKK _ajkkk N N NI1MMMMMMMMN	?5577E QH%PPP 	? 	? 	?LL:A>>>>>>>>	? -1)&(#&(#!"13#.0  WT[2FNNOO79$)-)>)D)D)F)F i	 i	%Ho>>@@@@@@@@ tt"*   %A(O%\%\ < N	   -33H==="a'"**8_EEG  !Q!Q83G3N3N3P3P!Q!Q!Q..NN[    NN#@%HHH ''(E(E(G(GHHH++D,LMMM%%d&8999,,T-UVVV#G-CTJJM&& ;d9:::))$*PQQQ++D,I,I'JZ,[,[\\\&*&:G# KK-x~>>>00+"	 1   j $ J JX! !       BB7HUUUUUUUU  44 K.5DM(+::7CCC w(?@@ Y8<8X5#q(O88 '2#'&*	 9    KK 2HNCCCCNN#=x~NNN 77JJJJJJJJJ. 1<<$N9@9V+c::\c'.'?*1*E	 =     '<=44!< 
 '~NN1LNN   #8 *9,-.2n.>.>.C484R4R$,g5" 5" 372N2N$,g3" 3"
@ 
@D28< <<$N+5'+*=	 =    177'~BBB  
 '6()*..*:*:R*?040N0N ('1 1 /3.J.J ('/ /
< 
<.x8    /CCC 33GXFFFFFFFFF44N#-#"%a&&	 5    )//8>0H0HQ0H0HIII . !"&."2"2R"7(,(F(F ') ) '+&B&B '' '
4 
4&x0000002 >>@@@@@@@@ tt	:)-)O)O)Q)Q#Q#Q#Q#Q#Q#Q 33OO# 	 	 	 VVFLL?HHH??????$$3CQWXXXXX   <DO$$V,,,05D-444 5:D111  	[ 	[ 	[LLGUYLZZZZZZZZ	[
 5:D11ED19999 5 	 	H#& ' ' ' '$($:$A$A$C$C' ' ' $ $  ( 7 N   a* 3K #>??OQWXXXCCCCCC((7GU[\\\\\    D"@((000491t*  H344II9::	   &))+  "YY'?@@FNN>D233V  
GGGGGG,,*4(,     %    D +	    @AAASTTT ::<<<<<<<< 	4(,%))+++##I...	R"4)?FFL#|'8'8':':#,3,?*#?#*41F#L#L  - -) d$7>>?GGD5666-??LLL 	R 	R 	RLLADLQQQQQ	R 011
 	9KK+Z888joo/@@4=+=+=+?+?@@@2
   	 	 	 	 	 	 	 QKK=OOO	DIIIIII55dmDDDDDDDDIWWy}}["/M/M/T/T/V/VWWWWWHKK?JJJJ 	D 	D 	DNN?CCCCCCCC	D
 7799999999 	7C  
  
 55== 
  
  
 
 
 	7 44666
 Q-$$$$$$$$$ -J,K,K)/T/V/V, - 	-(,D%--///////// 0 	66CC!% D          4555535555 11333333333..000**,,,,,,,,,	A??????
 (8H02- (11 + +
7&&$BBBBBBw{{<'@'@BB! '   
 FT`HaHabbbs7b==!-*********+  	A 	A 	ALL<a@@@@@@@@	A 	t;=UVVV 	t:<STTT
 	t<>WXXX 	t>@[\\\ ! 	KKMD*++		BB4+ABBBBB  * (,'='=,(JJJJ (> (
 (
$ 	t46GHHH 	t=?YZZZ	V--// 
;U<<>>   &&t'BD[\\\\
 88::: 	V 	V 	VLLEPTLUUUUU	V 	t:<STTT*+++ts  4 D)B-C:9D):&D# D)"D##D)(D)B/H
 
&H32H37I I$#I$.A1L   
M*M

M=N 
NN"A#P 
PP3Q 
QQQ0 0
Q=<Q=AS &S?>S?AU &V V)AX 
XX\0 0
\=<\=]) )&^^A_$ $&``4a &a/.a/7c 
c3c..c3/e 
ee<f 
gf<<g1g7 7
h&h!!h&;8{76H {77
C@A@! @ AC. @!
AC#@+*AB/AAA*A)AB/A*
AA7A4AB/A6AA7A7+AB/B"AC. B/AC#B<ACCAC. CAC#C#AC. C.	AC7FAF# F#
AF0F/AF0I)AI= I=
AJ
J	AJ
L;B1AO- O-&APPAPR6A7AT. T.
AUT8AUUAUXAY YAYZ(B.A] ]
A^]!A^^A^b)A1Ad d&AeeAer{  r  Tr   r  _attemptr9  c                    t           dd          t                       _        t          j                    t          j                               } j                            |           :	  |           n-# t          $ r  t          
                    dd           Y nw xY w fd}|                    |           |S )u  Launch a long-lived background task with task-level supervision.

        Complements upstream's per-iteration inner-loop try/except (which only
        guards a single loop-body) by covering what that CANNOT: an exception
        raised in the watcher's OUTER ``while self._running:`` loop or its
        pre-try setup region, plus task-level death generally. A bare
        ``asyncio.create_task`` drops such an exception on the floor — no log,
        no restart, the watcher silently gone. This retains the handle in
        ``self._background_tasks``, logs any crash, and restarts with capped
        exponential backoff up to ``_MAX_SUPERVISED_RESTARTS`` failures in rapid
        succession (each within ``_SUPERVISED_HEALTHY_SECS`` of its restart).
        The counter resets after any run that stayed healthy for at least
        ``_SUPERVISED_HEALTHY_SECS`` — so a long-lived daemon that crashes
        occasionally over days is never permanently abandoned.

        ``on_spawn`` (optional) is invoked with the freshly-created task on
        every spawn, INCLUDING internal backoff respawns. Callers that also
        track the live handle elsewhere (e.g. ``self._reconnect_watcher_task``
        for ``_ensure_reconnect_watcher_running``) MUST pass it — otherwise the
        supervisor's own respawn creates a new task without updating that
        external handle, so ``_ensure_...`` later sees the stale/done handle
        and spawns a SECOND concurrent watcher (double reconnect attempts).
        r  Nzon_spawn callback for %s raisedTr   c                    j                             |             | j                    rd S  | j                    }|d S t                              d
||           r߉j        rt          j                    z
  }|j	        k    rdnj
        k    r$t                              d
j	                   d S t          ddt          d          z            	
fd}t          j         |                      }j                             |           |                    j         j                   d S d S d S )	NzSupervised task %s died: %rr   r   uh   Supervised task %s died %d times in rapid succession (each within %ds of restart) — giving up restartsr  r     c                     K   t          j                    d {V  j        r                    dz              d S d S )Nrk   r  )r  r`  rf  rc  )backoffcoro_factoryeffective_attemptr   r9  r  r  s   r6   _respawnz@GatewayRunner._spawn_supervised.<locals>._done.<locals>._respawn-  sx      !-000000000} ..( $+%6%:%- /      rB   )r  r  r  r   r/   r  rf  r,   rb  _SUPERVISED_HEALTHY_SECS_MAX_SUPERVISED_RESTARTSr  r  ri  rv   r  )r   r5   ran_forr  respawn_taskr  r  r  _startedr  r   r9  r  r  s        @@r6   _donez.GatewayRunner._spawn_supervised.<locals>._done,  s   "**1---q{}} !+--C{ LL6cCLPPP "O4= "O.**X5d;;;
 )*%%(0%$(EEELLN)5   Fb!s+<a'@'@"@AA	 	 	 	 	 	 	 	 	 	 	  '288::>>&**<888..t/E/MNNNNNE"O "O "O "OrB   )r-   rt   r  r,   rb  r  ri  rv   r.   r/   r0   r  )	r  r  r   r  r  r9  r   r  r  s	   ``````  @r6   rc  zGatewayRunner._spawn_supervised,  s   0 4,d33;%(UUD" >## "<<>>22""4(((U U U U>tTTTTTU-	O -	O -	O -	O -	O -	O -	O -	O -	O -	O -	O^ 	u%%%s   8B 'B.-B.       @c                 \  K   t          j        d           d{V  | j        r	 | j        t          j        |           d{V  +| j                                         d{V }|D ]}|                    d          }|s| j                            |           d{V s;	 |                     |           d{V  | j                            |           d{V  x# t          $ rV}t                              d||d           | j                            |t          |                     d{V  Y d}~d}~ww xY wnC# t           j        $ r  t          $ r'}t                              d|d           Y d}~nd}~ww xY wt          j        |           d{V  | j        dS dS )u  Background task that processes pending CLI→gateway session handoffs.

        Polls ``state.db`` for sessions in ``handoff_state='pending'`` and,
        for each one:

        1. Atomically claims it (pending → running).
        2. Resolves the destination platform's configured home channel.
        3. Re-binds the gateway's session_key for that home channel to the
           CLI's existing session_id via ``session_store.switch_session`` so
           the full role-aware transcript replays on the next agent turn.
        4. Forges a synthetic ``MessageEvent`` (``internal=True``) with a
           handoff-notice text and dispatches through the normal gateway
           message pipeline so the agent runs and replies on the platform.
        5. Marks the row ``completed`` (or ``failed`` with ``handoff_error``).

        The CLI process is poll-blocked on the row's terminal state and
        prints the result to the user.
        r{  Nr   z!Handoff for session %s failed: %sTr   zHandoff watcher tick error: %s)r  r`  rf  r)   list_pending_handoffsrT   claim_handoff_process_handoffcomplete_handoffr.   r/   r   fail_handoffrU   rf  r0   )r  r  r  rb  r%   r5   s         r6   ri  zGatewayRunner._handoff_watcher -  sv     * mAm 	*S#+!-111111111 $ 0 F F H HHHHHHH" R RC!$J% ! !%!1!?!?
!K!KKKKKKK ! R"33C888888888".??
KKKKKKKKKK$ R R R?&d '    #.;;JCQQQQQQQQQQQQQQRR  )    S S S=sTRRRRRRRRS-)))))))))5 m 	* 	* 	* 	* 	*sI   !E AE %;C! E !
E+AD<7E <EE FF  Frb  c           	        K   ddl m} ddlm}m} ddlm} |d         }|                    d          pd                                	                                }|st          d          	  ||          }n(# t          t          f$ r t          d	| d
          w xY wt          || j        | j                  }	|	st          d| d          |	j        }
| j                            |          }|r|j        st          d| d          |                    d          p	|dd         }d| }	 |
                    t)          |j                  |           d{V }n7# t*          $ r*}t,                              d||d           d}Y d}~nd}~ww xY w|p|j        rt)          |j                  nd}t)          |j                  }||j        k    ot5          |          }|r|sd}d}nd}|r|nd}||j        k    r|dk    r|rt)          |          }n|} ||||j        ||d|          }| j        j                            |          }|r|j        ni } |||                    dd          |                    dd                    }| j                             |           d{V  | j        !                    ||           d{V }|t          d| d |           | "                    |           | #                    |           d!| d"} |||d#          }t,          $                    d$|||j        ||           | %                    |           d{V }|sdS i }|r||d%<   	 |	&                    |t)          |j                  ||pd           d{V }n%# t*          $ r}t          d&|           |d}~ww xY wtO          |d'd          s#tO          |d(d)          } t          d&|            dS )*zAExecute one handoff row. Raises on failure (caller marks failed).r   r  )r%  r*  )r:  r   handoff_platformr   zhandoff_platform is emptyzunknown platform 'r  z
platform 'z' is not active in this gatewayzno home channel configured for z(; run /sethome on the desired chat firstrL  N   u   Hermes — z/Handoff: create_handoff_thread raised on %s: %sTr   r  zsystem:handoffr~  Handoff)r_   r  r  r}  r  r  rd  r  r  Fr  r  zcould not switch session key u    → z([Session was just handed off from CLI ("z") to this channel. The full prior conversation history is loaded above. Briefly confirm you're working here and summarize what we were working on, so the user can continue from this device.])r   r  r	  ub   Handoff: dispatching synthetic turn for CLI session %s → %s (home=%s, thread=%s, session_key=%s)rd  zadapter.send failed: r  r  r	  )(r  r  rP  r%  r*  r  r:  rT   rV   rW   r  rH  rj  r/  rX   r{  r  r 
  r  create_handoff_threadrU   r.   r/   r0   rd  r  r.  r|  r   r#  r  r	  get_or_create_sessionswitch_session_evict_cached_agentr
  r  _handle_messager  r-   )!r  rb  r  r%  r*  r:  cli_session_idr.  r_   r_  r  rX  	cli_titlethread_namenew_thread_idr5   effective_thread_idhome_chat_idis_telegram_private_chatdest_chat_typedest_user_iddest_chat_iddest_sourcer%  r  r  switchedsynthetic_textsynthetic_eventresponse_textsend_metadatar  r  s!                                    r6   r  zGatewayRunner._process_handoffR-  s     ++++++DDDDDDDD777777T!344:AACCIIKK 	<:;;;	Fx..HHH% 	F 	F 	FDMDDDEEE	F /xdmTT	 	K]KKK   # {++H55 	4< 	:- : : :  
 GGG$$:rr(:	 0I//		!")"?"?DL!!;# #      MM  	! 	! 	!LLAsT     !MMMMMM	! , 
#'>;Ct 	 4<(()) B3LAA 	!
  		Z!9 		Z%N+LL "N+CY<<IYL x'''Nh,F,FK^,F233LL'L#m i$ )
 
 
 {,00::&2:""''$)II.G$N$N%*YY/I5%Q%Q
 
 
 &<<[IIIIIIIII 1@@n]]]]]]]]RRR.RR   	  --- 	))+666G	 G G G 	 ',
 
 
 	3M4<9L		
 	
 	
 #22?CCCCCCCC 	 F )+ 	=)<M+&	G$>>DL!!%	       FF  	G 	G 	G<s<<==3F	G vy$// 	>&'+HIIC<s<<===	> 	>s<   ,A8 8%B2.E! !
F+ FF52N( (
O
2OO
c           	      "  K   t          j        d           d{V  i }d}| j        r	 | j                                         d{V  g }t          | j        j                                                  D ]E\  }}|j	        r| j        
                    |           d{V s.|                    ||f           F|ri }|D ]S\  }}	|                    d          }
t          |
          dk    r|
d         nd}|                    |d          dz   ||<   Td	                    d
 t!          |                                          D                       }t"                              dt          |          |           |D ]o\  }}	 	 ddlm} |                    d          }
t          |
          dk    r|
d         nd} ||j        |d           n# t,          $ r Y nw xY wd}t/          | dd          }|W|5  | j                            |          }t3          |t4                    r|d         n|r|nd}ddd           n# 1 swxY w Y   |%|                     |          }|r|j        j        nd}|r&|t<          ur|                     |d           d{V  |                      |           | !                    |d           | j        "                    |           d{V  t"          #                    d|j                   |$                    |j        d           # t,          $ r}|                    |j        d          dz   }|||j        <   ||k    r`t"          %                    d||j        |           | j        "                    |d           d{V  |$                    |j        d           n#t"          #                    d|||j        |           Y d}~id}~ww xY w|retM          d |D                       }t          |          |z
  }|rt"                              d||           nt"                              d|           	 | '                                }|rt"                              d|           n2# t,          $ r%}	t"          #                    d|	           Y d}	~	nd}	~	ww xY wt/          | dd           }d!}tQ          j(                    |z
  |k    r	 tS          t/          | j*        d"d          pd          }|dk    r=| j        +                    |           d{V }|rt"                              d#|           n2# t,          $ r%}	t"          #                    d$|	           Y d}	~	nd}	~	ww xY wtQ          j(                    | _,        n2# t,          $ r%}t"          #                    d%|           Y d}~nd}~ww xY wt[          |          D ]%}| j        s nt          j        d           d{V  &| j        dS dS )&a  Background task that finalizes expired sessions.

        Runs every ``interval`` seconds (default 5 min).  For each session
        whose reset policy has expired, invokes ``on_session_finalize``
        hooks, cleans up the cached AIAgent's tool resources, evicts the
        cache entry so it can be garbage-collected, and marks the session
        so it won't be finalized again.
        r  Nr  r  r  r  r   rk   r   c              3   *   K   | ]\  }}| d | V  dS )r  Nr,  )r?   r  cs      r6   rA   z8GatewayRunner._session_expiry_watcher.<locals>.<genexpr>?.  sA       . .'+q!1

q

. . . . . .rB   z,Session expiry: %d sessions to finalize (%s)r
  r   session_expiredr
  r  r$
  r
  expiry_finalizedr6  zSession expiry finalized for %szkSession finalize gave up after %d attempts for %s: %s. Marking as finalized to prevent infinite retry loop.F)clear_model_overridez*Session finalize failed (%d/%d) for %s: %sc              3   .   K   | ]\  }}|j         d V  dS )rk   N)r  )r?   r  rs  s      r6   rA   z8GatewayRunner._session_expiry_watcher.<locals>.<genexpr>.  sB          "a!:L            rB   z3Session expiry done: %d finalized, %d pending retryz!Session expiry done: %d finalizedz+Agent cache idle sweep: evicted %d agent(s)zIdle agent sweep failed: %s_last_session_store_prune_tsr  r!   session_store_max_age_daysz,SessionStore prune: dropped %d stale entrieszSessionStore prune failed: %sz Session expiry watcher error: %s).r  r`  rf  r	  r	  r  rf  r  r  r  _is_session_expiredrs   rC   r   rT   rD   sortedr/   r  r
  r
  r%   r.   r-   r  rR   ra  r  r  r   ri  r
  r  _clear_conversation_scopeset_expiry_finalizedr0   r$  r   r^  _sweep_idle_cached_agentsr,   rF  rX   prune_old_entriesr  range)r  r  _finalize_failures_MAX_FINALIZE_RETRIES_expired_entriesr  r  
_platforms_kr  r  _plat_plat_summaryr
  	_platform_cached_agentr  _cached
_exp_staters  failuresr  _failed_idle_evicted_last_prune_ts_prune_interval_max_age_prunedr  s                                r6   rd  z%GatewayRunner._session_expiry_watcher.  sZ      mB-/ !m d	'^D.==?????????#% "&t'9'B'H'H'J'J"K"K : :JC- ! !%!9!M!Me!T!TTTTTTT ! $++S%L9999#  24J"2 I IB!##-0[[1__q		),6NN5!,D,Dq,H
5))$(II . ./5j6F6F6H6H/I/I. . . % %M KKF,--}  
 #3 L LJCK
!MMMMMM%(YYs^^F58[[1__q		"I,,+0+;)2'8    
  ) ! ! ! D!
 )-&-d4G&N&N&2!, { {*.*;*?*?*D*D>HRW>X>X0z

ip^z^e^evz{ { { { { { { { { { { { { { {
 )0)-)A)A#)F)FJEO,YJO,A,AUYM( ]BY-Y-Y"&"H"H -7G #I # #        00555 66(: 7    #6KKERRRRRRRRR=!,   +..u/?FFFF$   #5#9#9%:JA#N#NQR#R?G*5+;<#'<<<"NN!W (%*:A  
 #'":"O"O %E #P # #        /2253CTJJJJ"LL L (*?AQST  & $     &6       E ""233e;G Q!7   
 ?  D$($B$B$D$DM$ I)   ! D D DLL!>CCCCCCCCD ")/Ms!S!S"(9;;//AAJ#&#DK1MqQQVUV$ $ $a<<,0,D,V,VW_,`,`&`&`&`&`&`&`G& " &$R$+!" !" !" % J J J%DbIIIIIIIIJ8<	D5 D D D?CCCCCCCCD 8__ ' '} EmA&&&&&&&&&&I m d	' d	' d	' d	' d	's   EV AGL'
G L'G  L':>I8L'I	L'I	CL'%V '
O-1B1O("V (O--A*V 1R
 	V 

R9R4/V 4R990V *A(U V 
VU=8V =VV 
W(WWc                 "    t          dd          S )zCReturn configured stall timeout (seconds); 0 disables the watchdog.r  r  )rY  r"  s    r6   _session_stall_timeout_secondsz,GatewayRunner._session_stall_timeout_seconds.  s    8#>>>rB   c              #     K   t                      }t          t          | di                                                     D ]2}|t	          |          }||v r|                    |           |V  3t          t          | di                                                     D ]V}t          |                                          D ]2}|t	          |          }||v r|                    |           |V  3WdS )zAYield every live platform adapter (default + multiplex profiles).r{  NrQ  )rt   r  r-   r_  r   rv   )r  r   r  aidamaps        r6   _iter_gateway_adaptersz$GatewayRunner._iter_gateway_adapters.  s     GD*b99@@BBCC 	 	GW++Cd{{HHSMMMMMMM':B??FFHHII 	 	D..  ?kk$;;	 	rB   c                    t          | dd          pi                     |          }|	|t          u rdS t          |d          sdS 	 |                                }n# t
          $ r Y dS w xY wt          |t                    r|ndS )zReturn the shared activity snapshot for stall progress (#72039).

        Single progress source: ``AIAgent.get_activity_summary()`` /
        ``agent.session_activity``. No turn-start or pending-inbound clocks.
        r  Nr	  )r-   rT   ri  r   r	  r.   rR   rS   )r  r  r   r	  s       r6   _session_activity_for_stallz)GatewayRunner._session_activity_for_stall.  s     0$77=2BB;OO=E%<<<4u455 	4	0022GG 	 	 	44	$Wd33=ww=s   A 
A*)A*timeout_secondsc                 	  K   ddl m}m}m}m} t          | dd          }|	i }|| _        d}t          j                    }i }	|                                 D ]K}
t          |
dd          pi }t          |
                                          D ]\  }}|r||	vr	||
|f|	|<   Lt          t          | dd          pi 
                                          D ]J\  }}|r||	v s|s|d         }t          |dd          }||                     |          nd}
|
C|
|f|	|<   Kt          |	
                                          D ]o\  }\  }
}|du}|r|                     |          nd}|r |||          nd}t          |                    |                    } ||||	          r|                    |d           d
} |||||          s|t!          dt#          |dz                      }|pi }t$                              d|||||                    d          p|                    d          pd|                    d          p|                    d          pd           t          |dd          }|t          |dd          nd}|s"t$                              d|           d||<   tt          |
dd          pi                     |          dup2t          t          | dd          pi                     |                    } ||                     |          t          j                              }|r|;||k     r5t$                              d|||           |                    |d           ?	 |%t+          | d          r|                     |          nd}	 t/          j        |
                    t5          |           ||          |          t6                     d{V }n7# t.          j        $ r% t$                              dt6          |           Y w xY w|@t          |dd          d
u r-t$                              d|t          |dd                     1|dz  }d||<   =# t:          $ r'}t$                              d||           Y d}~id}~ww xY wt          |                                          D ]}||	vr|                    |d           |S ) zScan pending inbound sessions and notify once per stall episode.

        Returns the number of notifications sent this pass (for tests).
        r   )!format_session_stall_notification*resolve_session_idle_seconds_from_activity'should_clear_session_stall_notification&should_emit_session_stall_notificationrr  Nr  rq  r  r  )r  r  has_pending_inboundF)r  r  r  already_notifiedrk   r  zSession stall detected: session=%s idle=%.0fs (timeout=%.0fs, ~%d min); pending inbound present | last_activity=%s | provenance=%s (agent.session_stall_timeout)last_activity_desclast_activity_descriptionr  r[  last_activity_provenancer  z5Session stall notify skipped (no chat_id): session=%sTzSSession stall notify aborted (no longer stale): session=%s pending=%s fresh_idle=%sr	  r  r  zLSession stall notify send timed out after %.0fs for %s; will retry next tickr  z&Session stall notify failed for %s: %sr  r	  )gateway.session_stallr  r  r  r  r-   rr  r,   r  r  r  r	  r  r   rT   r$  r  rF  r/   r   r  r   r	  r  r  r  rU   "_STALL_NOTIFY_SEND_TIMEOUT_SECONDSr  r.   rg  )r  r  r  r  r  r  notified_mapsentra  r   r  r  r  r  r  r  r  has_pendingactivityr  alreadyminsr  still_pending
fresh_idler   r  r5   r  s                                r6   _check_session_stallsz#GatewayRunner._check_session_stalls.  s     
	
 	
 	
 	
 	
 	
 	
 	
 	
 	
 	
 	
 t%>EEL+7D(ikk13
2244 	? 	?G"7,?FFL"L&*<+=+=+?+?&@&@ ? ?"U ?;j#@#@UEV/6.>J{+? &*T+T228b??AA&
 &
 	7 	7!K  +";";8";QKEUHd33F4:4F((000D  '.&6J{##59*:J:J:L:L5M5M E	 E	1K1'='t3KALV00===RV 
 ::8MMMM 
 <++K8899G66 /)$/    
   d33399 /)$/!(	    #q#lb01122D~2HNN0 122 << ;<<\** << :;;    ]Hd;;F:@:Lgfi666RVG K  
 -1[) "5t<<BGG    T#3T::@bEE#    DC00==IKK  J ! &:+G+G:!     d333* )gd<Y.Z.Z) 44V<<< #*#3LL==lKK%- %  
 !C$ $ $      FF +   NN7:#	   H %'&)T*J*Je*S*SNN@#1NOO  
 	,0[))   <        ))++,, 	, 	,C*$$  d+++sD    )Q=*AO87Q=80P,(Q=+P,,AQ=1
Q==
R.R))R.c                 @  K   t          j        t          dt          dt	          |                                         d{V  | j        r	 |                                 }|dk    r|                     |           d{V  n2# t          $ r%}t          
                    d|           Y d}~nd}~ww xY wt          dt          t	          |                              }t          |          D ]%}| j        s nt          j        d           d{V  &| j        dS dS )aE  Periodic pending-inbound + stale-activity stall watchdog (#72016).

        Progress comes only from ``get_activity_summary()`` (#72039).
        Pending inbound is a notify policy gate, not a progress clock.
        Notify-only: does not kill the turn (contrast ``gateway_timeout`` /
        ``shutdown_watchdog``).
        r"   r	  Nr   zSession stall watcher error: %srk   )r  r`  r  r  rG  rf  r  r  r.   r/   r0   rF  r  )r  r  r  r5   stepsr  s         r6   re  z$GatewayRunner._session_stall_watcher/  sd      mCc#uX&?&?@@AAAAAAAAAm 	'E==??Q;;44W========= E E E>DDDDDDDDE 3uX//00E5\\ ' '} EmA&&&&&&&&&& m 	' 	' 	' 	' 	's   5B 
B3B..B3c                 J    	 ddl m}  |            pdS # t          $ r Y dS w xY w)z0Return the profile name this gateway represents.r   r  r(  )r  r  r.   )r  r  s     r6   r{  z"GatewayRunner._active_profile_name/  sO    	CCCCCC**,,9	9 	 	 	99	s    
""c                 ,    t           dd          sdS t           dd          }||                                sdS t                              d||                                nd                                 j        d fd	           _        dS )
a  Ensure the platform reconnect watcher background task is alive.

        If the tracked reconnect watcher task has died (e.g. from exhausting
        its restart budget, or a terminal exception that _spawn_supervised
        could not recover), respawns it so platforms queued for reconnection
        are not permanently stranded. Called after queueing a retryable fatal
        error in _handle_adapter_fatal_error (#70344).
        rf  FNr+  u7   Reconnect watcher task is dead (done=%s) — respawningzN/Ar2  c                 &    t          d|           S r4  r5  r6  s    r6   r   zAGatewayRunner._ensure_reconnect_watcher_running.<locals>.<lambda>/  r7  rB   r8  )r-   r  r/   r   rc  rh  r+  )r  r   s   ` r6   r  z/GatewayRunner._ensure_reconnect_watcher_running/  s     tZ// 	Ft6==DIIKKFE+DIIKKK	
 	
 	
 (,'='=,(JJJJ (> (
 (
$$$rB   c           
      x  K   t          j        d           d{V  | j        r| j        s@t	          d          D ]/}| j        s dS | j        r nt          j        d           d{V  0Ot          j                    }t          | j                                                  D ]}| j        s dS | j        	                    |          }|*|	                    d          r@||d         k     rM|d         }|d         dz   }t          ||          s)t                              d	|j                   | j        |= t                              d
|j        |           d}	 |                     ||          }|s)t                              d|j                   | j        |= |                    |                                            |                    | j                   |                    | j                   |                    | j                   t1          |dd          }t3          |          r || j                   |                    | j                   |                    |                     |j                             | j         |_         | !                    ||d           d{V }	|	r|| j"        |<   | #                    |           tI          |d          r| j%        |_&        | j"        | j'        _"        | j        |= | (                    |j        ddd           t                              d|j                   	 ddl)m*}
  |
| j"                   d{V  n# tV          $ r Y nw xY w	 | ,                    |           n:# tV          $ r& t          -                    d|j        d           Y nw xY w|j.        rs|j/        sl| (                    |j        d|j0        |j1                   t                              d|j        |j1                   te          |           d{V  | j        |= n| (                    |j        d|j0        |j1        pd           tg          |          }||d<   t          j                    |z   |d<   t                              d|j        |           te          |           d{V  ,# tV          $ r}|te          |           d{V  | (                    |j        ddti          |                     tg          |          }||d<   t          j                    |z   |d<   t                              d|j        ||           Y d}~d}~ww xY wt	          d          D ]&}| j        s dS t          j        d           d{V  '| j        dS dS )u7  Background task that periodically retries connecting failed platforms.

        Uses exponential backoff: 30s → 60s → 120s → 240s → 300s (cap).
        Retryable failures (network/DNS blips) keep retrying at the backoff
        cap indefinitely — they self-heal once connectivity returns, so a
        transient outage never requires manual intervention. Non-retryable
        failures (bad auth, etc.) drop out of the queue immediately. The
        circuit breaker (``_pause_failed_platform`` / ``/platform pause``)
        remains available for manual operator control via ``/platform list``
        and ``/platform resume <name>``, but is no longer triggered
        automatically — auto-pausing a recovered platform was the cause of
        bots silently staying dead after a transient DNS failure.
        r  Nr  rk   r	  r}  rX   r|  zKReconnect %s: no bot credential on queued config, removing from retry queuezReconnecting %s (attempt %d)...zGReconnect %s: adapter creation returned None, removing from retry queuer  Tr  r  r  rx  u   ✓ %s reconnected successfullyr   r  rc   z3resume-pending reschedule after %s reconnect failedr   rw  zAReconnect %s: non-retryable error (%s), removing from retry queuerv  zfailed to reconnectz&Reconnect %s failed, next retry in %dsz)Reconnect %s error: %s, next retry in %ds)5r  r`  rf  r  r  r,   rb  r  rg  rT   r  r/   r   r   r  rN  rP  rQ  rR  rm  rS  rf  rT  r	  r-   r  rg  rU  r;  rV  rW  r_   r  r  r{  r  r   rX  r  re  r  r]  r   r.   r
  r0   rY  rp  r~  r  r  r  rU   )r  r  ra  r_   r  r  r  r  r  r  r   r  rs  s                r6   rh  z)GatewayRunner._platform_reconnect_watcher/  s7      mBm B	') r + +A= - !-**********.""C !7!<!<!>!>?? m m} FF-11(;;<
  88H%% l+++"&x.z*Q. 4HoNN NN4   
 .x85NG  
 I"228_MMG" !e$N   !28< //0M0M0O0OPPP33D4TUUU--d.@AAA44T5]^^^$+G5KT$R$RM.. C%d&ABBB11$2XYYY33D4Q4QRYRb4c4cddd.2.BG+
 %)$F$F %G % %      G  P?29h/>>wGGG"7,CDD ]<@<\G98<,5 28<<<$N+6'+*.	 =    $Ex~VVV!YYYYYY"9"9$-"H"HHHHHHHHH( ! ! ! D! BBHBUUUU(   "LL U ()- )      !0 *?9V *?<<$N+2'.'?*1*E	 =    _$NG,G   6g>>>>>>>>> 28<<<<$N+5'.'?*1*E*^I^	 =    #5W"="=+2Z(-1^-=-=-G\*D$NG   6g>>>>>>>>> !   * 6g>>>>>>>>>88 '1#'&)!ff	 9    199G'.D$)-)9)9G)CD&NNC 7       %6 2YY ' '} FFmA&&&&&&&&&&E m B	' B	' B	' B	' B	'sj   "A S#F+SM,+S,
M96S8M99S=NS,OSOD
S
U7BU22U7c                   K   | j         }t          |t                    sdS t          j                    }g }|                                D ]v}t          |t                    s|                                D ]I}t          |t          j                  r-||ur)|                                s|                    |           Jw|D ]}|	                                 | 
                                }|rO|dk    rIt          j        ||           d{V \  }}|r(t                              dt          |                     |                                 dS )a  Cancel profile-scoped reconnects before tearing down their registry.

        A reconnect can be waiting in adapter setup while shutdown begins. It
        must not republish an adapter after the secondary registry is drained.
        Waiting is bounded by the same adapter-cleanup budget; if a task does
        not finish in time, the stopped runner state still prevents it from
        installing an adapter when it eventually resumes.
        Nr   r  zLTimed out waiting for %d secondary profile reconnect task(s) during shutdown)r  rR   rS   r  r
  r_  Taskr  rs   r  r  r  r/   r   r   r  )	r  r  rf  rl  profile_pendingr   r  r  
unfinisheds	            r6   )_cancel_secondary_profile_reconnect_tasksz7GatewayRunner._cancel_secondary_profile_reconnect_tasks0  st      0'4(( 	F&(($&&~~// 	' 	'Oot44 '..00 ' 'dGL11 'd'6I6IRVR[R[R]R]6ILL&&&'  	 	DKKMMMM7799 	Wq[[&-l5'&J&J&J J J J J J JE: b
OO   	rB   c                     | j         r| j        j        dk    rdS | j        dS ddlm}  |d          }|                                sdS || _        |                    d           dS )zAStart sd_notify only after a configured gateway is truly running.r   FNT)SystemdWatchdog)config_enabledzHermes Gateway running)rf  rX   systemd_watchdog_secondsr  gateway.systemd_notifyr  rr  ready)r  r  r
  s      r6   _start_systemd_watchdogz%GatewayRunner._start_systemd_watchdog0  s    } 	 D I I5!-4::::::"?$777~~ 	5!)/000trB   c                 b   K   | j         }|dS d| _         |                                 d{V  dS )z;Stop heartbeats before any potentially long shutdown drain.N)r  rq  )r  r
  s     r6   _stop_systemd_watchdogz$GatewayRunner._stop_systemd_watchdog0  sG      )F!%mmoorB   r
  r  r
  r
  c                2   K   t           dd          }t          |          r
 |             |rd _        | _        | _         j         j         d{V  dS d fd}d fdt          j         |                       _         j         d{V  dS )z-Stop the gateway and disconnect all adapters.r
  NTr'   c                    K   dt           dd fd} t          j                    }|_        i dt          ffd}t
          j                            d          s%t          t          j
                  ||d           	  |            d {V  |                                 d S # |                                 w xY w)Nphaser'   c                    	 ddl m} |                                }|rt                              d| |           n3# t
          $ r&}t                              d| |           Y d}~nd}~ww xY w	 ddlm}  |d|  d          }|r=t          	                    d	| t          |          d
                    |                     n3# t
          $ r&}t                              d| |           Y d}~nd}~ww xY w	 ddlm}  |d|  d          }|rt                              d| |           n3# t
          $ r&}t                              d| |           Y d}~nd}~ww xY w	 ddlm}  |             n3# t
          $ r&}t                              d| |           Y d}~nd}~ww xY w	 ddlm}	  |	             dS # t
          $ r'}t                              d| |           Y d}~dS d}~ww xY w)uw  Kill tool subprocesses + tear down terminal envs + browsers.

                Called twice in the shutdown path: once eagerly after a
                drain timeout forces agent interrupt (so we reclaim bash/
                sleep children before systemd TimeoutStopSec escalates to
                SIGKILL on the cgroup — #8202), and once as a final
                catch-all at the end of _stop_impl() for the graceful
                path or anything respawned mid-teardown.

                All steps are best-effort; exceptions are swallowed so
                one subsystem's failure doesn't block the rest.
                r   r  z,Shutdown (%s): killed %d tool subprocess(es)z(process_registry.kill_all (%s) error: %sN)mark_running_jobs_interruptedzGateway shutdown (z;) killed the job's tool subprocess before the run finished.z>Shutdown (%s): marked %d in-flight cron job(s) interrupted: %sr   z,mark_running_jobs_interrupted (%s) error: %s)interrupt_allzgateway shutdown (rT  r6  z6Shutdown (%s): interrupted %d background delegation(s)z"async interrupt_all (%s) error: %s)cleanup_all_environmentsz'cleanup_all_environments (%s) error: %s)cleanup_all_browsersz#cleanup_all_browsers (%s) error: %s)r  r  kill_allr/   r  r.   r0   r2  r  r   r   rD   r  r  tools.terminal_toolr   tools.browser_toolr!  )
r  r  _killedr  r  _interrupted_interrupt_async_async_nr   r!  s
             r6   _kill_tool_subprocesseszGGatewayRunner.stop.<locals>._stop_impl.<locals>._kill_tool_subprocesses1  s   	XGGGGGG.7799G J!7   ! X X XLL!KUTVWWWWWWWWX\ MLLLLL#@#@>U > > >$ $L $ \!3|#4#4dii6M6M   ! \ \ \LL!OQVXZ[[[[[[[[\	RXXXXXX//7TE7T7T7TUUUH T!8   ! R R RLL!EubQQQQQQQQRWLLLLLL,,....  W W WLL!JESUVVVVVVVVWSGGGGGG((*****  S S SLL!FrRRRRRRRRRSsv   8; 
A+A&&A+/AC 
C4C//C484D- -
E7EE!E2 2
F"<FF"&F8 8
G)G$$G)c            
      |                        d          } t          j                  t          j                  t          j                                                                                                                  j        t          j                  | t          j                    | z
  nd d	S )Nr   )	r  r  r  r  active_cron_jobsactive_api_runsr  watchdog_delay_sphase_elapsed_s)rT   r   r  r  rf  r  r  r  r  rE  r,   rb  )started_stop_started_at_boxr  s    r6   _shutdown_watchdog_snapshotzKGatewayRunner.stop.<locals>._stop_impl.<locals>._shutdown_watchdog_snapshot]1  s    .22377)-d.E)F)F $T^ 4 4#DM22%)%>%>%@%@(,(C(C(E(E'+'A'A'C'C-1-H(G3) ) 7>6I((722t  rB   PYTEST_CURRENT_TESTrk   )
done_eventsnapshot_fnr  )rU   ro  r  r)  rS   rq   rr   rT   rC  rE  r  rt   )r)  _watchdog_doner1  r0  _stop_impl_bodyr  s      @r6   
_stop_implz&GatewayRunner.stop.<locals>._stop_impl1  s.     ?Ss ?St ?S ?S ?S ?SN '_..N+9D(57        $ :>>"788 %3D4OPP- ;	   %%o+(        
 ""$$$$$""$$$$s   B) )B?c                 N  !K   t                               d"j        rdnd           t          j                    !!|d<   dt
          f!fd}d"_        d"_        t          "d	d           }t          |          r |             d {V  "
                                 d {V  "                                 d {V  t                               d
 |                       "j        }g }t          "j                                                  D ]\  }}|t           u r	 "j                            |"j        rdnd           d {V  |                    |           P# t(          $ r&}t                               d||           Y d }~{d }~ww xY w"                                }	"                                }
t          j                    }"                    |           d {V \  }}t                               d |            t          j                    |z
  |t3          |          "                                |	"                                |
"                                
  
         |sc|D ]`}|"j        vrU	 "j                            |           d {V  -# t(          $ r&}t                               d||           Y d }~Xd }~ww xY wa|rt                               d|"                                "                                "                                           "j        rdnd}t          "j                                                  D ]d\  }}|t           u r	 "j                            ||           d {V  2# t(          $ r&}t                               d||           Y d }~]d }~ww xY w"                    "j        rt<          nt>                     tA          j!                                                    dz   }"j        rtA          j!                                                    |k     r_""                    d           tA          j#        d           d {V  "j        r)tA          j!                                                    |k     _ | d           t                               d |                       "j        rU"j$        rN	 "%                                 d {V  n2# t(          $ r%}t           &                    d|           Y d }~nd }~ww xY w"'                    |           d {V  t          "dd           }t          "dd           }|||5  t          |(                                          }|)                                 d d d            n# 1 swxY w Y   |D ]>}tU          |tV                    r|d         n|}",                    |d           d {V  ?t          "j-                                                  D ]!\  }}".                    ||           d {V  "t          t          "di                                                     D ]^\  }}t          |                                          D ]#\  }}".                    |||           d {V  $|)                                 _t_          "d          r"j0        )                                 t                               d |                       t          "j1                  D ]*}|"j2        u r|"j3        u r|4                                 +"j1        )                                 "j-        )                                 t          "j                  D ]}"5                    |           	 dd l6m7}  |tq          "j9                  d!"           n# t(          $ r Y nw xY w"j        )                                 "j:        )                                 t_          "d#          r"j;        )                                 "j9        )                                 "j<        )                                 t_          "d$          r"j=        )                                 "j>        ?                                  | d%           t                               d& |                       	 dd'l@mA}  |             n2# t(          $ r%}t                               d(|           Y d }~nd }~ww xY wt          "d)d           }t          |d*|          }|t          t          "d+d           d*d           fD ]\}|t_          |d,          s	 |B                                 +# t(          $ r%}t                               d-|           Y d }~Ud }~ww xY wt          D                    "           t                               d. |                       dd/lEmF}mG}   |              |              |s.	 t          d0z  I                                 n*# t(          $ r Y nw xY wt                               d1           |r4"J                    t          |K                                                     "j        r"jL        	 t          t                      t          j                    t          "jP                  t          "j$                  d2d 3           n2# t(          $ r%}t                               d4|           Y d }~nd }~ww xY w"j        r5"jP        r."Q                                 t          "_S        "jT        pd5"_T        d"_        t          "d6d          r="j        s6t                               d7           ""                    d8"jT                   n""                    d9"jT                   t          "           t                               d: |                       d S );NzStopping gateway%s...z for restartr   r   r'   c                  0    t          j                     z
  S r;   )r,   rb  )_stop_started_ats   r6   _phase_elapsedzCGatewayRunner.stop.<locals>._stop_impl_body.<locals>._phase_elapsed1  s    ~''*:::rB   FTr  z5Shutdown phase: notify_active_sessions done at +%.2fsrl  rm  z/pre-drain mark_resume_pending failed for %s: %szShutdown phase: drain done at +%.2fs (drain took %.2fs, timed_out=%s, active_at_start=%d, active_now=%d, cron_at_start=%d, cron_now=%d, api_at_start=%d, api_now=%d)z2clear_resume_pending after drain failed for %s: %szGateway drain timed out after %.1fs with %d active agent(s), %d in-flight cron job(s), and %d api_server run(s); interrupting remaining work.z%mark_resume_pending failed for %s: %sr#   r  r	  zpost-interruptz7Shutdown phase: post-interrupt tool kill done at +%.2fsz-Failed to launch detached gateway restart: %sr  r  r   zshutdown idle-cacher
  rQ  r  z3Shutdown phase: all adapters disconnected at +%.2fs)flush_pending_to_filer  r6  r
  r  zfinal-cleanupz6Shutdown phase: final-cleanup tool kill done at +%.2fs)shutdown_cached_clientsz!shutdown_cached_clients error: %sr)   r*   rf  r.
  zSessionDB close error: %sz.Shutdown phase: SessionDB close done at +%.2fsremove_pid_filerelease_gateway_runtime_lockr  u   Skipping .clean_shutdown marker — drain timed out with interrupted agents; next startup will suspend recently active sessions.)requested_atr
  r
  r  z7Failed to write planned restart notification marker: %szGateway restart requestedrl  u   Gateway stopped by an unexpected signal — persisting gateway_state=running so container_boot auto-starts on the next boot (issue #42675)r  stoppedz&Gateway stopped (total teardown %.2fs))Vr/   r  r  r,   rb  rG  rf  r  r-   r  r  r
  r  r  r  r  ri  r	  mark_resume_pendingrs   r.   r0   r  r  r	  r   r  r
  r   r	  !_INTERRUPT_REASON_GATEWAY_RESTART"_INTERRUPT_REASON_GATEWAY_SHUTDOWNr  r	  r  r`  r  rg
  r  r
  r_  r  rR   ra  r
  r{  r  r   rQ  r  r  r  r  r
  r
  r<  rS   r  r	  r
  r  r  rh  rt   r0
  r=  r.
  r  _shutdown_executorr 	  r?  r@  r;  touchr8
  rg  r  rI  r>  r   r   r~
  rJ  r  rk  _shutdown_gateway_health_export)#r)  r0  r;  stop_watchdogr  _pre_drain_keys_skr  r  _cron_at_start_api_at_start_drain_started_atr  r	  _resume_reasoninterrupt_deadliners  r  r  _idle_agents_entryr_   r  _prof_amap_task_session_keyr<  r=  _self_dbr*   r?  r@  r:  r  s#                                    @r6   r6  z+GatewayRunner.stop.<locals>._stop_impl_body1  s"     KK'"&"9Ar    $~//(8 %;E ; ; ; ; ; ; "DM!DN#D*BDIIM&& &#moo%%%%%%%@@BBBBBBBBB ::<<<<<<<<<KKG    
 1G *,O#D$8$>$>$@$@AA 
] 
]V444]2FF-1-D\))J\         $**3////  ] ] ]LL!RTWY[\\\\\\\\] "88::N 6688M $ 0 0-1-F-Fw-O-O'O'O'O'O'O'O$M9KK/     #44M""))++++--**,,      +  C$"666"&":"O"OPS"T"TTTTTTTTT(   "LL T #R        7  @3 --////11..00  > *.)@X%%FX  $((<(B(B(D(D#E#E 	 	KC!888 "6JJ3P^__________$   C       
 ..9=9Px55Vx   &-%=%?%?%D%D%F%F%L"* -w/G/I/I/N/N/P/PSe/e/e//
;;;!-,,,,,,,,, * -w/G/I/I/N/N/P/PSe/e/e ('(8999M"N$$  
 & U4+A UU??AAAAAAAAAA  U U ULL!PRSTTTTTTTTU 00????????? "$(;TBBKT>488F&6+=  # ##'#8#8LLLNNN# # # # # # # # # # # # # # # + 	 	F%/%>%>Jq		F  @@(= A           &*$-*=*=*?*?%@%@ H H!'44WhGGGGGGGGGG !%WT3F%K%K%Q%Q%S%S T T  u)-ekkmm)<)<  %Hg885 9           t011 /&,,...KKE    
 d455 	 	DO++D...
 "((***M!!! $T%9 : : @ @11,????
HHHHHH%%d4+A&B&B:VVVVV     &&(((#))+++t566 4+11333"((***#))+++t^,, *!''))) $$&&& $#O444KKH    FJJJJJJ'')))) F F F@"EEEEEEEEF t]D99Hx99H ''$*N*NPUW["\"\] B B;gc7&;&;;BIIKKKK  B B BLL!<bAAAAAAAAB,,T222KK@    
 UTTTTTTTO((***  
!$55<<>>>>    D '    R66s=;M;M;O;O7P7PQQQ& _4+G+O_%:<<,0IKK+/0I+J+J(,T-C(D(D 
  $     ! _ _ _LL!Z\]^^^^^^^^_ & U4+D U55777& #D$($5$T9T!"DN, t95AA J$Ja J3  
 ++It7HIIII++It7HIII+D111KK@..BRBRSSSSSs   "?E""
F,FF  J!!
K+KK-!N
N?N::N?S9 9
T(T##T(.6V00V47V4=%_# #
_0/_01d 
d1d,,d1f##
g-gg1i 
ii=Al 
ml??mrX  )r-   r  r  r  r   r  r  ri  )r  r  r
  r
  _stop_guardsr7  r6  s   `     @r6   rq  zGatewayRunner.stop0  s      t%A4HHL!! 	LNNN 	8&*D#%5D"(7D%?&/!!!!!!!Fl	% l	% l	% l	% l	% l	% l	%\}	T }	T }	T }	T }	T }	T~ "-jjll;;orB   c                 H   K   | j                                          d{V  dS )zWait for shutdown signal.N)rh  r  r"  s    r6   wait_for_shutdownzGatewayRunner.wait_for_shutdown3  s3      "'')))))))))))rB   c                   K   t          | j        dd          sdS 	 ddlm}m} n# t
          $ r Y dS w xY w |            pd}d}i }| j                                        D ]@\  }}|                     |          }|||||f<   | 	                    ||          }	|	|||	<   At          | di           
                                D ]6}
dD ]1}|
                    |          }t          |t                    r|||<   27 |d	
          D ]\  }}||k    r	 ||                     |||           d{V z  }.# t          $ r&}t                               d||           Y d}~Yd}~wt$          $ r  t
          $ r(}t                               d||d	           Y d}~d}~ww xY w	 ddlm} ddlm} |gt1          | j                                                  z   }|D ].}|r*|| j        vr!||k    r| j        n ||          | j        |<   / ||           n,# t
          $ r t                               dd	           Y nw xY w|S )u8  Bring up adapters for every non-active profile this gateway serves.

        Returns the number of secondary adapters that connected. No-op (returns
        0) unless ``gateway.multiplex_profiles`` is on.

        Each profile's adapters are created and connected under that profile's
        HERMES_HOME + secret scope (``_profile_runtime_scope``), stored in
        ``self._profile_adapters[profile]``, and given a message handler that
        stamps ``source.profile`` before delegating to the shared
        ``_handle_message`` — so the agent turn resolves that profile's config,
        skills, and credentials. Same-platform credential collisions (two
        profiles polling the same bot token) are detected and refused here, the
        only point that sees every profile's resolved credentials together.
        r  Fr   )profiles_to_server  r(  Nr  )r  r  T	multiplexzDSkipping secondary profile '%s' due to port-binding config error: %sz-Failed to start adapters for profile '%s': %sr   r  rN  r  )served_profilesz could not record served_profiles)r-   rX   r  r\  r  r.   r{  r  _adapter_credential_fingerprintr[  r_  rT   rR   ra  _start_one_profile_adaptersr|  r/   r   rv  r  r 	  r  r  rO  r  rQ  rg  r  r  r0   )r  r\  r  r  r  r
  r  _adfpr  
retry_info
claim_nameretry_claimprofile_namer}  rs  r  rO  servedr   s                       r6   r\  z/GatewayRunner._start_secondary_profile_adapters3  s      t{$8%@@ 	1	VVVVVVVVV 	 	 	11	 )(**7i	 %'---// 	1 	1JE355c::B~'-$!99%EEN)*0' "$(;R@@GGII 	2 	2JD 2 2
(nnZ88k511 2+1GK(2
 +<*;d*K*K*K 	 	&L,v%%4#C#C ,$ $       		 3   Z        
 (      C !d         	L;;;;;;444444Xt'='B'B'D'D E EEF
    D(;;;  6>> **)\$777 '-
 ! 88888 	L 	L 	LLL;dLKKKKK	L sC   % 
33 D44
F>EF6FF"A3H &H?>H?rg  r}  r   r
  c                 v  K   ddl m} t          |          5   |            }t          |          }ddd           n# 1 swxY w Y   |rt	          d| d| d          t          d |j                                        D                       }|r1d                    |          }t          d| d	| d
| d| d	          | j
                            |i           }	d}
|j                                        D ]\  }}|j        st          | j        dd          r|t          j        u r3	 t          |          5  |                     ||          }ddd           n# 1 swxY w Y   n;# t$          $ r.}t&                              d||j        |d           Y d}~d}~ww xY w|s"t&                              d||j                   |                     ||          }|A|                    |          }|*t&                              d|||j        |j                   *|                     ||          }|Q|                    |          }|:|dd         \  }}t&                              d|||j        |||j        |           |                     |||           	 t          |          5  |                     ||           d{V }ddd           n# 1 swxY w Y   |r:||	|<   ||||<   ||||<   |
dz  }
t&                              d|j        |           n=t&                              d|j        |           |                     ||           d{V  i# t$          $ rI}t&                              d|j        ||           |                     ||           d{V  Y d}~d}~ww xY w|
S )z>Create+connect one profile's adapters under its runtime scope.r   r  Nz	Profile 'z
' enables z. Enable GATEWAY_ALLOW_ALL_USERS or the platform allow-all flag for that profile, or change dm_policy/group_policy away from 'open'.c              3   l   K   | ]/\  }}|j         t          |j        |j                  &|j        V  0d S r;   )r  _platform_binds_portr   r  )r?   r_   r  s      r6   rA   z<GatewayRunner._start_one_profile_adapters.<locals>.<genexpr>n3  s^       (
 (
)/&(
 %X^_5JKK	(
N(
 (
 (
 (
 (
 (
rB   r   z#' enables port-binding platform(s) z, but gateway.multiplex_profiles is on. The default profile owns the single shared HTTP listener and serves every profile through the /p/z:/ URL prefix. Remove these platform entries from profile 'z='s config.yaml or configure them only on the default profile.r  Fz9[MULTIPLEX] Profile '%s': _create_adapter('%s') raised %sTr   zQ[MULTIPLEX] Profile '%s': skipping platform '%s' - adapter creation returned Noneu   Profile '%s' and '%s' both configure %s with the same credential — refusing to start the duplicate (one credential cannot be consumed twice). Give each profile its own %s credential.u   Profile '%s' and '%s' both configure %s sidecars on %s:%s — refusing to start the duplicate listener. Set platforms.%s.extra.sidecar_port to a distinct port for profile '%s'.rk   u   ✓ %s connected (profile: %s)u&   ✗ %s failed to connect (profile: %s)u   ✗ %s error (profile: %s): %s)r  r  r  rj  rv  r  r#  r  rD   r|  rQ  
setdefaultr  r-   rX   r  r  rN  r.   r/   r  r   r   rZ  rT   r[  _configure_profile_adapterr  r  r  )r  rg  r}  r
  r  profile_cfg	violationport_binding_platformsjoinedprofile_mapr  r_   r  r  rs  r  ownerr  bindportr  s                        r6   ra  z)GatewayRunner._start_one_profile_adapters]3  s      	766666#L11 	H 	H--//K:;GGI	H 	H 	H 	H 	H 	H 	H 	H 	H 	H 	H 	H 	H 	H 	H  	&L  I      "( (
 (
-8-B-H-H-J-J(
 (
 (
 "
 "
 " 		YY566F1BL B BB B +7B B 9E	B B B   ,77bII	)4)>)D)D)F)F [	G [	G%Ho"* 
 %95AA..+L99 N N"228_MMGN N N N N N N N N N N N N N N   O N!       g N  
   $==hPP+$455$LL1 |X^X^   !99(GLLN)N33$!/!4JD$LL, $  $   ++G\8LLLG+L99  $($N$N% %      G                
K,3K)'34@ 01%12>/NIKK @(.R^____NN#KX^]ijjj77JJJJJJJJJ G G G=x~|]^___33GXFFFFFFFFFFFFFFG s   >AA.E,=E E, E$	$E,'E$	(E,,
F$6$FF$%M#4KM#K!	!M#$K!	%A<M##
N6->N11N6c                    |                     |                     |                     |                    |                     ||                     |                    | j                   |                    | j                   t          |dd          }t          |          r || j
                   |                    | j                   |                    |                     ||                     | j        |_        dS )zDInstall the profile-scoped handlers shared by startup and reconnect.r  N)rg  )rP  _make_profile_message_handlerrR  !_make_profile_fatal_error_handlerrS  rf  rT  r	  r-   r  rg  rU  r;  rV  rW  r  )r  r  rg  r_   r  s        r6   ro  z(GatewayRunner._configure_profile_adapter3  s    	##D$F$F|$T$TUUU''22<JJ	
 	
 	
 	!!$"4555(()QRRR)?FFM"" 	7M$5666%%d&LMMM''))()NN	
 	
 	
 #'"6rB   c                   K   d}t          j                    }	 | j        r+d}	 ddlm} ddlm}  ||          }t          |          5   |            j        	                    |          }	|	|	j
        s	 ddd           | j        }
t          |
t                    r|
	                    |          }t          |t                    r|	                    |          nd}t          |t           j                  r||u rIt          |t                    r2|                    |d           |s|
                    |d           dS dS dS dS dS |                     ||	          }|t"                              d|j        |           	 ddd           | j        }
t          |
t                    r|
	                    |          }t          |t                    r|	                    |          nd}t          |t           j                  r||u rIt          |t                    r2|                    |d           |s|
                    |d           dS dS dS dS dS |                     |||           |                     ||d           d{V }ddd           n# 1 swxY w Y   |r| j        r	| j                            |i           }||vr|||<   |                     |           t"                              d|j        |           	 | j        }
t          |
t                    r|
	                    |          }t          |t                    r|	                    |          nd}t          |t           j                  r||u rIt          |t                    r2|                    |d           |s|
                    |d           dS dS dS dS dS |                     ||           d{V  	 | j        }
t          |
t                    r|
	                    |          }t          |t                    r|	                    |          nd}t          |t           j                  r||u rIt          |t                    r2|                    |d           |s|
                    |d           dS dS dS dS dS |r|                     ||           d{V  	 | j        }
t          |
t                    r|
	                    |          }t          |t                    r|	                    |          nd}t          |t           j                  r||u rIt          |t                    r2|                    |d           |s|
                    |d           dS dS dS dS dS |                     ||           d{V  t7          |d	d
          rt7          |dd          s	 | j        }
t          |
t                    r|
	                    |          }t          |t                    r|	                    |          nd}t          |t           j                  r||u rIt          |t                    r2|                    |d           |s|
                    |d           dS dS dS dS dS n~# t           j        $ r  ||                     ||           d{V   t:          $ rD ||                     ||           d{V  t"                              d|j        |d           Y nw xY w| j        s	 | j        }
t          |
t                    r|
	                    |          }t          |t                    r|	                    |          nd}t          |t           j                  r||u rIt          |t                    r2|                    |d           |s|
                    |d           dS dS dS dS dS |dz  }t?          |          }t"                              d|j        ||           t          j         |           d{V  | j        +| j        }
t          |
t                    r|
	                    |          }t          |t                    r|	                    |          nd}t          |t           j                  r||u rIt          |t                    r2|                    |d           |s|
                    |d           dS dS dS dS dS # | j        }
t          |
t                    r|
	                    |          }t          |t                    r|	                    |          nd}t          |t           j                  r||u rFt          |t                    r0|                    |d           |s|
                    |d           w w w w w xY w)zDReconnect a retryable secondary adapter under its own profile scope.r   Nget_profile_dirrj  zASecondary %s reconnect skipped: adapter unavailable (profile: %s)Tr  u    ✓ %s reconnected (profile: %s)rY  Frp  z3Secondary %s reconnect attempt failed (profile: %s)r   rk   z1Secondary %s reconnect retry in %ds (profile: %s))!r  r
  rf  r  r}  r  r  r  r#  rT   r  r  rR   rS   r  r$  rN  r/   r   r   ro  r  rQ  rn  r  r  r  r-   rf  r.   r0   r  r`  )r  rg  r_   r|  r
  r  r}  r  r}  profile_configr  r  r   r  rt  r  s                   r6    _run_secondary_profile_reconnectz.GatewayRunner._run_secondary_profile_reconnect3  s^      +--Z	<- O-ACCCCCCBBBBBB#2?<#@#@L/==  )<)<)>)>)H)L)LX)V)V)19O1"     T 4G'4(( <")++l";";8B?TX8Y8Yc**8444_c!$55 <9M9M!/488 <'++Hd;;;. <#KKd;;;;;< << < :N9M< <[ #'"6"6x"P"P"?"NN c ( ,  
 #     T 4G'4(( <")++l";";8B?TX8Y8Yc**8444_c!$55 <9M9M!/488 <'++Hd;;;. <#KKd;;;;;< << < :N9M< <K 77#\8   )-(J(J#XD )K ) ) # # # # # #              &  4= &*&<&G&GVX&Y&Y#;664;K1 BB7KKK"KK B ( ,  
 #Z 4G'4(( <")++l";";8B?TX8Y8Yc**8444_c!$55 <9M9M!/488 <'++Hd;;;. <#KKd;;;;;< << < :N9M< <c #;;GXNNNNNNNNNR 4G'4(( <")++l";";8B?TX8Y8Yc**8444_c!$55 <9M9M!/488 <'++Hd;;;. <#KKd;;;;;< << < :N9M< <W  ";;GXNNNNNNNNND 4G'4(( <")++l";";8B?TX8Y8Yc**8444_c!$55 <9M9M!/488 <'++Hd;;;. <#KKd;;;;;< << < :N9M< <O 77JJJJJJJJJ):EBB '1H$ O O 6 4G'4(( <")++l";";8B?TX8Y8Yc**8444_c!$55 <9M9M!/488 <'++Hd;;;. <#KKd;;;;;< << < :N9M< <C -   *";;GXNNNNNNNNN    *";;GXNNNNNNNNNLLM $!%	 !      }  4G'4(( <")++l";";8B?TX8Y8Yc**8444_c!$55 <9M9M!/488 <'++Hd;;;. <#KKd;;;;;< << < :N9M< <# A,X66GN 	   mG,,,,,,,,,_ - O-b 4G'4(( <")++l";";8B?TX8Y8Yc**8444_c!$55 <9M9M!/488 <'++Hd;;;. <#KKd;;;;;< << < :N9M< < 4G'4(( <")++l";";8B?TX8Y8Yc**8444_c!$55 <9M9M!/488 <'++Hd;;;. <#KKd;;;;<< :N<s   
d &Z& 
-J7Z& 
:JZ& 5JZ& JZ& J A)Z& Z& 7Z& >Z& %d &A8\!d  \!!
d 4Ad Cgc                    | j         r|j        sdS | j        }t          |t                    s	i }|| _        |                    |i           }||v rdS t          j        |                     ||          d| d|j	                   }|||<   t          | dd          }t          |t                    st                      }|| _        |                    |           |                    |j                   dS )zDSchedule one runner-owned reconnect without sharing primary secrets.Nzsecondary-reconnect:r  )r   r  )rf  rp  r  rR   rS   rn  r  ri  r  r   r-   rt   r  rv   r  r  )r  rg  r_   r  r  r  r   background_taskss           r6   %_schedule_secondary_profile_reconnectz3GatewayRunner._schedule_secondary_profile_reconnectW4  s    } 	G$A 	F0'4(( 	5G-4D*!,,\2>>&&F"11,IIGGGx~GG
 
 
 %)!"4)<dCC*C00 	6"uu%5D"T"""/788888rB   c                 .     dt           ddf fd}|S )zGRoute a secondary-profile fatal error to that profile's reconnect slot.r  r'   Nc                 F   K                        |            d {V  d S r;   )#_handle_profile_adapter_fatal_error)r  r_   rg  r  s    r6   _handlerzAGatewayRunner._make_profile_fatal_error_handler.<locals>._handlert4  s8      ::<SZ[[[[[[[[[[[rB   r  )r  rg  r_   r  s   ``` r6   rz  z/GatewayRunner._make_profile_fatal_error_handlerp4  sM    	\$7 	\D 	\ 	\ 	\ 	\ 	\ 	\ 	\ 	\ rB   c                   K   t          | di                               |          }t          |t                    r|                    |          |ur#t                              d|j        |           dS |                    |d           |                     ||           d{V  | j	        sdS | 
                    |||           t                              d|j        ||j        pd           dS )am  Remove a failed multiplexed adapter without touching the primary slot.

        Secondary adapters are owned by ``_profile_adapters`` rather than
        ``self.adapters``. The primary-only fatal handler intentionally ignores
        them; without this route, a fatal secondary Discord client stayed live
        forever after its liveness sampler stopped.
        rQ  zBIgnoring stale fatal error from secondary %s adapter (profile: %s)Nz6Fatal %s adapter error for multiplexed profile %s (%s)r  )r-   rT   rR   rS   r/   r0   r   r$  r  rf  r  r  r~  )r  rg  r_   r  rt  s        r6   r  z1GatewayRunner._handle_profile_adapter_fatal_errory4  s      d$7<<@@NN+t,, 	0I0IQX0X0XLLT  
 F$'''++GX>>>>>>>>>} 	F22<7SSSDN$1			
 	
 	
 	
 	
rB   c                 d     ddl m} 	  |          n# t          $ r dY nw xY w fd}|S )at  Return a message handler that stamps source.profile then delegates.

        Auth runs inside ``_handle_message`` *before* the agent-turn scope is
        installed. For secondary profiles under multiplex, wrap the whole
        handler in ``_profile_runtime_scope`` so allowlists/tokens from that
        profile's ``.env`` are visible to ``get_secret`` / authz.
        r   r|  Nc                 <  K   	 t          | dd           | j        j        s| j        _        n# t          $ r Y nw xY wBt	                    5                      |            d {V cd d d            S # 1 swxY w Y                       |            d {V S )Nr  )r-   r  r  r.   r  r  )r  r}  rg  r  s    r6   r  z=GatewayRunner._make_profile_message_handler.<locals>._handler4  s
     5(D11=elFZ=+7EL(   '+L99 = =!%!5!5e!<!<<<<<<<= = = = = = = = = = = = = = = =--e444444444s   )/ 
<<A88A<?A<)r  r}  r.   )r  rg  r}  r  r}  s   ``  @r6   ry  z+GatewayRunner._make_profile_message_handler4  s}     	877777	 *?<88LL 	  	  	 LLL	 		5 		5 		5 		5 		5 		5 		5 s    &&c                 L     t          t                                 fd}|S )z@Scope a multiplexed default-profile message from ingress onward.c                    K   t                    5                      |            d {V cd d d            S # 1 swxY w Y   d S r;   )r  r  )r  r}  r  s    r6   r  zEGatewayRunner._make_default_profile_message_handler.<locals>._handler4  s      '55 9 9!11%888888889 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9s   ;??)r   rG  )r  r  r}  s   ` @r6   %_make_default_profile_message_handlerz3GatewayRunner._make_default_profile_message_handler4  s<    O--..	9 	9 	9 	9 	9 	9 rB   c                 d    t          | j        dd          r|                                 S | j        S )z:Return the correctly scoped handler for a primary adapter.r  F)r-   rX   r  r  r"  s    r6   rQ  z&GatewayRunner._primary_message_handler4  s5    4; 4e<< 	@==???##rB   c                 F    t                               |          }|dS | |fS )z?Return the exclusive credential resource claimed by an adapter.N)r  r`  )r_   r  fingerprints      r6   rZ  z'GatewayRunner._adapter_credential_claim4  s-    
 $CCGLL4+&&rB   c                 p   t          | dd          dk    rdS t          |dd          }t          |dd          }t          |t                    r|                                sdS 	 t	          |          }n# t
          t          f$ r Y dS w xY wdd|                                                                |fS )a  Return the exclusive listener resource claimed by an adapter.

        Photon sidecars are per-profile processes. Even when two profiles use
        different project credentials, their sidecars cannot share a bind and
        port. Represent that endpoint as a claim so multiplex startup rejects
        the later adapter before either ``connect()`` or ``disconnect()`` can
        disturb the first profile.
        r   Nphoton_sidecar_bind_sidecar_portlistener)r-   rR   rU   rV   rF  rU  rH  rW   )r_   r  rv  rw  s       r6   r[  z%GatewayRunner._adapter_listener_claim4  s     8Wd++x774w66w66$$$ 	DJJLL 	4	t99DD:& 	 	 	44	Hdjjll&8&8&:&:DAAs   &A6 6B
Bc                    d}dD ]R}t          | |d          }t          |t                    r*|                                r|                                } nS|sht          | dd          }|UdD ]R}t          ||d          }t          |t                    r*|                                r|                                } nS|s_t          | dd          }t          |dd          }t          |t                    r(|                                r|                                }|sdS ddl}|                    d|z                       d                                                    dd	         S )
as  Return a stable, log-safe fingerprint of an adapter's credential.

        Used only to detect two profiles claiming the same platform credential.
        Returns a salted hash (never the credential itself) of the adapter's
        primary credential, or None when no credential is discoverable (in
        which case we don't attempt conflict detection for it).
        N)r  	bot_token_token	api_token
_bot_token_project_secretrX   )r  r  r  r   zhermes-mux:r     )r-   rR   rU   rV   hashlibsha256encode	hexdigest)r  r  attrvalrk  rX   r  s          r6   r`  z-GatewayRunner._adapter_credential_fingerprint4  s    

 	 	D '4..C#s## 		 		  	'8T22C2  D!#tT22C!#s++ 		  #		 	$Wh55F&'400C#s## $		 $		 	4~~}u4<<WEEFFPPRRSVTVSVWWrB   c                    t          |d          rnt          |j        t                    rT|j                            d| j        j                   |j                            dt          | j        dd                     	 ddlm	} |
                    |j                  rH|                    |j        |          }|	| |_        |S t                              d|j                   dS n8# t           $ r+}t                              d	|j        |           Y d}~nd}~ww xY w|t$          j        k    r9dd
lm}m}  |            st                              d           dS  ||          S |t$          j        k    rbddlm}m}	m}
  |	            st                              d           dS  |
|          st                              d           dS  ||          S |t$          j        k    r9ddlm}m }  |            st                              d           dS  ||          S |t$          j!        k    rBddl"m#}m$}  |            st                              d           dS  ||          }| |_        |S |t$          j%        k    rBddl&m'}m(}  |            st                              d           dS  ||          }| |_        |S |t$          j)        k    r9ddl*m+}m,}  |            st                              d           dS  ||          S |t$          j-        k    r9ddl.m/}m0}  |            st                              d           dS  ||          S |t$          j1        k    r9ddl2m3}m4}  |            st                              d           dS  ||          S |t$          j5        k    r1ddl6m7}m8} |st                              d           dS  ||          S dS )zCreate the appropriate adapter for a platform.

        Checks the platform_registry first (plugin adapters), then falls
        through to the built-in if/elif chain for core platforms.
        r  r  r  Fr   r  NzWPlatform '%s' is registered but adapter creation failed (check dependencies and config)z,Platform registry lookup for '%s' failed: %s)WhatsAppCloudAdapter!check_whatsapp_cloud_requirementsu@   WhatsApp Cloud: aiohttp/httpx missing — reinstall hermes-agent)SignalAdaptercheck_signal_requirementsvalidate_signal_configz$Signal: runtime requirements not metz8Signal: SIGNAL_HTTP_URL or SIGNAL_ACCOUNT not configured)WeixinAdaptercheck_weixin_requirementsz*Weixin: aiohttp/cryptography not installed)APIServerAdaptercheck_api_server_requirementsz!API Server: aiohttp not installed)WebhookAdaptercheck_webhook_requirementszWebhook: aiohttp not installed)MSGraphWebhookAdapter"check_msgraph_webhook_requirementsz&MSGraph webhook: aiohttp not installed)BlueBubblesAdaptercheck_bluebubbles_requirementsz`BlueBubbles: aiohttp/httpx missing or BLUEBUBBLES_SERVER_URL/BLUEBUBBLES_PASSWORD not configured)	QQAdaptercheck_qq_requirementszIQQBot: aiohttp/httpx missing or QQ_APP_ID/QQ_CLIENT_SECRET not configured)YuanbaoAdapterWEBSOCKETS_AVAILABLEz>Yuanbao: websockets not installed. Run: pip install websockets)9r   rR   r  rS   rn  rX   r  r-   rF  r  is_registeredr   create_adaptergateway_runnerr/   r  r.   r0   r  WHATSAPP_CLOUD gateway.platforms.whatsapp_cloudr  r  r   SIGNALgateway.platforms.signalr  r  r  WEIXINgateway.platforms.weixinr  r  r  gateway.platforms.api_serverr  r  r  gateway.platforms.webhookr  r  r  !gateway.platforms.msgraph_webhookr  r  BLUEBUBBLESgateway.platforms.bluebubblesr  r  QQBOTgateway.platforms.qqbotr  r  YUANBAOgateway.platforms.yuanbaor  r  )r  r_   rX   r  r  rs  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  s                            r6   rN  zGatewayRunner._create_adapter5  sD    67## 	
6<(F(F 	L##)3   L##*%?GG  	\CCCCCC ..x~>> +::8>6RR& .2G*"N 6N  
 t'(  	\ 	\ 	\LLGYZ[[[[[[[[	\ x...        5466 V   t''///((         
 -,.. EFFFt))&11 YZZZt =(((((YYYYYYYY,,.. KLLLt =(((,,,dddddddd0022 BCCCt&&v..G%)G"N)))\\\\\\\\--// ?@@@t$nV,,G%)G"N111        6577 GHHHt((000---hhhhhhhh1133    B  C  C  Ct%%f---''PPPPPPPP((** jkkkt9V$$$)))VVVVVVVV' _```t!>&)))ts    AC)  C) )
D3!DDc           	           	 	 ddt           dt          t                    dt          t                    dt          f fd}|S )u@  Build a platform-bound auth callback for adapter use.

        Adapters that fetch external context (e.g. Slack
        ``conversations.replies``) call this through
        ``BasePlatformAdapter._is_sender_authorized`` to mark non-allowlisted
        senders as unverified in LLM context, mitigating indirect prompt
        injection from third parties in shared threads/channels.

        The returned callback delegates to :meth:`_is_user_authorized` so the
        full auth chain — platform allowlists, group allowlists, pairing
        store, allow-all flags — stays the single source of truth.

        ``profile_name`` binds the callback to the secondary adapter's own
        multiplex profile, so its ``SessionSource`` resolves that profile's
        secret scope instead of falling back to the active profile.
        Nr  r}  r  r'   c                 f    | sdS t          |pd|pd|           }                    |          S )NFr   r   )r_   r  r}  r  r  )r%  r	  )r  r}  r  r  r_   rg  r  s       r6   checkz5GatewayRunner._make_adapter_auth_check.<locals>.check5  sT    
  u"!2#.w$  F ++F333rB   r  )rU   r   r   )r  r_   rg  r  s   ``` r6   rW  z&GatewayRunner._make_adapter_auth_check5  sm    . (,%)	4 	4	4}	4 c]	4 		4 	4 	4 	4 	4 	4 	4 	4 rB   r  c           	      $  K   |                      |          }|sdS t          | dd          }|rjt          |dd          t          j        k    rKt	          |t          |dd                    r,t
                              dt          |dd                     dS d}|r*t          |d          r|                    |j	                  }| 
                    |          }|dk    rt          |d	d          rz	 |                    |j        |j        ||
           d{V }t          |dd          rdS n<# t          $ r/ t
                              dt          |dd          d           Y nw xY w|                    |j        ||
           d{V  dS )zIDeliver a setup/operational notice using platform-specific privacy rules.NrX   r_   r  z@Skipping Slack platform notice for configured ignored channel %spublicget_notice_deliveryprivater  r  r  Fz7[%s] send_private_notice failed, falling back to publicr  Tr   )r	  r-   r  r  r  r/   r  r   r  r_   r	  send_private_noticer  r  r.   r0   r  )r  r  r  r  rX   notice_deliveryr   r  s           r6   r  z&GatewayRunner._deliver_platform_notice5  s     **622 	Fx..		
D11X^CC)&'&)T2R2RSS D KKR	400   F" 	Jgf&;<< 	J$88IIO33F;;i''GFIt,L,L'&::NN%	  ;           69e44 F   MFJ44!       ll6>7XlFFFFFFFFFFFs   4:D1 16E*)E*r1  pinned_session_idc                   K   t          t          | j                  }|t                              d           dS d}	 |                    |           d{V }n-# t          $ r  t                              d|d           Y nw xY w|t                              d|           dS |}d}|                    d          r|                    d	          d
k    r1t                              d||                    d	                     dS d}	 |	                    |           d{V }n/# t          $ r" t                              d|d           d}Y nw xY w|r||k    rt                              d|           dS 	 |                    |           d{V }n# t          $ r d}Y nw xY w||                    d          r"t                              d||dnd           dS |j
        ||hv }|s	 |                    |j
                   d{V }	|	N|	                    d          r9|	                    d	          d
k    r |	                    |j
                   d{V nd}
n# t          $ r d}
Y nw xY w|
|k    }|s$t                              d|||j
                   dS ||j
        k    r|S |j
        }|r(| j                            |j        ||           d{V }n&| j                            |j        |           d{V }|#t                              d|j        |           dS t                              d|||j                   |S )a  Resolve an async completion to its verified owning gateway session.

        A compression rotation ends the physical parent row while continuing
        the same logical conversation in a child.  Follow that lineage, but
        never let a late completion override an unrelated /new or restored
        route.  Unknown ownership remains fail-closed; the result is still
        available in the delegation records.
        Nz]Async-delegation completion has no session database; dropping injection (#55578 fail-closed).z,Async-delegation parent lookup failed for %sTr   zeAsync-delegation completion has unknown spawning session %s; dropping injection (#55578 fail-closed).Fended_at
end_reasonrK   zAsync-delegation completion pinned to ended session %s (end_reason=%r); dropping injection instead of resurrecting it (#55578 fail-closed).z5Async-delegation compression-tip lookup failed for %szgAsync-delegation completion pinned to compressed session %s without a continuation; dropping injection.zGAsync-delegation compression continuation %s is %s; dropping injection.r  endedzoAsync-delegation completion for compression lineage %s -> %s does not own current route %s; dropping injection.zcAsync-delegation completion could not bind routing key %s to owning session %s; dropping injection.z\Pinned async-delegation completion to owning session %s (was %s) for routing key %s (#57498))r   r   r)   r/   r   rh  r.   r0   rT   get_compression_tipr%   r	  advance_compression_sessionr  r  r  )r  r1  r  r3   
pinned_rowtarget_session_idfollows_compressiontip_rowroute_owns_lineage	route_row	route_tipprior_session_idr  s                r6   !_resolve_async_delegation_sessionz/GatewayRunner._resolve_async_delegation_session5  s      #t/00
NN;   4
	)556GHHHHHHHHJJ 	 	 	LL>!      	 NN;!  
 4-#>>*%% J	~~l++}<<, &NN<00   t"&
)*4*H*H%+ + % % % % % %!!  ) ) )K%!    
 %)!!!) % (9=N(N(NB%  
 t * 6 67H I IIIIIII   '++j"9"9*%!(IIg	   t!.!9!!> " & D
%&0&<&<]=U&V&V V V V V V VI %0%MM*55 1%MM,77=HH )<<]=UVVVVVVVVV " I ! % % % $III%%.2C%C"% I%%!,   t 888  (3 
	!5QQ) !       HH "5DD)!       H NN9)!	   43%	
 	
 	
 sH   A 'BBD) ))EE>F F)(F)3A2I& &I54I5u=   Agent is running — wait or /stop first, then switch models.u>   Agent is running — wait or /stop first, then change runtime.u8   Agent is running — wait or /stop first, then run /moa.)r  codex-runtimemoa_BUSY_REJECT_TEXT	quick_keyc                   K   |j         }t          |dd          }t          |dd          }|rs| j        | j        | j        | j        | j        | j        | j        d	                    |          }| ||||           d{V S | j
        	                    |          }	|	|	S |dv ri d| j        d| j        d	| j        d
| j        d| j        d| j        d| j        d| j        d| j        d| j        d| j        d| j        d| j        d| j        d| j        d| j        d| j        	                    |          }
|
 |
|           d{V S t8                              d||           d| dS )u`  Dispatch a recognized slash command while an agent is running.

        Resolution order:
          1. ``busy_handler`` — special mid-run variant (e.g. /goal's
             control-verb whitelist, /queue's FIFO enqueue, /model's
             custom reject text).
          2. ``busy_policy == "dispatch"`` — the command's normal handler.
          3. Catch-all busy-reject text. Rejecting is required rather than
             falling through to interrupt + discard: commands like /model,
             /reasoning, /voice, /insights, /title, /resume, /retry,
             /undo, /compress, /usage, /reload-mcp, /sethome, /reset (all
             registered as Discord slash commands) would interrupt the
             agent AND get silently discarded by the slash-command safety
             net, producing a zero-char response. See #5057, #6252, #10370.
        busy_policyr	  busy_handlerN)rr  rq  r  rd  r  egressgoal)dispatchinterrupt_then_dispatchstatusr   r  r	  r	  agents
backgroundkanbansubgoalyolor  footerhelpcommandsr  r  versionuM   busy_policy=%s for /%s has no mid-run handler — falling back to busy-rejectu   ⏳ Agent is running — `/zE` can't run mid-turn. Wait for the current response or `/stop` first.)r   r-   _busy_start_command_busy_stop_command_busy_new_command_busy_queue_command_busy_steer_command_busy_egress_command_busy_goal_commandrT   r  _handle_status_command_handle_context_command_handle_restart_commandr	  r	  _handle_agents_command_handle_background_command_handle_kanban_command_handle_subgoal_command_handle_yolo_command_handle_verbose_command_handle_footer_command_handle_help_command_handle_commands_command_handle_profile_command_handle_update_command_handle_version_commandr/   r   )r  r  cmd_defr  r  r   policyhandler_keyspecialreject_textplains              r6   _dispatch_busy_slash_commandz*GatewayRunner._dispatch_busy_slash_command6  sV     $ |-::g~t<< 	#1/-113/  c+  "$WUIv>>>>>>>>>044[AAK&""<<<$547 47 47	
 1 $5 d= $5 47 1 47 $5 1 D9 47  $5!" 47#$ c$ii% &  "U5\\)))))))NN./5t  I$ I I I	
rB   c                 @   K   t                               d|           dS )Nz3Ignoring /start platform ping for active session %sr   r/   r  r  r  r  r  s       r6   r  z!GatewayRunner._busy_start_command6  s"       	I9UUUrrB   c                 &   K   ddl m}  |            S )Nr   format_status_text)hermes_cli.proxy_clir  )r  r  r  r  r  s        r6   r  z"GatewayRunner._busy_egress_command6  s'      ;;;;;;!!###rB   c                    K   |                      ||t          d           d {V  t                              d|           t	          t          d                    S )Nstop_commandinterrupt_reasoninvalidation_reasonu@   STOP for session %s — agent interrupted, session lock releasedzgateway.stop.stopped)_interrupt_and_clear_session_INTERRUPT_REASON_STOPr/   r  r9  r   r  s       r6   r  z GatewayRunner._busy_stop_command6  s~       //3 .	 0 
 
 	
 	
 	
 	
 	
 	
 	
 	VXabbba 677888rB   c                    K   |                      ||t          d           d {V  |                     |           d {V S )Nnew_commandr  )r   _INTERRUPT_REASON_RESET_handle_reset_commandr  s       r6   r  zGatewayRunner._busy_new_command6  sw       //4 -	 0 
 
 	
 	
 	
 	
 	
 	
 	
 //666666666rB   c                    K   |                                                                 }t          t          |dd                     }|s|sdS |                     |          }|rt          di d|d|r|j        nt          j        d|j	        d|j
        d|j        dt          t          |dg           pg           dt          t          |dg           pg           d	|j        d
|j        d|j        d|j        d|j        d|j        d|j        d|j        d|j        d|j        }|                     |||           |                     ||                     |                    }|dk    rdS d| dS )Nr  Usage: /queue <prompt>r   r  r  raw_messager4  r  r	  reply_to_textreply_to_author_idreply_to_author_namereply_to_is_own_message
auto_skillr  channel_contextr	  rE  r  rk   zQueued for the next turn.zQueued for the next turn. (z queued)r,  )get_command_argsrV   r   r-   r	  r:  r  r;  r	  r  r(  r4  r  r	  r)  r*  r+  r,  r-  r  r.  r	  rE  r  r  )	r  r  r  r  queued_text	has_mediar  r  r   s	            r6   r  z!GatewayRunner._busy_queue_command7  s     
 ,,..4466
 d;;<<	 	,9 	,++**622 	A'    [3<RU//+BR || "--	
 !++  |R @ @ FBGGG !r!B!B!HbIII %*$=$= $11 $)#;#; &+%?%? ).(E(E !++  %33 !& 5 5  !"  //#L& y,@@@!!)T5M5Mf5U5U!VVA::..<U<<<<rB   c                 \  K   |                                                                 }|sdS |                     |          }|r|j        j        nd }|t
          u rc|                     |          }|rJt          |t          j	        |j
        |j        |j        |j                  }|                     |||           dS |rt          |d          r{	 |                    |          }	n8# t"          $ r+}
t$                              d||
           d|
 cY d }
~
S d }
~
ww xY w|	r(|d d         t)          |          dk    rdnd	z   }d
| dS dS |                     |          }|rJt          |t          j	        |j
        |j        |j        |j                  }|                     |||           dS )NzUsage: /steer <prompt>)r   r  r  r4  r  r.  u9   Agent still starting — /steer queued for the next turn.r  zSteer failed for session %s: %su   ⚠️ Steer failed: r  r   r   u8   ⏩ Steer queued — arrives after the next tool call: 'r  zSteer rejected (empty payload).u4   No active agent — /steer queued for the next turn.)r/  rV   r  r  r   ri  r	  r:  r;  r	  r  r4  r  r.  r  r   r  r.   r/   r   r   )r  r  r  r  r	  _steer_statero	  r  r  acceptedr5   r  s               r6   r  z!GatewayRunner._busy_steer_command:7  s      ++--3355
 	,++//	::3?I)//T333..v66G 	E+#!,!1 <$/#(#7$)$9      ""9lGDDDNN 		5W]G<< 		55(..z:: 5 5 5@)SQQQ4s444444445  ]$SbS/c*oo6J6JUUPRS\RY\\\\44**622 		A'(-| +$3 % 5  L y,@@@EEs   C' '
D1 DDDc                   K   |                                 pd                                                                }|r|                    d d          d         nd}| p	|dv p|dk    }|r|                     |           d {V S dS )Nr   rk   r   >   r  rq  r  pauseresumer  unwaitr  ui   Agent is running — use /goal status / pause / clear / wait mid-run, or /stop before setting a new goal.)r/  rV   rW   rC   _handle_goal_command)r  r  r  r  	_goal_arg
_goal_verb_is_controls          r6   r  z GatewayRunner._busy_goal_commandk7  s       ++--3::<<BBDD	4=EY__T1--a002
 M $\\$V# 	
  	:225999999999zzrB   c                 V   K   j         }	 ddlm}  |             n,# t          $ r t                              dd           Y nw xY wt          t          dd                    }|syt          |dd	          t          j	        k    rZt          t           d
d	          t          |dd	                    r,t                              dt          |dd	                     d	S t           dd          r*|s(t          dd          s                                d	S |s                                  |s4	 ddlm}  |d t           dd	                    }n4# t          $ r'}t                              d|           g }Y d	}~nd	}~ww xY w|D ]}t#          |t$                    s|                    d          }	|	dk    rMt                              d|                    d          |j        r|j        j        nd|j        pd            d	S |	dk    rI|                    d          }
t#          |
t.                    rt1          j        |
          j         } n	|	dk    r n|rn|j        >                     |          s't                              d|j        j                   d	S nՉ                     |          st                              d|j        |j        |j        j                   |j        dk    r                     |j        |j                   d!k    rZ|j        r|j        j        nd}                      |          }|t          !                    d"|           d	S |"                    ||j                  rd	S |#                    ||j        |j        pd#          }|r| $                    |          }|rdt          |d$d	          }t#          |t.                    r|r|d%k    rd&| d'nd#}|%                    |j        d(| d)| d*| d'| d+	           d	{V  nS $                    |          }|r!|%                    |j        d,           d	{V  |&                    ||j                   d	S  '                    |          } (                    |          }|>|j)        j*        r1j+        pd#,                                }-                                }|d-v rd.}nX|d/v rd0}nQd	}|rF	 dd1l.m/} n# t          $ r d	}Y nw xY w|*	  ||          }|r|j0        nd	}n# t          $ r d	}Y nw xY w|rd#}n|}|rtb          d2z  }tb          d3z  }	 |2                    d4          }|3                    |d56           |                    |           |4                    d7           n7# tj          $ r*}t                              d8|           d9| cY d	}~S d	}~ww xY wd|j)        _*        tm          |          d:k    r|n|d	d:         d;z   }d<| d=S |rtb          d2z  }tb          d3z  }	 |2                    d4          }|3                    d#d56           |                    |           |4                    d7           t                              d>||           n2# tj          $ r%}t                              d?|           Y d	}~nd	}~ww xY wd|j)        _*        d	}	 dd@l7m8} |9                    |dA          }n# t          $ r d	}Y nw xY w||t           :                                        }  ;                               d	{V }!| r%|!s#t                              dB||j<                   d#S |!r|!=                    dC          s|>                    ||!          }"|"rt                              dD||j<                    $                    |          }#|#rH	 |#?                    |j                   n,# t          $ r t                              dEd           Y nw xY wd#S ddFl7m@}$ |$A                    |          }%d}&	 ddGlBmC}'  |'|          }&n# t          $ r d}&Y nw xY w|%r|&s̉j+        pd#,                                }(|(D                    dH          E                                })-                                }*d	}+|*dIv rdJ}+n"|*dKv rdL}+n|*dMv rdN}+n|)dOv rdJ}+n|)dPv rdL}+n|)dQv rdN}+|+4|$F                    ||%                    dR          |+           d	{V }"|"pd#S |$G                    |           t          dSdT          }, (                    |          }-|-r|-jI        jJ        nd}.|-y|-jI        jK        l|.rit          jL                    |.z
  }/|-jI        jK        }0t          dU          }1d#}2|0rt          |0dV          r	 |0O                                }3|3                    dWt          dU                    }1dX|3                    dYd           dZ|1d[d\|3                    d]d           dC|3                    d^d           }2n# t          $ r Y nw xY w|,dk    rt          |,d_z  d`          nt          dU          }4|0t          uo|,dk    r|1|,k    p|/|4k    }5|5rKt                              da||/|1|,|2            R                    |dbc            S                    |            T                    |          rdd1l.m/}6 -                                }7|7r |6|7          nd	}8|8r&|8j0        ddk    r U                               d	{V S |8r&|8j0        dek    r V                               d	{V S |7r!|8 W                    ||8j0                  }9|9|9S |8r X                    |8||           d	{V S jY        t          j[        k    rJt                              df|            $                    |          }|rt          |j]        |           d	S t          t          j_        dgdh                    }: (                    |          };|;r|;jI        jJ        nd}<|j        t          j`        k    rjY        t          ja        k    r|:dk    r|<rt          jL                    |<z
  |:k    rt                              dit          jL                    |<z
  |            $                    |          }|r; jb        djk    r c                    ||           nt          |j]        |dk           d	S  (                    |          }=|=r|=jI        jK        nd	}>|>t          u r-                                dlk    r? S                    |           t                              dm|           t          dn          S  $                    |          }|rt          |j]        |dk           d	S  je        rn f                                r g                    |            f                                rdo h                                 dpndq h                                 drS  jb        djk    r3t                              ds|            g                    |           d	S  jb        dtk    rj+        pd#,                                }?d}@jY        t          ja        k    ryji        srjj        sk|?rit          |>dt          rY	 t          |>k                    |?                    }@n5# t          $ r(}At                              du||A           d}@Y d	}A~And	}A~Aww xY w|@rt                              dv|           d	S t                              dw|            g                    |           d	S  l                    |>          r3t                              dx|            g                    |           d	S  m                    |           d	{V r3t                              dy|            g                    |           d	S jY        t          ja        k    rji        sjj        st          |>dzd          du rt          |>d{          r	 |>n                    j+        pd#,                                          rt                              d||           d	S n3# t          $ r&}At                              d}||A           Y d	}A~And	}A~Aww xY wt                              d~|           j+        }Bt          dd	          pg }C :                              r> o                     $                    |          |j+        pd#d           d	{V \  }B}Dn|Bs|Crt                    }B|>q                    |B           d	S -                                }Eddl.mr}Fms}Gm/}H |Er |H|E          nd	}|r|j0        n|E}I|Ere|bt#           jt        t$                    r jt                            di           pi }Jnt           jt        di           pi }Jt#          |Jt$                    r|E|Jv r|J|E         }K|K                    d          dk    r|K                    d          pd#,                                }L|Lr|L=                    dC          r|LndC|L }L|LD                    dC          }Mu                                ,                                }N|L d'|N ,                                _+        |Mr|Mv                                d         n|M}E|Er |H|E          nd	}|r|j0        n|E}I|Er'|Ir% |G|I          r W                    ||I          }9|9|9S |Erg |G|I          r[u                                ,                                }O|j        r|j        j        nd#|j        |I|E|O|Od}P	  jw        x                    d|I |P           d	{V }Qn5# t          $ r(}Rt                              d|I|R           g }QY d	}R~Rnd	}R~Rww xY w|QD ]}St#          |St$                    st/          |S                    dd#                    ,                                E                                }T|Tr|Tdk    ri|Tdk    r8|S                    d          }Ut#          |Ut.                    r|Ur|Uc S d|E dc S |Tdk    r2|S                    d          }Ut#          |Ut.                    r|Ur|Und	c S |Tdk    rt/          |S                    dd#                    ,                                D                    dC          }V|Vs1t/          |S                    dd#                    ,                                }WdC|V d'|W ,                                _+        -                                }E|Er |H|E          nd	}|r|j0        n|E}I n|Idk    rZt          jz         j{        |           d	{V r |                                S  fd}X }                    ddd|X           d	{V S |Idk    r ~                               d	{V S |Idk    r                                d	{V S |Idk    rt                              d|           d#S |Idk    r                                d	{V S |Id$k    r                                d	{V S |Idk    r                                d	{V S |Iddk    r U                               d	{V S |Idk    rddlm}Y  |Y            S |Idek    r V                               d	{V S |Idk    r                                d	{V S |Idk    r                                d	{V S |Idk    r                                d	{V S |Idlk    r                                d	{V S |Idk    r                                d	{V S |Idk    r                                d	{V S |Idk    r                                d	{V S |Idk    rddlm}Z u                                ,                                }[|[rdnd}\	  $                    |          }|rE                     |          }]|%                    t/          |j                  |\|]           d	{V  n,# t          $ r t                              dd           Y nw xY w	  |Z|[          _+        n# t          $ r Y dS w xY w|Idk    rddlm}^ u                                ,                                }_	  |^|_          }`n# t          $ r Y dS w xY wd|`v rdnd}\	  $                    |          }|rE                     |          }]|%                    t/          |j                  |\|]           d	{V  n,# t          $ r t                              dd           Y nw xY w|`_+        |Idk    r                                d	{V S |Idk    r                                d	{V S |Idk    r                                d	{V S |Idk    r                                d	{V S |Idk    r                                d	{V S |Idk    r                                d	{V S |Idk    r                                d	{V S |Idk    r                                d	{V S |Idk    r                                d	{V S |Idk    r                                d	{V S |Idk    r                                d	{V }at          |add	          }b|brt          |add#          pd#}\|\r	  $                    |          }|rE                     |          }]|%                    t/          |j                  |\|]           d	{V  n,# t          $ r t                              dd           Y nw xY w	 |b_+        n6# t          $ r t          |add#          pd	cY S w xY wt          |add#          pd	S |Idk    r                                d	{V S |Idk    r fd}cd}du                                ,                                }e|erS	 t          dÐt;          |ev                                d                             }dn# t<          t>          f$ r d}dY nw xY w|ddk    rdnd|d dƝ}f }                    dd|f|c           d	{V S |Idk    r                                d	{V S |Idk    r                                d	{V S |Idk    r                                d	{V S |Idk    r                                d	{V S |Idk    r                                d	{V S |Idk    r                                d	{V S |Idk    r                                d	{V S |Idk    r                                d	{V S |Idk    r                                d	{V S |Idk    r                                d	{V S |Idk    r                                d	{V S |Idk    r                                d	{V S |Idk    r                                d	{V S |Idk    r                                d	{V S |Idk    r                                d	{V S |Idk    r                                d	{V S |Idk    r                                d	{V S |Idk    r                                d	{V S |Idk    r                                d	{V S |Idk    r                                d	{V S |Idjk    rCu                                ,                                }g|gsdS 	 |g_+        n# t          $ r Y nw xY w|Idtk    rCu                                ,                                }h|hsdS 	 |h_+        n# t          $ r Y nw xY w|Idk    r                                d	{V S |Idk    rddlm}im}j ddlm}k u                                ,                                }l|ls
 |i            S 	  |k            }m |jt#          |mt$                    r|m                    dަ          ni           }nn# t          $ r  |ji           }nY nw xY w|nd         }o	 |l_+                             |          }p|pj        j        _        d|odddd|pj        _                             |           d_        n# t          $ r Y dS w xY w|Idk    r                                d	{V S |Idk    r                                d	{V S  je        rdq h                                 dS |Ert#           jt        t$                    r jt                            di           pi }Jnt           jt        di           pi }Jt#          |Jt$                    si }J|E|Jv r* W                    ||E          }9|9|9S |J|E         }K|K                    d          dk    r
|K                    dd#          }q|qr	 ddlm}r  |r            }st          j        |qt          j        j        t          j        j        |s           d	{V }tt          j        |t                                d           d	{V \  }u}v|up|v                                ,                                }w|wrddlm}x  |x|w          }w|wr|wndS # t          j        $ r Y dS t          $ r}d| cY d	}~S d	}~ww xY wd|E dS |K                    d          dk    r|K                    d          pd#,                                }L|Lr|L=                    dC          r|LndC|L }L|LD                    dC          }Mu                                ,                                }N|L d'|N ,                                _+        |Mr|Mv                                d         n|M}End|E dS d|E dS |Er	 ddlm}y  |y|E                    dd                    }z|zr`u                                ,                                }N |z|N          }{t          j        |{          r|{ d	{V }{|{rt/          |{          nd	S n2# t          $ r%}t                              d|           Y d	}~nd	}~ww xY w|Erd}|	 ddlm}}m}~  |~|E          }|u                                ,                                }|j        r|j        j        nd	} |}||||          }|r@|\  }}}|_+        d}||r/t                              d|d                    |                     n3# t          $ r&}At                              d |A           Y d	}A~And	}A~Aww xY w|Ert                                          dd          s	 ddlm}m}m}  |             ||E          }|=|                             dd#          }|j        r|j        j        nd	}|r$|r"ddlm} | ||          v rd| d| dS u                                ,                                }	 dd	lm}m}  ||          \  }}n# t          $ r	 d	}g |}}Y nw xY w|rG|rEddlm}  ||          fd
|D             }|rdd                    |           d| dS |r,|* ||g|||          }|r|\  }}}|_+        nd|E dS  ||||          }|r|_+        net          |E          }|r|S |E                    dd          |Fvr9t                              d|E|j        r|j        j        nd           d|E dS n3# t          $ r&}t                              d|           Y d	}~nd	}~ww xY w|sKt          jz         j{        |           d	{V r+                     |          r                                 S d	S  j        r"|s t                              d|           	 dS                      ||          \  }}|t                              d|           |S                      |          }|||jI        _        t          |jI        _K        t          jL                    |jI        _J                                                               |          }	                      |||           d	{V }	 d#}t#          |t$                    r&t/          |                    d          pd#          }nt#          |t.                    r|}|,                                rU	  j                            |           d	{V }n# t          $ r d	}Y nw xY w|                     |||           d	{V  n3# t          $ r&}t                              d|           Y d	}~nd	}~ww xY w|                     |                                |            S                    |                                ||           S #                      |                                |            S                    |                                ||           w xY w(  a  
        Handle an incoming message from any platform.
        
        This is the core message processing pipeline:
        1. Check user authorization
        2. Check for commands (/new, /reset, etc.)
        3. Check for running agent and interrupt if needed
        4. Get or create session
        5. Build context for agent
        6. Run agent conversation
        7. Return response
        r   )reset_session_varsz*reset_session_vars failed at handler entryTr   r	  Fr_   NrX   r  z9Dropping Slack message from configured ignored channel %sr  r
  )invoke_hookpre_gateway_dispatchrf  )r  r1   rf  z*pre_gateway_dispatch invocation failed: %sr
  skipz8pre_gateway_dispatch skip: reason=%s platform=%s chat=%srj  r  rewriter   r   allowz(Ignoring message with no user_id from %sz Unauthorized user: %s (%s) on %sr~  r  pairz1Cannot offer pairing code on %s: no pairing storer   r  r(  z-p rn  z;Hi~ I don't recognize you yet!

Here's your pairing code: `z%`

Ask the bot owner to run:
`hermes zpairing approve r   z<Too many pairing requests right now~ Please try again later!>   rO   r	  r	  >   r	  r	  r	  resolve_command.update_response.update_prompt.jsonz.tmpr  rJ  rB  z#Failed to write update response: %su/   ✗ Failed to send response to update process:       …u
   ✓ Sent `z` to the update process.ziRecognized /%s during pending update prompt for %s; cancelled prompt with default and dispatching commandz=Failed to write cancel response for pending update prompt: %sr  )include_choice_promptszfGateway retained pending clarify after voice transcription produced no usable text (session=%s, id=%s)r;  z=Gateway intercepted clarify text response (session=%s, id=%s)z.Failed to resume typing after clarify responseslash_confirmr	  z!/>   r	  rO   r	  r	  once>   r	  rememberr	  >   r	  r	  r  	nevermindr  >   approve oncerN  r	  >   r	  r	  >   r	  r  rP  
confirm_idr    r	  r	  r
  z | last_activity=r  r	  .0fzs ago) | iteration=r	  r  r  i   zWEvicting stale _running_agents entry for %s (age: %.0fs, idle: %.0fs, timeout: %.0fs)%sstale_running_agent_evictionr6  r  r   uF   PRIORITY photo follow-up for session %s — queueing without interrupt&HERMES_TELEGRAM_FOLLOWUP_GRACE_SECONDSz3.0uV   Telegram follow-up arrived %.2fs after run start for %s — queueing without interruptrd  r	  rq  u7   HARD STOP (pending) for session %s — sentinel cleareduE   ⚡ Force-stopped. The agent was still starting — session unlocked.r	  r	  r	  r	  z'PRIORITY queue follow-up for session %sr  z(PRIORITY steer failed for session %s: %szPRIORITY steer for session %sz/PRIORITY steer-fallback-to-queue for session %szjPRIORITY interrupt demoted to queue for session %s because the running agent has active subagents (#30170)zdPRIORITY interrupt demoted to queue for session %s because context compression is in flight (#56391)r	  r	  z PRIORITY redirect for session %sz+PRIORITY redirect failed for session %s: %sz!PRIORITY interrupt for session %sr  zVoice-priority-interruptr	  )GATEWAY_KNOWN_COMMANDSis_gateway_known_commandrF  quick_commandsr   aliasr  )r_   r  r   raw_commandr  r%	  zcommand:z/command:%s hook dispatch failed (non-fatal): %sdecisionr	  r  z
Command `/z` was blocked by a hook.handledr'  r%	  r  c                  >   K                                    d {V S r;   )r%  r  r  s   r6   	_do_resetz0GatewayRunner._handle_message.<locals>._do_reset^:  s-      !77>>>>>>>>>rB   z/newzJThis starts a fresh session and discards the current conversation history.)r  r   rL  detailexecutetopicr  rr  z,Ignoring /start platform ping for session %sr  whoamir  r  r  r  rt  memoryskillslearn)build_learn_promptu+   Learning a skill from what you described…u*   Learning a skill from this conversation…r  zlearn ack send failedu,   Could not start /learn — please try again.init)build_init_prompt_for_cwd)r  u+   Could not start /init — please try again.zUPDATE the existing AGENTS.mdu)   Updating AGENTS.md from a project scan…u+   Generating AGENTS.md from a project scan…zinit ack send failedr;	  r  r  r  r9  r  r  personalityr  suggestions	blueprint
agent_seedzblueprint ack send failedretryundoc                  >   K                                    d {V S r;   )_handle_undo_commandr_  s   r6   _do_undoz/GatewayRunner._handle_message.<locals>._do_undo;  s-      !66u=========rB   rk   z;This removes the last user/assistant exchange from history.zThis removes the last z user turns from history.z/undosethomecompressusagetopupinsightsz
reload-mcpzreload-skillsbundlesr	  r  r  r0   rL  r7  rb  branchrollbackdiffr  r'  zJUsage: /steer <prompt>  (no agent is running; sending as a normal message)r  r  )	moa_usagenormalize_moa_configr7  default_presetzmoa://localzmoa-virtual-providerchat_completions)r  r  r  r  r  zFailed to prepare MoA turn.r  r  z) and is not accepting new work right now.execr   rD
  rI
  r  r  r   zCommand returned no output.zQuick command timed out (30s).zQuick command error: zQuick command '/z' has no command defined.z' has no target defined.z4' has unsupported type (supported: 'exec', 'alias').)get_plugin_command_handlerr  r  z"Plugin command dispatch failed: %s)build_bundle_invocation_messageresolve_bundle_command_key)r  r_   z$Bundle %s skipped missing skills: %sr   zBundle dispatch failed: %s_bundle_handled)get_skill_commandsbuild_skill_invocation_messageresolve_skill_command_keyr   )get_disabled_skill_namesrc   r,  z** skill is disabled for z(.
Enable it with: `hermes skills config`)&build_stacked_skill_invocation_messagesplit_stacked_skill_commandsc                     g | ]X}                     |i                                d d          v .                     |i                                d d          YS )r   r   r)  )r?   r  _plat_disabled
skill_cmdss     r6   r  z1GatewayRunner._handle_message.<locals>.<listcomp>T<  sj     + + + !)~~a4488DDVV 'NN1b1155fbAAVVVrB   z8** skill(s) in this stacked invocation are disabled for z*.
Enable them with: `hermes skills config`r  z#Failed to load stacked skills for /r   uO   Unrecognized slash command /%s from %s — replying with unknown-command noticer  zUnknown command `/zl`. Type /commands to see what's available, or resend without the leading slash to send as a regular message.z*Skill command check failed (non-fatal): %su;   Refusing new turn for session %s — external drain active.u   ⏳ This agent is draining for a maintenance action and isn't accepting new turns right now. It'll be back in a moment — please resend shortly.z@Rejecting new active session %s: max_concurrent_sessions reachedr  )r1  r  r  z!goal continuation hook failed: %s)r  gateway.session_contextr>  r.   r/   r0   r   r-   r  r  r  r  r
  r  r
  r?  r   rR   rS   rT   r_   r   r  rU   r>  rJ  r  r	  r  r}  _get_unauthorized_dm_behaviorr  _pairing_store_forr  _is_rate_limitedgenerate_coder	  r  _record_rate_limitr  r  
persistentupdate_prompt_pendingr   rV   get_commandr>  rF  r   r;  with_suffixr  rD  ru   r   r  r  get_pending_for_sessionr	  _prepare_clarify_reply_textr  r   !resolve_text_response_for_sessionresume_typing_for_chatrM  get_pendingr  r	  r  rW   ro   clear_if_stalerY  r  r	  r   r,   rG  r   r	  r  ri  "_invalidate_session_run_generationr
  r  r  r  _check_slash_accessr  r  r;  r  r?  r  rq   r  r  r	  r  r  r9  r  r  r	  r  r  r  r  ru	  r|	  r	  r	  r  r  rW  rX  rX   r/  rC   r  emit_collectr  r  r   r+   _maybe_confirm_destructive_slash_handle_topic_commandr  r	  r
  _handle_whoami_commandr  r  r  _handle_platform_commandr   _handle_stop_command_handle_reasoning_command_handle_memory_command_handle_skills_commandagent.learn_promptrh  r	  hermes_cli.init_commandrj  _handle_fast_commandr  r  r  _handle_approvals_command_handle_model_command_handle_codex_runtime_command_handle_personality_commandr  _handle_suggestions_command_handle_blueprint_command_handle_retry_commandrF  rH  
IndexError_handle_set_home_command_handle_compress_command_handle_usage_command_handle_topup_command_handle_insights_command_handle_reload_mcp_command_handle_reload_skills_command_handle_bundles_commandr	  r	  r  r  _handle_debug_command_handle_title_command_handle_resume_command_handle_sessions_command_handle_branch_command_handle_rollback_command_handle_diff_commandr  r9  hermes_cli.moa_configr}  r~  rg  r8  r  rB  rC  _moa_restore_overrider  _moa_disable_after_turnr  _handle_voice_commandrX
  rE
  create_subprocess_shellr  r  r  r  r  r   r   r  rH  r  r  agent.skill_bundlesr  r  rD   localsagent.skill_commandsr  r  r  r/  r  r  r  r9  r'  r)  r  rn	  leaser	  _begin_session_run_generation_handle_message_with_agentr	  r  _post_turn_goal_continuation_restore_moa_one_shot(_restore_pending_one_turn_model_override_release_turn_lease)r  r  r  r>  is_internal_invoke_hook_hook_results	_hook_exc_result_action	_new_textr.  r  coder  store_profileprofile_arg
_quick_key	_up_staterV  r   r  _recognized_cmd_resolve_update_cmd_cmd_defresponse_pathprompt_pathtmprs  labelr  _pending_clarify_clarify_has_audio_raw_clarify_reply	_resolved_clarify_adapter_slash_confirm_mod_pending_confirm_tool_approval_liver	  
_raw_reply_norm_reply
_cmd_reply_confirm_choice_raw_stale_timeout_quick_state	_stale_ts
_stale_age_stale_agent_stale_idle_stale_detail_sa	_wall_ttl_should_evict_resolve_cmd_inner_evt_cmd_cmd_def_inner_denied_telegram_followup_grace_grace_state_started_at	_ra_statero	  r	  r	  r5   r	  r	  r  r   rW  rX  _resolve_cmd	canonicalrY  qcmdr  target_command	user_argsr%	  hook_ctxhook_results	_hook_errhook_resultr\  r  r#  new_argsr`  r  rh  
_learn_req_ack	_ack_metarj  _init_notes_init_prompt_blueprint_result_blueprint_seedrs  _undo_n	_undo_raw_undo_detailqueue_payloadsteer_payloadr}  r~  r8  moa_payloadrk  moa_cfgpreset
_moa_stateexec_cmdrE
  sanitized_envr  r  r  r  r   r  plugin_handlerr  r  r  r  
bundle_keyuser_instruction_bundle_platbundle_resultr|  _loadedmissingr  r  r  cmd_key_skill_namer  _get_plat_disabled_build_stackedr  
extra_keysstacked_instruction_disabled_extrastacked_result_missing_unavail_msg_active_session_lease_limit_message_claim_state_run_generation_agent_result_final_textr1  	_goal_excr  r  s   ``                                                                                                                                                           @@r6   r  zGatewayRunner._handle_message~7  s;      	VBBBBBB     	V 	V 	VLLEPTLUUUUU	V
 75*e<<== 	
D11X^CC)h--wvy$/O/O  D
 KKK	400   4 D8%@@		 E#CUKK	
 --e4444  	411333  #	#LLLLLL ,*  #*$"F"F! ! !  # # #KYWWW "# )  !'400 !++h//f$$KKRH--17O--i3)	    44i'' 'F 3 3I!)S11 . + 3E	 J J J!&Eg%%E &  D	^# ++F33 GI^___t ))&11 8	NN=v~vO_agapavwww  D((66O"N 7   	  :@ W 5 5i $ 7 7 ? ? (LLK%    4 !11-PP  4$22!6>63C3Ir   T"66v>>G (/y$(O(O  *-==$ -$ !. : : 3-2222 "$ $ &ll"N7:>7 7 (37 7  -	7 7 04	7 7 7         #66v>>G %ll"N6         "44]FNSSS4 11&99
,,Z88	 Y%9%O :#**,,C##%%C((( #&& #"& 
33^^^^^^^$ 3 3 3.2+++3*63':':3'?'?H?G.QhmmTOO( 3 3 3.2OOO3" ($&MM$'M D ,/A A*-BBQ'33F;;CNN=7NCCCKK...&&$&7777 Q Q QNN#H!LLLPQPPPPPPPPQ >C	$:),]););r)A)A}UXVXUXGY\aGaCECCCC  C ,/A A*-BB'33F;;CNN2N888KK...&&$&777KKP'"	       NNW       
 >C	$: 	$======+CC4  D      	$ 	$ 	$#	$'L,D!%d&E&Ee&L&L!M!M'+'G'G'N'N!N!N!N!N!N!N! *< B$/	   r
 " *<*G*G*L*L (JJ 2 	  KKW"$4$?   (,'?'?'G'G$' ,CCFNSSSS(   "LL P)- )      2 	>=====-99*EE#	(<<<<<<"7"7
"C"C 	( 	( 	("'	( 	:$7 	:**1133J %++D117799K**,,J"O@@@"(555"*DDD"* CCC"( <<<"* ==="**"4"<"< 0 4 4\ B BO# #      	 !B& --j999 ((>EE//
;;4@GL%00a	#(9(?(KPY(Ky0J',2L  ,,KM 
6L M M 
	&;;==C"%''*BE%LL"Q"QKeCGG4H),T,T e e'4e e'*ww/?'C'Ce eFIggN^`aFbFbe e "M
 !   D
 ?QST>T>T.3T:::Z_`eZfZfI$;; '!+Q?Q0Q .!I-	   >B
K&	   779 8    11*===##J// H	 RQQQQQ((**H=EO//9994N  @."5"A"A!88????????? A."5"B"B!99%@@@@@@@@@  #N6226>;NOO&"N  !>>>:v         ![%666egqrrr226:: ^/0I:W\]]]t',	BEJJ( ($  33J??L:FM,+66AK8#444&+*:::,q00 1Y[[;.3KKKlIKK+-  
 226:: 	,77**:ugFFFF3#5&!'+	    t00<<I4=GIN004M 777$$&&&0055jAAAKK Y[efff)*qrrr 226:: /1"#'	    t~ 3355 L88UKKK 7799ws4#=#=#?#?ssssv4+E+E+G+Gvvv
 $//F
SSS44ZGGGt$// $j.B5577
&+*:::!, ;!- ; # ;  w77	 ;("&}':'::'F'F"G"G$ ( ( ('QS]_bccc"'(   LL!@*MMM4NPZ[[[44ZGGGt //>> N  
 44ZGGGt <<ZHHHHHHHH H  
 44ZGGGt
 "k&666( 7) 7 M+KUSS M:66	$--uz/?R.F.F.H.HII $%GTTT#t$ !   NNE"        LL<jIII#jO!%t<<BK..u55 	B+/+R+R,,V44J$" : ,S , , & & & & & &" % B B":5"A"A##O444 4 ##%%	
 	
 	
 	
 	
 	
 	
 	
 	
 	
 -4=<<(((%-:HMM7	  	Kx'$+t,, R!%1A2!F!F!L"!(6F!K!K!Qr.$// KG~4M4M%g.88F##w.."hhx006B==??F K+1+<+<S+A+A!S|6||)/s););$)$:$:$<$<$B$B$D$D	(.%<%<%<%<%B%B%D%D
?M"a."6"6"8"8";";Sa<C#M<<#8#8#85=$JHMM7	  	y 	%=%=i%H%H 	..vyAAG"  .	//	:: .	--//5577H5;_LFO11"!>$& $ H	"%)Z%<%<*y**H& &              " " "Ey    ""  ,  !+t44 {z2>>??EEGGMMOO 8w#6#6v%%)ooi88G!'3// 'G '&IIIIIIIy(()ooi88G&0#&>&>T7T77PTTTTy(("%#;;# #eggffSkk   ' ! ";??:r#B#BCCIIKKH!=[!=!=8!=!=!C!C!E!EEJ#//11G8?I||G444TH19 FwIE ) &t'I6RRRRRRRR ?<<>>>? ? ? ? ? ?>>, " ? 	 	 	 	 	 	 	 	 	 33E:::::::::225999999999KKF
SSS2
""66u=========	!!55e<<<<<<<<<  44U;;;;;;;;;  44U;;;;;;;;;  ??????%%'''	!!55e<<<<<<<<<  44U;;;;;;;;;
""66u=========	!!55e<<<<<<<<<225999999999##77>>>>>>>>>  44U;;;;;;;;;  44U;;;;;;;;; >=====//117799J B==A 
E226:: V $ @ @ H HI!,,s6>':':D9,UUUUUUUUU E E E4tDDDDDEF//
;;

 F F FEEEF  JIIIII002288::KE88{KKK E E EDDDE 3lBB <;B 
D226:: V $ @ @ H HI!,,s6>':':D9,UUUUUUUUU D D D3dCCCCCD%EJ 225999999999	!!55e<<<<<<<<<  44U;;;;;;;;;225999999999##77>>>>>>>>>33E:::::::::'';;EBBBBBBBBB%%99%@@@@@@@@@  44U;;;;;;;;;%%99%@@@@@@@@@##&*&D&DU&K&K K K K K K K%&7tLLO F 0&"==C QQ"&":":6"B"B" ^(,(H(H(P(PI"),,s6>/B/BDS\,"]"]]]]]]]]$ Q Q Q%@4PPPPPQJ!0EJJ  J J J"#4fbAAITIIIJ 0&"==EE33E:::::::::> > > > > >G..006688I   !!S):):1)=%>%>??GG"J/      GGG  a<< NMPgPPP 
 >>#  ?          	!!66u=========
""66u=========33E:::::::::33E:::::::::
""66u=========$$88?????????'';;EBBBBBBBBB	!!55e<<<<<<<<<	!!55e<<<<<<<<<225999999999  44U;;;;;;;;;	!!55e<<<<<<<<<33E:::::::::33E:::::::::  44U;;;;;;;;;
""66u=========  44U;;;;;;;;;
""66u=========225999999999$$88?????????!2244::<<M  0//*

     "2244::<<M  dcc*

    225999999999
        655555002288::K # y{{"3!kmm..CQUAVAV/^swwu~~~\^__ 3 3 3..r223-.F5(
!00<<
.8.E.T+ %# -5 2: :
'6 ((44404-- 5 5 54445 	!!55e<<<<<<<<<33E:::::::::> 	mlT%?%?%A%Allll  ;	l$+t,, R!%1A2!F!F!L"!(6F!K!K!Qrnd33 $!#.(( 2267CC&"N%g.88F##v--#xx	266H U? VUUUUU,@,@,B,BM)0)H ('.'9'>'.'9'>$1	* * * $ $ $ $ $ $D 4;3CDDTDTDVDV`b3c3c3c-c-c-c-c-c-cNFF&,&6%>%>%@%@%F%F%H%HF% G N N N N N N)>)>v)F)F-3#V669VV&3 D D D#C#C#C( ? ? ?#>1#>#>>>>>>>?  U'TTTTXXf%%00"hhx006B==??F T+1+<+<S+A+A!S|6||)/s););$)$:$:$<$<$B$B$D$D	(.%<%<%<%<%B%B%D%D
?M"a."6"6"8"8";";Sa  T'SSSSkgkkkk  	HHIIIIII "<!;GOOCQT<U<U!V!V! ; % 6 6 8 8 > > @ @I+^I66F*622 .'-*0:3v;;;d:;  H H HCQGGGGGGGGH  !	B $OB        87@@
)','='='?'?'E'E'G'G$ =CO#U6?#8#8QUL$C$C"$4j!-% % %M % 0=-Wg%(
*." "KK F *DIIg,>,>  
  B B B;SAAAAAAAAB  j	N688<<(95AA j	NiN         
 0/11
33G<<&
 #-W"5"9"9&""E"EK5;_NFO11$E  dddddd&*<*<e*L*L*LLL!J !J !Ju !J !J !J (-'='='?'?'E'E'G'G$
O       
 989IJJ 8
$7$7 % O O O)-:<>N$7


O " e  eddddd););U)K)K)K+ + + + +%/+ + +
 + !L?)C)C !L !LGL!L !L !L
 " -n&@)7$2z2/$.* * *
 * T5C2C(),EJJ $T#S#S#SS<<#%5z    -),EJ
 $<G#D#DL# ,++ sC008NNNC#5;_MFO11#	  5 5 5 5  N N NI1MMMMMMMMN  	W%6.&
 &
  
  
  
  
  
  
 	
 88@@ A>>@@@4 & 		{ 		KKM  
)  150O0O1
 1
-~ %KKR   "!**:66 ,&;L#"9'+y{{$##%%%<<ZHH5	B"&"A"A%Q[]l"m"mmmmmmmMM mT22 0"%m&7&78H&I&I&OR"P"PKKs33 0"/K $$&& 
-.2.F.\.\]c.d.d(d(d(d(d(d(d$ - - -(,-$0"??*7#)+6 @         
  M M M@)LLLLLLLLM  &&uj99999*EEE --j999 $$ZAAAA &&uj99999*EEE --j999 $$ZAAAAs    &A	A	:$E 
F)FFT TT#T: :U	U	*AW 
W6W1+W61W6A3Z8 8
['[""['9\ \&%\&;` &`?>`?"a4 4bb$Bi' '
i43i4"|9 9
}+}&&}+BA	AC) C)
ADC3ADDADO.$AP P
AQPAQ Q AQb!AAc> c>&Ad'd&Ad'd+Ad< d<
Ae
e	Ae
f Af f
AffAff'AAh h&Ah-h,Ah-oAAp) p)&AqqAqqAq qAq>q=Aq>s,6At# t#At;t:At;@1B@9 @9
BAABAA:BB B
BBBBBC;?BD; D;BEEBEEABF; F;
BG	GBG	K1B=BN/ N/BOO	BOO
BOOBOOBOS	BBU U
BV UBU;U;BV VB!BX* X*
BYX4BYYBYZA:Ba \&Ba \(B]  \?Ba ] B]]Ba ]B]]ABa ^-Ba _,Ba _:ABa a
Ba<aBa7a7Ba<f)Bl gA(Bj h1 Bi iBj iBi!iBj i Bi!i!$Bj jBl j
Bj6jBj1j,Bl j1Bj6j6Bl lABm)c                     t          |dd          sdS 	 t          |dd          }||                     |          j        _        |                     |           dS # t
          $ r Y dS w xY w)a  Revert a ``/moa <prompt>`` one-shot model override after its turn.

        Called from the ``finally`` of the message-handling path so the revert
        fires whether the turn succeeded, raised, or was interrupted. A no-op
        unless ``event._moa_disable_after_turn`` is set. ``_moa_restore_override``
        carries the prior per-session override (``None`` means the user had no
        override, so the MoA override is cleared outright).
        r  FNr  )r-   r  rB  rC  r  r.   )r  r  r  _restores       r6   r  z#GatewayRunner._restore_moa_one_shot=  s     u7?? 	F	u&=tDDHIQD	**7F$$Y///// 	 	 	DD	s   AA 
A*)A*c                    |sdS 	 |                      |          }|r|j        j        nd}|d|j        _        |sdS |                     ||           dS # t          $ r  t
                              dd           Y dS w xY w)zBRestore a per-session model override after ``/model --once`` runs.Nz)Failed to restore one-turn model overrideTr   )r  rB  one_turn_restore_restore_session_model_overrider.   r/   r0   )r  r  
_otr_stater	  s       r6   r  z6GatewayRunner._restore_pending_one_turn_model_override=  s     	F		U11+>>JCMWz.??SWH%;?
'8 00hGGGGG 	U 	U 	ULLDtLTTTTTT	Us   5A A &A?>A?)r  r  c          
      @  K   |pg }t          |d          }|rt          |dd          n|j        pd}t          | j        dd          }t          | j        dd          }|p|                     |          }|                     |           t          |||          }	|	rL|j        rEt          |j                  }
|j	        t          j        k    r|j        r|
 d	|j         d
}
d|
 d| }t          |dd          r|j         d| }g }g }|j        r!g }g }t          |j                  D ]\  }}|t!          |j                  k     r|j        |         nd}t%          ||          r|                    |           |j        t*          j        k    r|                    |           n'|s%t/          ||          r|                    |           |                    d          s|s*|j        t*          j        k    r|                    |           |rKt5          j        | j        ||           d{V }|dk    rUt;          |          |                     |          j        _         tB          "                    dt!          |                     ntB          "                    d|t!          |                     d}	 | #                    ||          \  }}tI          |pi           }||d<   n,# tJ          $ r tB          &                    dd           Y nw xY wddl'm(}  ||          5  | )                    ||           d{V }ddd           n# 1 swxY w Y   |r| *                    ||           d{V \  }}|r| +                                r| ,                    |          }| -                    || .                    |                    }|r_|D ]\}	 |/                    |j0        d| d|           d{V  +# tJ          $ r%}tB          &                    d|           Y d}~Ud}~ww xY w|rddl1m2} |D ]}tf          j4        5                    |          }|6                    dd          }t!          |          d k    r|d         n|} to          j8        d!d|           }  ||          }!d"|  d#|! d$}"|" d%| }|rddl1m2} |D ]}#tf          j4        5                    |#          }|6                    dd          }t!          |          d k    r|d         n|} to          j8        d!d|           }  ||#          }!d&|  d#|! d'}"|" d%| }|j        rnddl9}$ddl1m2}% h d(}&t          |j                  D ]J\  }}t%          ||          s tu          ||          stw          ||          r7|t!          |j                  k     r|j        |         nd}|d)v r]tf          j4        <                    |          d*         =                                }'|'|&v rd+}n|$>                    |          \  }(})|(r|(}nd,}tf          j4        5                    |          }*|*6                    dd          }+t!          |+          d k    r|+d         n|*},to          j8        d!d|,          }, |%|          }-t          |,|-|          }.|. d%| }L|Mt          |d-d          t          j@        k    r.t          |d.d          rdd/lAmB}/  |/            rd0|jC         d1| }t          |d2d          r8|jD        r1|jE        dd3         }0t          |d4d          r	d5|0 d6| }nd7|0 d6| }d8|v r6	 dd9lFmG}1 dd:lHmI}2 tf          jJ        K                    d;tf          j4        L                    d<                    }3d}4d}5i }6g }7	 t                      }5|5K                    di           }6t          |6tH                    r&|6K                    d=          }8|8t          |8          }4	 dd>lPmQ}9  |9|5          }7n'# tJ          $ r |5K                    d?          pg }7Y nw xY wn# tJ          $ r Y nw xY w| #                    |||5@          \  }:};|;K                    dA          pd}<t          |6tH                    r*|6K                    dB          p|6K                    d          n|6}=|:|=k    rd}4|4t          |6tH                    rk	 ddClRmS}>  |>dd|6K                    dA          |<|6K                    dD          |;K                    dD                     d{V rd}4n# tJ          $ r d}4Y nw xY w|7r,|<r*	 ddElPmT}?  |?|:|<|7F          }@|@r|@}4n# tJ          $ r Y nw xY w |2|:|<|;K                    dG          pd|4|;K                    dD          pd|7H           d{V }A |1||3|A|3I           d{V }B|BjU        rT| ,                    |          }C|Cr;|C/                    |j0        dJV                    |BjW                  pdK           d{V  dS |BjX        r|BjY        }nN# tJ          $ rA}DtB          Z                    dL|D           tB          &                    dMd           Y d}D~Dnd}D~Dww xY w|S )Na  Prepare inbound event text for the agent.

        Keep the normal inbound path and the queued follow-up path on the same
        preprocessing pipeline so sender attribution, image enrichment, STT,
        document notes, reply context, and @ references all behave the same.

        Side effect: buffers per-session native image paths when the active
        model supports native vision AND the user has images attached. The
        caller consumes and clears that session-scoped buffer at the
        ``run_conversation`` site to build a multimodal user turn. When the
        list is empty, the ``_enrich_message_with_vision`` text path has
        already run and images are represented in-text.
        _gateway_pending_stt_textNr   r  Tr  Fr  z | Slack user <@>[r  r.  z

[New message]
r  r  nativezSImage routing: native (model supports vision). %d image(s) will be attached inline.zLImage routing: text (mode=%s). Pre-analyzing %d image(s) via vision_analyze.r  z4vision enrichment: session runtime resolution failedr   r   )scoped_runtime_main	   🎙️ "r  r  z&Transcript echo failed (non-fatal): %sto_agent_visible_cache_pathr  r  r  z	[^\w.\- ]z*[The user sent an audio file attachment: 'r  u3  . Its content is not inlined here. If the user's request involves what the audio contains, transcribe or process it yourself — for example by passing the path to a transcription or media tool — instead of asking the user to describe it. Only ask what to do with it if their intent is genuinely unclear.]r   z$[The user sent a video attachment: 'u1  . Its content is not inlined here. If the user's request involves what the video contains, inspect or process it yourself — for example by passing the path to a video analysis or media tool — instead of asking the user to describe it. Only ask what to do with it if their intent is genuinely unclear.]>   .md.cfg.csv.ini.log.txt.xml.yml.json.toml.yaml>   r   application/octet-streamrk   z
text/plainrS  r_   r4  _discord_tools_loadedz[Triggering message id: `uG   ` — use as `message_id` for reply/react/pin via the discord tools.]

r)  rp  r,  z%[Replying to your previous message: "z"]

z[Replying to: "@)#preprocess_context_references_async)get_model_context_length_asyncr  ~r3  get_compatible_custom_providerscustom_providersr  r  r(  should_clear_context_pin_asyncr  "get_custom_provider_context_lengthr  r  r\  r  r  r  config_context_lengthr  r\  )r  r3  allowed_rootr   zContext injection refused.z(@ context reference expansion failed: %sz,@ context reference expansion failure detail)[r   r-   r   rX   r  r  r+  r  r,  r_   r  r  r  r.  r  r  r   r  r  rs   r  r;  r  r  r   r  r  r  _decide_image_input_moder  r  r  native_image_pathsr/   r  rX  rS   r.   r0   r0
  rD  _enrich_message_with_vision"_enrich_message_with_transcription_should_echo_stt_transcriptsr	  r	  r=  r  r  tools.credential_filesrG  rq   rx   r[
  rC   r<   r   	mimetypesr  r  r  rW   
guess_typer  r|  rP  rU  r4  r	  r)  agent.context_referencesrW  agent.model_metadatarX  rr   rT   r	  rQ   rR   rF  rg  r[  hermes_cli.route_identityr^  r`  blockedrD   warningsr`  r  r   )Er  r  r  r  r  _pending_stt_preparedmessage_text_group_sessions_per_user_thread_sessions_per_user_is_shared_multi_user_safe_user_nameaudio_file_pathsvideo_pathsimage_pathsaudio_pathsr  rx   r  	_img_modevision_runtime
turn_modelr  rD  _successful_transcripts_echo_adapter
_echo_meta_tx	_echo_exc_to_agent_path_apath	_basenamer  _display_agent_path_note_vpath
_mimetypesrG  _TEXT_EXTENSIONS_extguessedr  r[
  rE   r  r  context_note_disc_tools_loadedreply_snippetrW  rX  _msg_cwd_msg_config_ctx_msg_cfg_msg_model_cfg_msg_custom_providers_msg_raw_ctxr[  
_msg_model_msg_runtime_msg_base_url_msg_configured_modelr^  r`  _msg_custom_ctx_msg_ctx_len_ctx_resultr~  r5   sE                                                                        r6   _prepare_inbound_message_textz+GatewayRunner._prepare_inbound_message_text#=  sp     * -R '/J K K %GE6=== 	 	
 $+4;8QSW#X#X $+DK9SUZ$[$[! "IT%A%A&%I%I 	00=== <$<%>!
 !
 !

 ! 	AV%5 	A ?v?OPPO (.00V^0&IIIII   A@@,@@L
 5+T22 	W#3VVVVL ')!# `	"KK$U%566 - -401C8I4J4J0J0J)!,,PR )22 -&&t,,, %):::$++D1111. -3LUTU3V3V -&&t,,,##H-- -e -@RVaVg@g@g&&t,,, 2 #*"31! +# # #      	
 (( 7;;6G6G ''#  !3KKmK((   
 KKf!3{#3#3   &*N595X5X#)(3 6Y 6 62
N *.n.B)C)C2<w//$   R%) %      KJJJJJ,,^<<  -1-M-M('. . ( ( ( ( ( (                ">B>e>e ? ? 9 9 9 9 9 955 + "t/P/P/R/R "$($<$<V$D$DM!%!A!A&$JfJfglJmJm!n!nJ$ "#: 
" 
"C	"&3&8&8$*N$6$6$6$6-7 '9 '" '" !" !" !" !" !" !" !" !"
 $- " " " &$Li!" !" !" !" !" !" !" !""  	<\\\\\\* < <G,,V44	"a00(+Fq(8(86!99i6,X>>,nV44F F F'2F F F  #(;;\;; 	<\\\\\\% < <G,,V44	"a00(+Fq(8(86!99i6,X>>,nV44F8 F F'2F F F  #(;;\;; -	C****JJJJJJyyy$U%566 (C (C4 *%33,UA66 -UA66
 01C8I4J4J0J0J)!,,PR<<<7++D11!4::<<D/// ,%/%:%:4%@%@
" ?$+EE$>E
 7++D11 sA..+.u::??uQxx!vlCFF
 98>>
;L*V[\\".BBLBB 
D11X5EEE|T22 F TSSSSS!!## &0@ & &#& &  5/400 	UU5N 	U "/5Mu7?? U&M & &#& & 
  UTTlTT,e\XXXXXXOOOOOO:>>."':L:LS:Q:QRR"&!#(*%355H%-\\'2%>%>N!.$77 @'5'9'9:J'K'K'3.1,.?.?OWUUUUUU0O0OPX0Y0Y--$ W W W08=O0P0P0VTV---W    D ,0+N+N! + ( ,O , ,(
L
 !- 0 0 < < B ".$77(N&&y11P^5G5G5P5P' &
 !666&*O".:nd3S3S./\\\\\\!?!?  *..z::)*..z::(,,Z88" "       3 /3O$ / / /*./( ] XXXXXX*L*L",%2-B+ + +
 + >.=O$   %C%C*(,,Y77=2*9)--j99?R%:& & &             %H$G  #/!)	% % %       &  #77??H &mm"N IIk&:;;[?[          4' 7#.#6L \ \ \I3OOOKVZ[[[[[[[[\ s   =0K. .&LL+MMM'P
P2P--P2)Ai ;Aa `- ,a -!aa aa i 
a"i !a""Bi 8Ae i ei ei 'f  ?i  
f
i fB2i i 
j7jjc                6  K   t          t          | dd          dd          rYt          |                     |                    5  |                     ||||           d{V cddd           S # 1 swxY w Y   |                     ||||           d{V S )zDRun inbound preprocessing under the routed profile when multiplexed.rX   Nr  Fr  r  r  r  )r-   r   _resolve_profile_home_for_sourcer  )r  r  r  r  r  s        r6   ,_prepare_profile_scoped_inbound_message_textz:GatewayRunner._prepare_profile_scoped_inbound_message_text>  s+      744002FNN 	'(M(Mf(U(UVV  !??!# +	 @                        77#	 8 
 
 
 
 
 
 
 
 	
s   A11A58A5c                    K   |                      |          s|j        pd                                S |                     |d           d{V \  }}d                    d |D                       S )zDReturn raw text or successful voice transcripts for a clarify reply.r   Nr   c              3   f   K   | ],}|                                 |                                 V  -d S r;   r  )r?   
transcripts     r6   rA   z<GatewayRunner._prepare_clarify_reply_text.<locals>.<genexpr>>  sT       
 
!!

 
 
 
 
 
rB   )r	  r   rV   $_transcribe_pending_audio_event_oncerD   )r  r  r  r	  s       r6   r  z)GatewayRunner._prepare_clarify_reply_text>  s      ..u55 	.J$"++---*.*S*S2+
 +
 %
 %
 %
 %
 %
 %
!! {{ 
 
4
 
 
 
 
 	
rB   c                     |                      |          }||j        j        sg S t          |j        j                  }g |j        _        |S r;   )r  r  rf  r  )r  r  r  r  s       r6   r  z1GatewayRunner._consume_pending_native_image_paths>  sL    ((55= 0 C=IU%899.0+rB   c                    |r|d S t          | dd           }|t                      }|| _        	 t          j        |          ||<   n.# t
          $ r! t                              d|d           Y d S w xY w	 |                    |           t          | dd          }t          |          |k    r+|
                    d           t          |          |k    )d S d S # t
          $ r Y d S w xY w)	Nru  z*Failed to cache live session source for %sTr   rv  r4  Fr&  )r-   r   ru  r>  rJ  r.   r/   r0   r  r   popitem)r  r  r  cached_sourcesmax_sizes        r6   _cache_session_sourcez#GatewayRunner._cache_session_source>  s-    	fnF '94@@!(]]N$2D!	*5*=f*E*EN;'' 	 	 	LLE{]aLbbbFF		&&{333t%;SAAHn%%00&&E&222 n%%000000 	 	 	DD	s$   A 'A32A37A"C 
C+*C+c                 ~    t          | dd          }||j        | j        urt          | j                  }|| _        |S )z>Return the single async facade for this runner's SessionStore.rd  N)r-   _storerf  r"  rd  )r  facades     r6   r	  z!GatewayRunner.async_session_store>  sG     5t<<>V]$2DDD&t'9::F(.D%rB   c                     |sd S t          | dd           }|sd S |                    |          }|'	 |                    |           n# t          $ r Y nw xY w|S )Nru  )r-   rT   r  r.   )r  r  r  r  s       r6   r	  z(GatewayRunner._get_cached_session_source?  s     	4 '94@@ 	4##K00**;7777   s   A 
AAr  r  c                 `  K   t          j                     }t          |j        d          r|j        j        nt	          |j                  }|j        pddd                             dd          }t          |dd          }t          |dd          pddd                             dd          }	t          	                    d	||j
        p|j        pd
|j        pd
|||	           t          j        | j        |           d{V }
|
\t          	                    d|j        |j        |j        |
           t#          j        ||
          }	 ||_        n# t&          $ r Y nw xY w| j                            |           d{V }|j        }t	          t          |dd          pi                     d          pd                                          }|r"|                     ||           d{V }|dS |}|                     ||           t          j        | j        |           d{V r	 | j        rF| j                            t	          |j                  t	          |j                             d{V nd}n.# t&          $ r! t                              dd           d}Y nw xY w|rt	          |                    d          pd          }|rb| j        [	 | j                            |           d{V }n/# t&          $ r" t                              d|d           |}Y nw xY w|r||k    r|}|r0||j         k    r%| j        !                    ||           d{V }||}|rK|t	          |                    d          pd          k    r#t          j        | j"        ||d           d{V  nO	 t          j        | j#        ||           d{V  n,# t&          $ r t                              dd           Y nw xY wt          |dd          }|r3| $                    |d           | %                    |           d|_&        |j'        |j(        k    p|pt          |dd          }t          |dd          rd|_)        |rC| j*        +                    d|j        r|j        j        nd|j        |j         |d           d{V  tY          || j-        |          }| .                    |          }d}d}d}	 t_                      }ta          |                    d          pi                     dd                    }n# t&          $ r Y nw xY w| 1                    |||          }g }|rt          |d d          pd!}|d"k    rd#}n|d$k    rd%}n|d&k    rd'}nd(}	 te          ||          }n# t&          $ r d}Y nw xY w|r|d)z   |z   }|3                    |           	 | j4        j-        5                    |j        t          |d*d+          ,          } |j        r|j        j        nd}!t          |d-d          }"|d.v p| j6        o
|"o|!| j7        v}#|#r| 8                    |          }$|$r|d"k    rd/}%nJ|d&k    rd0}%nA|d$k    rd1| j9         d2}%n/| j:        d3z  }&| j:        d3z  }'|'s|& d4n|&r|& d5|' d6n|' d6}(d7|( }%d8|% d9})	 t          j        | j;        |           d{V }*|*r|) d)|* })n# t&          $ r Y nw xY w|$<                    |j        |)| =                    |          :           d{V  n2# t&          $ r%}+t                              d;|+           Y d}+~+nd}+~+ww xY wd|_>        t          |d<d          },|r2|,r/t          |,t                    r|,gnt          |,          }-	 d=d>lAmB}.mC}/ g }0g }1|-D ]r}2 |.|2|?          }3|3rF|3\  }4}5}6d@|6 dA}7 |/|4|5|7          }8|8r*|03                    |8           |13                    |2           Wt          D                    dB|2           s|0rP|03                    |j                   d)E                    |0          |_        t          	                    dC|1|           n3# t&          $ r&}+t          D                    dD|-|+           Y d}+~+nd}+~+ww xY wt          | dEd          }9|9\|9F                    |j         ||t          dFdG          H           d{V }:|:(| H                    |          jI        };|:|;_J        ||;_K        | j        L                    |j                    d{V }<|<rt          |<          dIk    rd=dJlNmO}=mP}> dK}?dL}@d}AdM}BdN}CdO}DdP}Ed}Fd}Gd}Hd}Id}Jd}Kd}Li }M	 t_                      }M|Mrk|M                    dQi           }Nt          |Nt                    r|N}?nt          |Nt                    r|N                    dR          p|N                    dQ          p|?}?|N                    dS          }O|O(	 t          |O          }Fn# t          t          f$ r Y nw xY w|N                    dT          pd}G|N                    dU          pd}H|M                    dVi           }Pt          |Pt                    rct	          |P                    dWd                    U                                dXv }A|P                    dY          }Q|Q0	 t          |Q          }R|Rd=k    r|R}Bn# t          t          f$ r Y nw xY w|P                    dZ          }S|S0	 t          |S          }R|Rd=k    r|R}Cn# t          t          f$ r Y nw xY w|P                    d[          }T|T0	 t          |T          }R|Rd=k    r|R}Dn# t          t          f$ r Y nw xY wt          |D|C          }D|P                    d\          }U|U0	 t          |U          }R|Rd=k    r|R}En# t          t          f$ r Y nw xY w|?}J|G}K|H}L	 | X                    ||t          |Mt                    r|Mnd]          \  }?}V|V                    dT          p|G}G|V                    dU          p|H}H|V                    d^          p|I}In# t&          $ r Y nw xY w|F2	 d=d_lYmZ}W  |W|J|?|L|H|K|G           d{V rd}Fn# t&          $ r d}FY nw xY w|F|Hr	 	 d=d`l[m\}Xm]}Y  |X|M          }Zn<# t&          $ r/ |M                    da          }Zt          |Zt                    sg }ZY nw xY w |Y|?|H|Zb          }[|[rt          |[          }Fn# t          t          f$ r Y nw xY wn# t&          $ r Y nw xY w|A	r |>|?|Hpd|Ipd|F|Gpdc           d{V }\t          |\|@z            }]t          |\ddz            }^t          |<          }_|j^        }`|`d=k    r|`de}an |=|<          df}a|B}b|]k    p|_|bk    }c|crt          | dgd          }d|dt          |ddh|d          }dt          |ddid          }e|ei	  |e|j                   }fn# t&          $ r d}fY nw xY w|frC|f                    djd=          d=k    r)t          	                    dk|j         |fdj                    d}c|crt          	                    dl|_dm|at          |@dnz            |\dm|]dm           | =                    || _                    |                    }g	 d=dol`ma}h d=dplbmc}i | X                    ||t          |Mt                    r|Mnd]          \  }?}V|V                    d^          rdq |<D             t                    dIk    r	 | j        d                    |j                    d{V }jn<# t&          $ r/}kd}jt          D                    dr|j         |kd           Y d}k~knd}k~kww xY wt          | j        dh| j                  }l |id,i |V|?dIdddsg|j         |ldtt          |j           t          _        d}m	 d_g        t          t          dud          dvd          }nt          |n          r |n|l|j                    d_i        dw _j        t          jk                    }o |h            |ol                    dfdx          }p	 t          jm                    }q	 t          |Cn                                z
  dy          }r	 t          jo        t          jp        |p          |rz           d{V \  }s}tno# t          jq        $ r] t          jm                    |qz
  }un                                }v|v|Ck     r+|u|Dk     r%t          	                    d{|j         |u|v|D           Y Â w xY wn# t          jq        $ r d}w|w<jr        rd}wn2s                                }w|wt          jt        d|           d{V  |w<|ws|p d{V \  }s}tn-u                                 | v                    |pd}~           d}m|Ed=k    rt          | |j         |E           d=dlxmy}x t          d|xj{        d           t          D                    d|j         n                                t          jm                    |qz
  |D           d|Cdd}y	 | 8                    |          }z|zr*|j        r#|z<                    |j        |y|g:           d{V  n2# t&          $ r%}{t          D                    d|{           Y d}{~{nd}{~{ww xY w Y n>t          $ r2 }                                 |ms| v                    |pd~           d}m w xY wj         }||||j         k    }}ta          t          dd                    }~|}r| j        ~                    |||s           d{V s&t                              d|j         ||           d}}d}~n`|||_         |                     ||||           | j                                         d{V  t          j        | j"        ||d           d{V  |}r$d=|_^        |s}<t          |s          } |=|s          }nJ|~r$d=|_^        |s}<t          |s          } |=|s          }n$|_}}t          D                    d|j                    t          	                    d|_|dm|dm           ||^k    rt          D                    d|dm           t          dud          }|t          |dd          r|Ed=k    rt          | |j         |E           d=dlxmy}x t          d|xj        d           t          |dd          pd}d=dlm}  ||d          }d| d}	 | 8                    |          }z|zr*|j        r#|z<                    |j        ||g:           d{V  n# t&          $ r%}{t          D                    d|{           Y d}{~{nd}{~{ww xY w|t          |dd          rt          |dd          }t          |dd          pd}d| d| d}	 | 8                    |          }z|zr*|j        r#|z<                    |j        ||g:           d{V  n2# t&          $ r%}{t          D                    d|{           Y d}{~{nd}{~{ww xY w| %                    |           |ms|                     d~           d{V  n:# | %                    |           |ms|                     d~           d{V  w w xY wn2# t&          $ r%}+t          D                    d|+           Y d}+~+nd}+~+ww xY w|<s| j                                         d{V sd}	 d=dlm}m}m}m}m} t_                      } ||          dk    rQ |||          sE|3                     |                                                        |t          dz  |           n|3                    |           nG# t&          $ r:}t                              d|           |3                    |           Y d}~nd}~ww xY w|<s|j        r|j        t          j        k    r|j        t          j        k    r|j        j        }!t#          |!          }d}	 d=dlm} |r ||          pd                                nd}n# t&          $ r d}Y nw xY w|s-|r)t)          j        |          pd                                nd}	 |s!| j-                            |j                  rd}n# t&          $ r Y nw xY w|sk	 d=dlm} t          |dd          pd                                }|r,|dRk    r& |            }|                    |j                  rd}n# t&          $ r Y nw xY w|sQ|j        t          j        k    rdnd}d|!                                 d| d})|                     ||)           d{V  |                     |||          }|r|3                    |           |                     |||<|           d{V }|dS 	 d=dlm} d=dlm}m}m}  |            }t          |dd          }|rgt          |t                    rR |||          \  }}|} |||          }||n|}tI          t_                                r ||||          }n|}n2# t&          $ r%}t                              d|           Y d}~nd}~ww xY w|r|r|                     ||           |                     | 8                    |          ||           	 |j        r|j        j        nd|j        |j        pdt          |dd          rt	          t          |dd                    ndt          |d*d          pd|j         |dd         d}| j*        +                    d|           d{V  |j         }t          jm                    }|                     |||<||||| _                    |          |j        t          |dd          |||j                   d{V }t          jm                    |z
  }	 | 8                    |          }t          tU          |          dd          }t          tU          |          dd          }|rXt          |          rI|                    |j        | =                    || _                    |                               d{V  n1|r/t          |          r |                    |j                   d{V  n# t&          $ r Y nw xY w|                     ||          st          	                    d|pd|           | 8                    |          }t          tU          |          dd          |                    ||           n-|r+t          |d          r|j                            |d           	 |                     |           dS |                    d          pd}te          |          rd}	 d=dlm}  |||          }n# t&          $ r d}Y nw xY w|dk    r|sd}|                    dg           }t          j                     |z
  }|                    dd=          }t          |          }t          	                    d||j        pd
|||           |rztk          |          rj|                     |           	 | j                            |           d{V  n3# t&          $ r&}t                              d||           Y d}~nd}~ww xY w|s6tq          ||t          |<          ɦ          }ts          |j        |          }|                    d          r|d         |j         k    r|j         |k    r|d         |_         |                     |||j                    | j                                         d{V  | j                            |j         ||           d{V  t          j        | j"        ||dʬ           d{V  n$t          	                    d|pd||j                    	 tw          t_                      ty          |j                  dta          t          | dd                    |j        t          j        hΦ          }n9# t&          $ r, |j        t          j        k    rdnt          | dd          }Y nw xY w|r|r|s||                    dϦ          }|rdd=dlm} |                                                                }t          |          dk    r7dE                    |ddх                   }|dt          |          dz
   dӝz  }n|                                }	 d=dlm}  |t_                      ty          |j                  dd֦          }n# t&          $ r d}Y nw xY w|dk    r:dE                    d؄ |                                D                       }d| d)| }nS|dk    r:dE                    dۄ |                                D                       }d| d)| }n ||          }d| d| }d}	 d=dlm}  |t_                      ty          |j                  |                    dQ          |                    dd=          pd=|                    dS          pdt(          j                            dd          |          }n4# t&          $ r'}t                              d|           d}Y d}~nd}~ww xY w|r |r|                    d          s	|s| d)| }| j*        +                    di |d|pddd         i           d{V  	 d=dlm} |j        }g |_        t          |          D ]O\  }}t          j        |                     |                     |dnz  dk    rt          jt        d=           d{V  Pn2# t&          $ r%}+t                              d|+           Y d}+~+nd}+~+ww xY w	 d=dlm} t          |j                  }|D ]d}Đt          |Ħ          }|rP	 |                     ||Ħ           d{V  2# t&          $ r%}t                              d|Ʀ           Y d}~ƌ\d}~ww xY wen2# t&          $ r%}+t                              d|+           Y d}+~+nd}+~+ww xY wta          |                    d                    }ǐte          |          }t	          |                    dd                    U                                |oTta          |                    d                    p2t          fddD                       pdv ot          |<          dk    }|r!t          	                    d|j                    nZ|r!t          	                    d|j                    n7|r5t          D                    d|j         |                    dd                     |                    d          r%t          	                    d|r|j         nd           n|                    d          r|r|rt          	                    d|j                    | j                            |           d{V }| %                    |           | $                    |d           |ʁ%|}t          j        | j"        ||d           d{V  |pddz   }t          j                     }|rnf|<sd|                    dg           }| j                            |j         d|pg t                      |j        r|j        j        nd|d           d{V  |                    d | j        du          }|rn.|s|rĐd||n|||n|ːd}|j        rt	          |j                  |ΐd<   |j        o7| j                            |j         t	          |j                             d{V }|r)t          	                    d|j        |j                    n| j                            |j         ||͐           d{V  nf|                    dt          |<                    }t          |          |k    r
||d         ng }|sd||n|||n|ːd}|j        rt	          |j                  |ΐd<   | j                            |j         ||͐           d{V  |r/| j                            |j         d||ːd|͐           d{V  nd}|D ]}|Ӡ                    d          d	k    ri |ӥd|i}|sA|Ӡ                    d          dk    r&|j        rd|vrt	          |j                  |Ԑd<   d}| j                            |j         ||͐           d{V  | j                            |j        |                    dd=          
           d{V  |                     ||j                    d{V  |r#t          	                    d|j                    d}ta          |                    d                    }| 8                    |          }|duo*ta           t          |֐dd           ||                    }|s6|                     ||||Ր          r|                     ||           d{V  |                    d          r|                    d          s|r4| 8                    |          }|r|                     |||ئ           d{V  |r	 | 8                    |          }|rJ|٠<                    |j        || =                    || _                    |                    :           d{V  n3# t&          $ r&}t                              d|           Y d}~nd}~ww xY w	 |                     |           dS ||                     |           S # t&          $ r}+	 | 8                    |          }t          tU          |ڦ          dd          }t          tU          |ڦ          dd          }|rXt          |          rI|ڠ                    |j        | =                    || _                    |                               d{V  n1|r/t          |          r |ڠ                    |j                   d{V  n# t&          $ r Y nw xY wt                              d|           	 dt                      v r|
|d}	 | j        L                    |j                    d{V }n# t&          $ r g }Y nw xY wt          |ܐdd                   D ]?}|ݠ                    d          dk    r"||n|}|ݠ                    d          |k    } n@|sqd||n|||nt          j                     d}t          |dd          rt	          |j                  |ΐd<   | j                            |j         |Φ           d{V  n-# t&          $ r  t                              dd           Y nw xY wd}t          |+dd          }dt                      v rt          |<          nd=}|dk    rd}ߐn|dk    rd}ߐn|dk    rt          |+dd          }i }	 |?|                                                    di           }t          |t                    si }n# t&          $ r Y nw xY w|                    d          dk    rH|                    d          }|r,|d=k    r&d=dl}|                    |dz            }d | d!}nEd"}nAd#}n=|d$k    rd%}n2|d&v r-|dk    r	 Y d}+~+|                     |           d'S |d(k    rd)}ߐd*|ߛ d+cY d}+~+|                     |           S d}+~+ww xY w# |                     |           w xY w(-  zAInner handler that runs under the _running_agents sentinel guard.r   r   NP   r   rn  r	  r)  zSinbound message: platform=%s user=%s chat=%s msg=%r reply_to_id=%s reply_to_text=%rr  z1telegram topic recovery: chat=%s user=%s %r -> %sr=  r   gateway_session_idr  rd  z%Failed to read Telegram topic bindingTr   r%   z$compression-tip lookup failed for %szcompression-tip-walkr6  z'Failed to record Telegram topic bindingwas_auto_resetF
auto_resetis_fresh_resetzsession:start)r_   r  r%   r  privacy
redact_piiauto_reset_reasonidler<
  zy[System note: The user's previous session was stopped and suspended. This is a fresh conversation with no prior context.]dailyz[System note: The user's session was automatically reset by the daily schedule. This is a fresh conversation with no prior context.]resume_pending_expiredu   [System note: The previous gateway session could not be recovered after a restart (API recovery timed out). This is a fresh conversation — use /resume to restore history if needed.]zy[System note: The user's previous session expired due to inactivity. This is a fresh conversation with no prior context.]r   r}  r~  )r_   session_typereset_had_activity>   r<
  r  z+previous session was stopped or interruptedz"gateway restart recovery timed outzdaily schedule at z:00r  hzh r   zinactive for u!   ◐ Session automatically reset (z). Conversation history cleared.
Use /resume to browse and restore a previous session.
Adjust reset timing in config.yaml under session_reset.r  z.Auto-reset notification failed (non-fatal): %sr-  r   )_load_skill_payload_build_skill_messager  z[IMPORTANT: The "zB" skill is auto-loaded. Follow its instructions for this session.]z#[Gateway] Auto-skill '%s' not foundz0[Gateway] Auto-loaded skill(s) %s for session %sz-[Gateway] Failed to auto-load skill(s) %s: %srr  r  rS  )	owner_keyr  r  r   )estimate_messages_tokens_roughrX  zanthropic/claude-sonnet-4.6g333333?i  r"   g     @     r@r  r(  r3  r  r  rK   r  >   rM   rO   rP   hygiene_hard_message_limithygiene_timeout_secondshygiene_total_ceiling_seconds hygiene_failure_cooldown_secondsr  r  r]  )r[  r`  r\  ra  )r  r  rc  r  ffffff?actual	estimatedr)   r*    get_compression_failure_cooldownremaining_secondszXSession hygiene: skipping compression for %s; previous failure cooldown active for %.1fsuf   Session hygiene: %s messages, ~%s tokens (%s) — auto-compressing (threshold: %s%% of %s = %s tokens)r  r+  )CompressionCommitFencers  c                 @    g | ]}|                     d           dv |S )r{  >   r  r  r  r)  r  s     r6   r  z<GatewayRunner._handle_message_with_agent.<locals>.<listcomp>jA  s8     ) ) )&'#$55==4Q#Q#Q !"#Q#Q#QrB   zSession hygiene could not restore the system prompt for session %s: %s. Preserving an empty prompt so the live turn rebuilds it with its configured providers.re  )r  r  r  skip_memoryr  r%   r3   r/  bind_session_statec                      d S r;   r,  )r
  kws     r6   r   z:GatewayRunner._handle_message_with_agent.<locals>.<lambda>A  s    D rB   c                  6                         d           S )Nr   )approx_tokenscommit_fence)_compress_context)_approx_tokens
_hyg_agent_hyg_commit_fence	_hyg_msgss   r6   r   z:GatewayRunner._handle_message_with_agent.<locals>.<lambda>A  s(    
0L0L,5r:H9J 1M 1* 1* rB   g{Gzt?r  u   Session hygiene compression for session %s still streaming after %.0fs (last progress %.1fs ago) — extending wait (ceiling %.0fs)g?zsession hygiene timeoutr
  r\  z%session hygiene compression timed outz1hygiene compression timeout activity stamp failedzSession hygiene compression for session %s made no progress for %.1fs (total wait %.1fs, ceiling %.1fs); continuing without compressionu+   ⚠️ Context compression timed out after .1fu   s with no output from the summary model. No messages were dropped — continuing without compression. Run /compress to retry, /reset for a clean session, or check your auxiliary.compression model configuration.z9Failed to deliver compression-timeout warning to user: %szsession hygiene unwindr4  u   Session hygiene: failed to persist compressed transcript for rotated session %s → %s; keeping the live entry on the original session so the conversation is not droppedzhygiene-compressionu   Gateway hygiene compression for session %s did not rotate or compact in place (no session_db on the hygiene agent) — preserving the original transcript instead of overwriting it with the summary (#21301).u>   Session hygiene: compressed %s → %s msgs, ~%s → ~%s tokensz3Session hygiene: still ~%s tokens after compression_last_compress_abortedz#session hygiene compression abortedz/hygiene compression abort activity stamp failed_last_summary_errorr  r   r   u$   ⚠️ Context compression aborted (u   ). No messages were dropped — conversation is unchanged. Run /compress to retry, /reset for a clean session, or check your auxiliary.compression model configuration.z9Failed to deliver compression-failure warning to user: %s_last_aux_model_failure_model_last_aux_model_failure_erroru%   ℹ️ Configured compression model `z
` failed (u   ). Recovered using your main model — context is intact — but you may want to check `auxiliary.compression.model` in config.yaml.z7Failed to deliver aux-model-fallback notice to user: %szsession hygienez(Session hygiene auto-compress failed: %sz[System note: This is the user's very first message ever. Briefly introduce yourself and mention that /help shows available commands. Keep the introduction concise -- one or two sentences max.])PROFILE_BUILD_FLAGr  r  profile_build_directiveprofile_build_modeaskrZ  z@Profile-build onboarding directive failed, using plain intro: %s)
get_secretrt   rj  r  z/hermes sethomez/sethomeu    📬 No home channel is set for z^. A home channel is where Hermes delivers cron job results and cross-platform messages.

Type z8 to make this chat your home channel, or ignore to skip.r  r  )coerce_message_timestampr   strip_leading_message_timestampsrE  r  z2Message timestamp injection failed (non-fatal): %srd  rp  )r_   r  r  rd  r}  r%   r  zagent:start_moa_config)r  rV  r  r  r%   r  r  r  r  r,  r+  r-  r  _stop_typing_with_metadatastop_typinguK   Discarding stale agent result for %s — generation %d is no longer currentr  pop_post_delivery_callbackr  r  r  #is_intentional_silence_agent_result(empty)u   ⚠️ The model returned no response after processing tool results. This can happen with some models — try again or rephrase your question.r  r  zMresponse ready: platform=%s chat=%s time=%.1fs api_calls=%d response=%d charsz&clear_resume_pending failed for %s: %sr  zagent-result-compressionz{Skipping agent-result session split sync for %s because the session binding moved from %s to %s before compression finishedr>	  r[  r'  rQ  )escape_code_fences_for_displayr  z
_... (z more lines)_r0  reasoning_styler  subtextc              3   (   K   | ]}|rd | ndV  dS )z-# z-#Nr,  r?   lns     r6   rA   z;GatewayRunner._handle_message_with_agent.<locals>.<genexpr>D  sB       , ,;="6J"JJJ$, , , , , ,rB   u   -# 💭 Reasoning

blockquotec              3   (   K   | ]}|rd | ndV  dS )z> rA  Nr,  r  s     r6   rA   z;GatewayRunner._handle_message_with_agent.<locals>.<genexpr>D  sB       , ,9;4IIII, , , , , ,rB   u   > 💭 **Reasoning:**
u   💭 **Reasoning:**
```
z
```

)build_footer_liner0  r  )r  r  r  context_tokensr3  r  turn_secondszruntime_footer build failed: %salready_sentz	agent:endr  r  r,  zProcess watcher setup error: %s&Watch notification injection error: %szWatch queue drain error: %sr  r  r9  c              3       K   | ]}|v V  	d S r;   r,  )r?   r  _err_str_for_classifys     r6   rA   z;GatewayRunner._handle_message_with_agent.<locals>.<genexpr>$E  s9        aq11      rB   )zcontext lengthzcontext sizezcontext windowzmaximum contextztoken limitztoo many tokenszreduce the lengthzexceeds the limitzrequest entity too largezprompt is too longzpayload too largezinput is too longr  r  zjSkipping transcript persistence for context-overflow failure in session %s to prevent session growth loop.up   Transient agent failure in session %s — persisting user message so conversation context is preserved on retry.zLSuppressing hidden-reasoning-only incomplete gateway turn for session %s: %sr  r:  u   Compression deferred for session %s — the compression lock is held by a concurrent compressor. Keeping the session intact; the next message retries normally.z7Auto-resetting session %s after compression exhaustion.compression_exhausted_resetzcompression-exhausted-resetu   

🔄 Session auto-reset — the conversation exceeded the maximum context size and could not be compressed further. Your next message will start a fresh session.r  r  )r{  r  r  r_   rE  rT  r  )r{  r  rE  r4  z:Skipping duplicate user turn (message_id=%s) in session %s)skip_dbr  r  r{  r  )r0  z5Suppressing intentional silence marker for session %s_streaming_tts_turn_completedc                      dS )NFr,  )_ar  s     r6   r   z:GatewayRunner._handle_message_with_agent.<locals>.<lambda>2F  s    ch rB   )r  ztrailing footer send failed: %szAgent error in session %srs  ir  z<Failed to persist inbound user message after agent exceptionstatus_coder  i  zH Check your API key or run `claude /login` to refresh OAuth credentials.i  zG Your API balance or quota is exhausted. Check your provider dashboard.i  r   usage_limit_reachedresets_in_secondsrB  z9 Your plan's usage limit has been reached. It resets in ~zh.zG Your plan's usage limit has been reached. Please wait until it resets.z@ You are being rate-limited. Please wait a moment and try again.i  z= The API is temporarily overloaded. Please try again shortly.>   r   rp  r  r   z% The request was rejected by the API.z)Sorry, I encountered an unexpected error.r  r,  )r,   r   r_   r   rU   r   rJ  r-   r/   r  r  r  r  r  r  r;  rd  r>  r  r.   r	  r  r  rT   rV   r  r  r  r)   get_telegram_topic_bindingr0   r  r%   r  r  r2  r  r  r  
created_atr
  r  r  r  r'  rX   _set_session_envrQ   r   _pinned_session_context_promptr)  rs   rf  get_reset_policynotifynotify_exclude_platformsr	  at_houridle_minutes_reset_notice_session_infor  r	  r  rR   r  r  r  r  r   rD   acquirerY  r  r  lease_tokenlease_generationload_transcriptr   rn  r  rX  rS   rF  rU  rH  rW   rG  r  rX  ro  r^  rg  r[  r`  r0  r=  agent.conversation_compressionr  	run_agentrs  rh  r   _GATEWAY_HYGIENE_PLATFORMcompression_in_placer  r%
  	_print_fnr	  run_in_executorrb  seconds_since_progressr  rk  r  commit_in_flighttry_cancel_before_commitr`  "release_cancelled_compression_lockr"
  r7   agent.session_activityr\  r`  AGENT_COMPRESSION_TIMEOUTr  revoke_commit_admissionrewrite_transcriptr  _rebind_turn_leaser  AGENT_COMPRESSION_COOLDOWNr   r   r
  has_any_sessionsr  r  r  r  r  r  r;  r  r<  r  r5  rT  r  rq   r  r 
  r  r  r  rL  r  _voice_channel_sidecar_noter  r  r  r  r  r  r  r  _set_pending_turn_sidecar_notes_bind_adapter_run_generation
_run_agentr  r  r   r  r  _is_session_run_currentr  r  r$  _clear_session_envr  gateway.response_filtersr  r  r@
  r
  r  r   r  r5  r=  
MATTERMOSTra  r  r!  r2  r1  gateway.runtime_footerr  rr   r  r  r  r  ri  r)  r  r  r  _inject_watch_notificationr  reset_sessionappend_to_transcriptrb  r4  has_platform_message_idupdate_session"_refresh_agent_cache_message_count_should_send_voice_reply_send_voice_reply_deliver_media_from_responser   r  r  r  mathceil)r  r  r  r  r  _msg_start_time_platform_name_msg_preview	_reply_id
_reply_txtr:  r1  r  r  resolved_entrybindingbound_session_idcanonical_session_idr  _was_auto_reset_is_new_sessionr   _session_env_tokens_redact_piir+  r-  _pcfgrV  turn_sidecar_notesreset_reasonr  continuity_noter  r.  had_activityshould_notifyr  reason_textr  r  r  r  session_infors  _auto_skill_namesr  r  _combined_parts_loaded_names_snamer&  _loaded_skill
_skill_dir_display_namer  _part_lease_registry_lease_token_lease_stater  r  rX  
_hyg_model_hyg_threshold_pct_hyg_compression_enabled_hyg_hard_msg_limit_hyg_timeout_seconds_hyg_total_ceiling_seconds_hyg_failure_cooldown_seconds_hyg_config_context_length_hyg_provider_hyg_base_url_hyg_api_key_hyg_configured_model_hyg_configured_provider_hyg_configured_base_url	_hyg_data
_model_cfg_raw_ctx	_comp_cfg_raw_hard_limitr
  _raw_timeout_raw_ceiling_raw_cooldown_hyg_runtimer^  _gw_gcp_gw_gccl_hyg_custom_providers_hyg_custom_ctx_hyg_context_length_compress_token_threshold_warn_token_threshold
_msg_count_stored_tokens_token_source_HARD_MSG_LIMIT_needs_compressr)   _getter_cooldown_state	_hyg_metar  rs  _hyg_session_rowr5   _hyg_session_db_hyg_cleanup_deferred_bind_hyg_stater   _hyg_future_hyg_wait_started_slice_compressedr  _hyg_waited_idle
_cancelledr\  _timeout_msgr~  _werr_hyg_new_sid_hyg_rotated_hyg_in_place
_new_count_new_tokens_comprp  r   	_warn_msg
_aux_model_aux_err_aux_msg_intro_noter  r  r  r  r  _onb_cfg_pb_errenv_keyhome_envr  _lgcprofsethome_cmd_vc_noters  _get_evt_tz_coerce_msg_tsr  _strip_msg_ts_evt_tz_evt_ts_clean_message_text_embedded_ts_event_epoch_ts_errr
  _run_start_session_id_turn_started_monotonicr  _turn_seconds_typing_adapter_stop_with_metadata_stop_typing_stale_adapterr  r  _intentional_silenceagent_messages_response_time
_api_calls	_resp_lenr  _show_reasoning_effectiverQ  r  r;  display_reasoningr1  _reasoning_style_quoted_footer_line_bfl_footer_errr  r  r  r`
  _pr_watch_eventsr  
synth_texte2agent_failed_earlyhidden_reasoning_incompleteis_context_overflow_failure	new_entryr  	tool_defsrT  _user_entry_skip_persistr  r  _user_msg_id_attachedr|  r  _already_sent_stts_adapter_streaming_tts_done_media_adapter_foot_adapter_err_adapter_already_persisted_recent_transcript_msg_expected_user_contentstatus_hintr  	_hist_len	_err_body	_err_json
_resets_inr<  _hoursr  r  r  r  r  s                                                                                                                                                                                                                                          @@@@@r6   r  z(GatewayRunner._handle_message_with_agent?  spF     )++29&/72S2Sm..Y\]c]lYmYm
(b#2#.66tSAAE#8$??	e_d;;Ar3B3GOOPTVYZZ
aF,KK)N'iy*	
 	
 	
 "+D,RTZ[[[[[[[[	 KKC0@)   !(9EEEF%    #6LLVTTTTTTTT#/UJ--3889MNNTRT
 

%'' 	  	+#'#I#I!$ $      N %*M"";777"4#?HHHHHHHH 8	[ &1!1!L!L//!&"233 "M " "        -1     DtTTT  /[#&w{{<'@'@'FB#G#G  $ @(8(D	@595E5Y5Y,6 6 0 0 0 0 0 0,, % @ @ @B,t %    0@,,,@ -@04DDD+?(# 1(8M<T(T(T &*%=%L%L[Zj%k%kkkkkkkH+(0 %(CL0I0I0OR,P,PPP!+96L         
[!+D,OQWYfgggggggggg  [ [ [LL!JUYLZZZZZ[
 "-1A5II 	1 **;|*LLL $$[111+0M( $(@@ ??}&6>> 	 ="2E:: 	1+0M( 	*///5;_LFO11"!>+6*	4 4          (]KK #33G<< #!%	(**E		) 4 4 :??eTTUUKK 	 	 	D	 <<[+
 
 )+  P	3"=2EtLLVPVL{**  [((  f!999  Y  ['"?v"V"V ' ' '"&' G+f4F%%l3331R+2CC#_!(d!C!C D   :@ P 5 5b&}6JERR
 !-0W W !M M$M%V-LL 
 ! "66v>>G ';66*WKK)-EEE*NKK)W44*Rv~*R*R*RKK$*$72$=E#)#6#;D:>'p%{{{{[`DpuDWDWPTDWDWDWDWimfpfpfpH*D(*D*DKW W W W !181B $ ?2 2 , , , , , ,L  , G,2)F)F)F)F( ! ! ! D!%ll"NF%)%E%Ef%M%M +           R R RMqQQQQQQQQR
 /3M+ |T22 	au 	a&0&<&<ME77$u++LaZZZZZZZZ-/+-* V VF11&*MMMG VCJ@z=J J J J  !5 4]JPU V V  9+225999)00888'LfUUUU" #**5:666!'_!=!=EJKKJ%{    a a aNP\^_````````a" "$==&!0!8!8($)"#94@@	 "9 " "      L '#22:>>C+7(0>- 0@@AYZZZZZZZZ"  x
	s7||q((        7J!%'+$"&#' ).&,1))-& M ML$(!'+$'+$I|022	 ?%!*w!;!;J!*c22 K%/

#J55 K%/^^I%>%>%g*..QXBYBY%g]g
 $.>>2B#C#C#/%=@]] : :$-z#: % % % $% )3z(B(B(Jd(2z(B(B(Jd
 !*mR @ @I!)T22 (%36%MM)T::4 4%''%94:0 +4--8T*U*U*6%*-o*>*>#*Q;;:A$7$-z#: % % % $%'0}}5N'O'O'3%*/*=*=#*Q;;;B$8$-z#: % % % $%'0}}5T'U'U'3%*/*=*=#*Q;;AH$>$-z#: % % % $% 6968L6 62 )26X(Y(Y(4%*/*>*>#*a<<DK$A$-z#: % % % $% )3%+8(+8(
/3/R/R%$/1;It1L1L$VIIRV 0S 0 0,J
 %1$4$4Z$@$@$QMM$0$4$4Z$@$@$QMM#/#3#3I#>#>#N,LL    D .9:\\\\\\!?!?1&4)4)" "       > :>6$ : : :59222: .5-5	;        5<GI4F4F11( ; ; ;4=MMBT4U4U1#-.CT#J#J ;8: 5; +3(",%2-B+ + +
 + N9<_9M9M6%z2       ( ],J,J*0b(.B*D*0b- - - ' ' ' ' ' '# -0'*<<- -) ),,?$,F(G(G% \\
 "/!A!A%%%3N$,MM%C%CG%L%LN$/M* #6"&?? 5!_4  
 # 8 #*$t"D"DK".&-k5+&N&N")+7Y[_"`"`".729'-:R2S2S#, 7 7 7267. 8?3F3FGZ\]3^3^ab3b3b &%Q$1$<$34G$H	!" !" !" 38" SKK>"~$9$9=.455.22488   !% @ @IeIefkIlIl m mIGYYYYYY555555373V3V#)(35?	45P5P(Z		VZ 4W 4 40
L
 (++I66 y*) )+2) ) )I
  #9~~22!&=A=M=Y=Y(5(@>& >& 8& 8& 8& 8& 8& 8&$4$4 (1 
!& 
!& 
!&7;$4$*NN)@ )6(@(+15 %3 %& %& %& %& %& %& %& %&
!& 3:$:JESWSc2d2d-4W 	." 	."&2	."*434/3046>Z/</G/>	." 	." 	." 	."
 !<$.$4!" !" !" 7P
 38= 5F!* GKJ$C6=(/
<PRV(W(W(<(,7& 7&O
 (0'@'@ %*(7,;,9,D)* )* )* HMJ$D;P;PJ$8+2+C+E+ED8N8N8P8P$5262F2F(,)* )* )* )* )* )* )*3& 3&K[%. =AN<L<L(9")6 690D2C2Z2Z2\2\1]056. 6.F
-6GNGW4;N;4O4O<BH2 H2 H2 B2 B2 B2 B2 B2 B2Q 163:3G -6 -6 -6>Bn>N>NQb>b8I8`8`8b8b49<P4P4P8CF`8`8`4:KK9Y 9F8P8CU8R56 56 56 5=H05#-6 16& ,3+? Y%2 Y%2 Y%259
.8.@
 0A/Q -6=B
050A0Z0Z0\0\ -7 0:/A 7>mE6J6J0J0J0J0J0J0J0J# /9.@$ 0: E)2 DO=N=N=N=N=N=NNK ->,`,`,b,b,b,0,W,W0;0:8Q -X -. -. -.
 EI,A/LPQ/Q/Q0H48-:R4Q12 12 12-. -. -. -. -. -. -R0:0W0B0\1H	-. -. -. -3NN1Q 1>0H0A0X0X0Z0Z040@0@CT0T0J	-. 	-. 	-.1]9M0U1] 1] 1] -9-2;?;S;STZ;[;[3; 16 16:B--8>8DAJ ;H ;6 ;6 56 56 56 56 56 56 56
 4= -2 -2 -2065J4912 12 12 12 12 12 12 12-2 -2 :;@ ,9 %. %. %. ):(Q(Q(S(S(S/D )I,0,W,W0;0:8P -X -. -. -.
 EI,A(-#%.. 4>3HL3?=C[3[L48(/
<WY^(_(_5& 5&M> (4 %.595M5`5`,8+6* 6* 0* 0* 0* 0* 0* 0* ). -3LL1N
 1>0H0<-. -. -. <AL<AMMGSM,D
 -1,C,C0:NL-. -. -. 372J2P2P2R2R,R,R,R,R,R,R,R292C040Q067L3. 3. 3. -. -. -. -. -. -. -. (4 %*KL(H2=585E5E
6T6T,77* 7* *7 %* LM(H2=585E5E
6T6T,77* 7* 6@
6D(.-[
 -:,D)* )* )* %+KK)=(2J+9(=(=+?Q?Q	%& %& %& (36K'K'K(.-:/:,>,>)* )* )* -4J@TVZ,[,[E','8WULdfk=l=l'8+HA+M+M,D04m6N0M-. -. -.)* )* )* )* )* )* )N,6,Q,>,Y-D	)* )* )* 07u>SUY/Z/Z/m^m )W(V(V(V(V(V/D/DTQU/V/V/V-=04-= -= -= )2).7;7O7OPV7W7WH/7 -sFN -s6>mmFNT]hqm6r6r0r0r0r0r0r0r0r/8 ). ). ).,2NN0k05-. -. -. -. -. -. -. -.). */):wuNmos?t?t):5<UDceg5h5h
3:5Bacg3h3h3{l{-bT^ -b -b7?-b -b -b )1).7;7O7OPV7W7WH/7 -rFN -r6>mmFNT\gpm6q6q0q0q0q0q0q0q0q/8 ). ). ).,2NN0i05-. -. -. -. -. -. -. -.). %)$<$<[$I$I$I+@ %*.2.T.T,6@Q /U /* /* )* )* )* )* )* )* )* %)$<$<[$I$I$I+@ %*.2.T.T,6@Q /U /* /* )* )* )* )* )* )* )* )*%*
 %   F         #	7T%=%N%N%P%PPPPPPP #	7N 7              011&&x00E99#GH.@AA : '--.E.E.G.G.M.M.O.OPPPIl]:<NOOOO&--k::: 7 7 7V   #))+666666667  2	D6? 2	Dv(./P/PU[UdhphxUxUx"O1M*=99G H999999BIQJJw//52<<>>>r    QAHPBIg..4";;===b %DK$@$@$Q$Q %$H     
JJJJJJ#FIt<<BIIKKD -	 1 1 !% 11&/BB -',H    D D (.88 &%# *}7J7J7L7L * * (* * *  33FFCCCCCCCCC 33E6;OO 	0%%h/// "NN#	 O 
 
 
 
 
 
 
 
 F	X??????         
 "kmmGe[$77G 7
< = = 74AM W5. 5. 5.1#\':$-~g'BBB$0$<LL, ' //C/E/EFF 	7#1>+."$ $ $LL $7L 	X 	X 	XLLMwWWWWWWWW	X  	R+ 	R00>PQQQ
 	))$$V,,	
 	
 	
|	9 6<_LFO11"!>!>/RHOPVXceiHjHjrSd!C!CDDDpr$V["==C+6'- H *//-::::::::: %2$<!&*n&6&6#!%$-0'-!%!=!=e!D!D$3"5->>%9'="/ "1 " "      L !N,,/FFM
"&":":6"B"B&-))+G' '#  'tO'<'<mTRR" Fx0C'D'D F)DD88"D$@$@$G$G           % F,)?)? F)55fnEEEEEEEEE    //
NKK a%#"  
 "&!9!9&!A!A4//1MtTT`"=="#1 >     $ R@Z([([ R";??
DQQQj ##$788888g $''(899?RH <LII -XXXXXX'J'J (( ($$  - - -',$$$- 9$$-A$. 
 *--j"==N!Y[[?:N%))+q99JHIKK_ ;)
I  *  F|TT 11+>>>2GGTTTTTTTTTT    LL@#R        ( W: (G   <FOXVV -- ,|2LP]Ph2h2h +/DDD/;L/IM,
 ++"NM4L   288:::::::::2OO%0#        
 "+96P          
 KK/ $*s-%0  ,I(**(99$ /@%!H!HII#_3;3F2G- - -))     (*=== E '8%@@ *)) ) &gX &g>R &g!-!1!12B!C!C! $gVVVVVV*0022==??E5zzB,0IIeCRCj,A,A))-VE

R-V-V-VV)),:,@,@,B,B)	2RRRRRR+B+B0220AA-"	, ,(( % 2 2 2+1(((2'944"&)) , ,ARA]A]A_A_, , , # # $Q#P#Ph#P#P)\99"&)) , ,?P?[?[?]?], , , # # $UW#T#T(#T#T -K,JK\,],])#f@Q#f#f\d#f#f L"LLLLLL#t 4 6 6!5fo!F!F&**733#/#3#34H!#L#L#QPQ#/#3#34D#E#E#M
~r::!.       " " ">LLL!"  ; ;1A1A.1Q1Q ;Zn ;&::L:: *//+ 00X^TcT20 0         CCCCCCC ,<46 1"+H"5"5 / /JAw'(A(A'(J(JKKK3w"}}%mA........./  C C C>BBBBBBBBC?JJJJJJ ;C<P Q Q( W WC!Ec!J!JJ! WW"&"A"A*c"R"RRRRRRRRR( W W W"LL)QSUVVVVVVVVWWW  ? ? ?:A>>>>>>>>?2 "&l&6&6x&@&@!A!A*V+ +' %((8(8"(E(E$F$F$L$L$N$N!
 += 
+\%%&=>>?? J     <     J 22Hs7||b7H ( + L!,   
 $ M!,   
 - )!, $$W.EFF	  "  677 *I 1>FM,,3	    !!"9:: #} #Q\ #M!,   #'":"H"H"U"UUUUUUU	((555 ..(E /    ( %.M!+96S          %ND B
 +  (,,Wb99	.CC!, .!*b!7!9!9=C_$TFO$9$9RT%' 	 	 	 	 	 	 	 	 	* +../@$BRZ^B^__O + e# c'B c # 0; -,) 2= /.  # F03E4D0E0EK-
 $ "6NN%0#e6F2G2G         ! KK8(-*B    2GG%0# / H           +../?WNN?B>?R?RU`?`?`~kll;;fh $ 2 &  4? 10!-  6A 32!## #K ' J478H4I4IL12GG%0# / H         
   "6KK)4%0XTVWW$3 L          -2)+  776??h66$ 83 8R 8 8 59 #6 9 9 % 0 !: ,E 9 925e6F2G2GE,/481"6KK)4e$3 L           *99)#/#3#34H!#L#L :         . 99]5         $ K!,    !!1!1.!A!ABBM 44V<<MT) Hi0OQhQhiiju  xF  G  G  H  H  
 (>11%>`m1nn> ,,UH========= // 8H8H8R8R  %)%=%=f%E%EN% "??$e^           
L	L(,(@(@(H(H( "/"4"4 & ,)-)I)I&RVRnRnotRuRu)v)v #5 # #       
 % L L L%FKKKKKKKKLn ##$788888k j ##$78888g  p	 p	 p	#77??&-&&(Dd' '#  'tL'9'9=$OO CH-@$A$A C&AA88"D$@$@$G$G           " Ch|&<&< C&226>BBBBBBBBB   8+FFF%l!VXX--,2J}Oh).&0373K3[3[\i\t3u3u-u-u-u-u-u-u**$ 0 0 0-/***0 ();CDD)A B B " "88F++v55 $8#C !5 4%1 3
 37((92E2EI_2_.!E 6 . $* $8#C !5 4%1 $:#E !7 6%)Y[[' ' #5,== N8;E<L8M8MK5"6KK)4'          l l l[fjkkkkkl K!!]D99K(1VXX(=(=G1Ic!!h##g###Az488		 ,$-NN$4$4$8$8"$E$E	))T:: +(*I    D==((,AAA!*/B!C!CJ! pj1nn#!%:+<!=!=&lbh&l&l&l&o"dKK##]
** r>>1    ##$788888 !C''"IKDK D D D     ##$78888gp	f ##$78888sl  E 
E%$E%2AJ (J-,J-! L )L.-L.<!O &PPAU	 	
UU&V7 7WW)C#\> )[7 6\> 7
\\> \9\> >
]-]((]-6Cb
 

b:b55b:Bu 'h7 6u 7iu 
iB+u 7l u l# u "l##u >m u m*'u )m**u n u n1.u 0n11*u o4 3u 4pu p	u A7r
 	u 

ru ru r< ;u <su 
su s( 'u (6t!u  t!!"u u uu uu 
u)(u)%x6 6yy0A4A\ %%~ 
A\ 
%~?:A\ ?AA\ @BA[	 B*9AF C$1AD DAF DA(AFE>AF F AFFAF FA[	 FDAMJAAK KAMK 
ALK*AL
LAML
ALLAMLA[	 L;AMMHA[	 U+AAV- V,A[	 V-
AWV7AWWA[	 WAWWAA[	 X AAY" Y!A[	 Y"
AZY,AZZA[	 ZAZZA[	 Z5A\ [	7A\ \ A\ \
A\3\A\.\.A\3]BA_, _,
A`0_60A`+`+A`0b)Ab5 b5AccAcc7#Ad d
Ad(d'Ad(d.AAf f
AffAfh=BAk k
AlkAk<k<Alm	DBq q%CAu uBq u
AuuBq uAuuB0Bq x)Bq yAy yBq yAy%y"Bq y$Ay%y%B+Bq | A|2 |1Bq |2
A}"|<A}}Bq }A}"}"D#Bq BA"BC) C(Bq C)3BDDBq DBDDB.Bq G3BH HBq HBHHBq HBHHBBq J*BBL? L>Bq L?
BM0M	BM+M&Bq M+BM0M0ABq OA4BP< P;Bq P<
BQ+QBQ&Q!Bq Q&BQ+Q+Bq Q/1BS2 R!BR>R=BS2 R>
BS-SBS(S#BS2 S(BS-S-BS2 S1Bq S2
BT!S<BTTBq TBT!T!Y9Bq nA!Bo= o<Bq o=
Bp-pBp(p#Bq p(Bp-p-Bq qBq qCAq+CBu
u	CAu

BuuCAuBuuCAu7Bzv%Bv9v8Bzv9BwwBzwBwwCBzzCAz'B{z?CA{B{{A,CA|/AB}1}0CA}1
B}>};CA}=B}>}>BCA?CA @CA@,CA@-CA ACAACA ACA&c                    t          t          | dd          dd          rNt          |                     |                    5  |                                 cddd           S # 1 swxY w Y   |                                 S )u  Session-info block for the auto-reset notice, profile-scoped.

        When multiplexing, resolve model/provider/context inside the profile
        serving ``source`` — otherwise the banner advertises the base config's
        model while the session actually runs on the profile's (#59003).
        Mirrors ``_run_agent``'s gating so single-profile gateways never
        enter the scope.

        Call via ``asyncio.to_thread`` from async handlers: under the scope,
        resolution can do blocking work (credential refresh, context-length
        HTTP probes) that must not run on the event loop. The scope is entered
        inside this method, so contextvars behave correctly in the worker
        thread.
        rX   Nr  F)r-   r  r  _format_session_infor-  s     r6   r  z(GatewayRunner._reset_notice_session_infoF  s     744002FNN 	3'(M(Mf(U(UVV 3 300223 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3((***s   A$$A(+A(c                 ^   ddl m}m} t                      }d}d}d}d}d}d}	d}
d}d}	 t	                      }	|	r|	                    di           }t          |t                    r|                    d          p|                    d          }
|                    d          }|(	 t          |          }n# t          t          f$ r Y nw xY w|                    d          pd}|                    d          pd}|}|}	 dd	lm}  ||	          }n%# t          $ r |	                    d
          }Y nw xY wn# t          $ r Y nw xY w	 t                      }|                    d          p|}|                    d          p|}|                    d          }n# t          $ r Y nw xY w|,	 ddlm}  ||
|||||          rd}n# t          $ r d}Y nw xY w|.|r,|r*	 ddlm}  ||||          }|r|}n# t          $ r Y nw xY w |||pd|pd||pd|          }|d}n||k    rd}nd}|dk    r
|dz  dd}n|dk    r	|dz   d}nt%          |          }d| dd|pd d| d| dg}|r$d |v sd!|v sd"|v r|                    d#|            d$                    |          S )%a  Resolve current model config and return a formatted info block.

        Surfaces model, provider, context length, and endpoint so gateway
        users can immediately see if context detection went wrong (e.g.
        local models falling to the 128K default).
        r   )get_model_context_lengthDEFAULT_FALLBACK_CONTEXTNr  r(  r3  r  r  rZ  r\  r  )should_clear_context_pinr_  ra  r   rb  rX   u:   default — set model.context_length in config to overridedetectedi@B r  Mi  Ku   ◆ Model: `r   u   ◆ Provider: 
openrouteru   ◆ Context: z	 tokens (rT  	localhostz	127.0.0.1z0.0.0.0u   ◆ Endpoint: r   )rn  r  r  rb  rQ   rT   rR   rS   rF  rU  rH  rg  r[  r.   r  ro  r  r`  rU   rs   rD   )r  r  r  r  rc  r  r  r  custom_provsr  configured_modelconfigured_providerconfigured_base_urlr  raw_ctxr[  r  r  r`  
custom_ctxr3  
ctx_sourcectx_displayr;  s                           r6   r  z"GatewayRunner._format_session_infoF  sf    	\[[[[[[[&(( $""	'))D @ HHWb11	i.. 3'0}}Y'?'?'Y9==QXCYCY$'mm,<==G*!47LL11 ):6 ! ! ! D!(}}Z88@DH(}}Z88@DH*2'*2'@QQQQQQ#B#B4#H#HLL  @ @ @#'88,>#?#?LLL@ 	 	 	D		355G{{:..:(H{{:..:(Hkk),,GG 	 	 	D	 !,-NNNNNN++$''  1 -1) - - -(,%%%- !(\(h(PPPPPP??%%1  

  7,6)    21^Mr"7^)
 
 
 !,!JJ777UJJ#J Y&&+i7>>>>KKu$$+u4777KKn--K $5###7X577?K??*???
  	600K84K4Ky\dOdOdLL4(44555yys   A<D9 'B7 6D9 7CD9 
C5D9 D D9 D52D9 4D55D9 9
EE
AF 
F)(F)/G GG!G: :
HHcanonical_cmdc                    ddl m} |sdS  || j        |          }|j        r|                    |j        |          rdS t                              d||j        r|j        j	        nd|j                   t          |j                  }|rFdd                    d |dd	         D                       z   t          |          d	k    rd
ndz   dz   }nd}d| d| S )u  Return a denial message if ``source`` cannot run ``canonical_cmd``,
        else None. Used by both the cold and running-agent dispatch paths
        in ``_handle_message`` so admin/user gating can't be bypassed by
        an in-flight agent.

        Backward-compat semantics live in
        :func:`gateway.slash_access.policy_for_source` — when the operator
        hasn't set ``allow_admin_from`` for the scope, the policy returns
        ``enabled=False`` and this method always returns None.
        r   )policy_for_sourceNzLSlash command /%s denied for %s:%s (not admin, not in user_allowed_commands)r  zYou can run: r   c              3       K   | ]	}d | V  
dS )r;  Nr,  )r?   r  s     r6   rA   z4GatewayRunner._check_slash_access.<locals>.<genexpr>G  s(      BBGGGBBBBBBrB   r   rJ  r   z . Use /whoami for the full list.zNo slash commands are enabled for non-admins on this platform. Ask an admin to add you to allow_admin_from or to set user_allowed_commands.u   ⛔ /z is admin-only here. )gateway.slash_accessr  rX   r  can_runr  r/   r  r_   r   r  user_allowed_commandsrD   r   )r  r  r  _policy_for_sourcer  allowed_previewr  s          r6   r  z!GatewayRunner._check_slash_accesscG  s/    	QPPPPP 	4##DK88~ 	!N!N 	4Z%+_=FO!!#N		
 	
 	
 !!=>> 	))BB_SbS-ABBBBBC00255552? 55 F3 
 D}CC6CCCrB   own_keyc           	         t          |dd          }t          |dd          }|r|sg S |j        j        }t          |dd          pd}d                    d||t	          |          t	          |          g          }g }|                                 D ]K\  }	}
|	|k    r|
t          u s|
s|	|k    s|	                    |dz             r|                    |	           L|S )u  Find running-agent keys for OTHER participants in the same thread.

        Only applies when the message originates in a thread.  In per-user
        thread mode (``thread_sessions_per_user=True``) each participant gets
        an isolated session key of the form
        ``agent:main:{platform}:{chat_type}:{chat_id}:{thread_id}:{user_id}``,
        so a run started by another user is invisible to the caller's own
        ``/stop``.  This returns the keys of any *actually running* agents
        (not the pending sentinel, not the caller's own key) whose key shares
        the caller's ``{chat_id}:{thread_id}`` prefix.

        Returns an empty list when the source is not in a thread, or when no
        sibling runs exist — callers must still gate on authorization.
        rd  Nr  r}  r   r  z
agent:main)	r-   r_   r   rD   rU   r#  ri  r   rs   )r  r  r  rd  r  r_   r}  r  matchesr  r   s              r6   _sibling_thread_run_keysz&GatewayRunner._sibling_thread_run_keysG  s    FK66	&)T22 	 	I?(FK66<"	 8YGc)nnM
 
 3355 	$ 	$JCg~~///u/f}}v| < <}s###rB   c                 T   ||j         dS |j        dS |j         j        dS 	 |j         j        j        }n# t          $ r Y dS w xY w|dk    rdS 	 t
          dz  }|                                sEt          | dd          r2t          j                    t          | dd          z
  dk     r	d| _	        d	S dS t          j        |                    d
                    }n# t          $ r Y dS w xY w|                    d          |k    rdS |                    d          }t          |t                    sdS |j        |k    rdS t          | dd          r	d| _	        d	S |                    d          }t          |t          t           f          rt          j                    |z
  dk    rdS d	S )aj  Return True if this /restart is a Telegram re-delivery we already handled.

        The previous gateway wrote ``.restart_last_processed.json`` with the
        triggering platform + update_id when it processed the /restart.  If
        we now see a /restart on the same platform with an update_id <= that
        recorded value, it is a redelivery when this process booted from that
        restart. Otherwise the marker must still be recent (< 5 minutes).

        Only applies to Telegram today (the only platform that exposes a
        numeric cross-session update ordering); other platforms return False.
        NFr7  z.restart_last_processed.jsonrn  rm  r  r  Tr  rJ  r_   	update_idrA  r  )r  platform_update_idr_   r   r.   r;  rw   r-   r,   rn  r  r  r   rT   rR   rF  rG  )r  r  r  marker_pathr  recorded_uidrA  s          r6   _is_stale_restart_redeliveryz*GatewayRunner._is_stale_restart_redeliveryG  s    =EL05#+5< (5	"\28NN 	 	 	55	Z''5	&)GGK%%''  D"8%@@ 	gdOS&I&IIBNN05D-4u:k33W3EEFFDD 	 	 	55	 88J>115xx,,,,, 	5#l225 4/77 	(-D%4
 xx//lS%L11 	y{{\)C//uts(   6 
AAAC 3(C 
C*)C*c                 "  K   |                                 pd                                }|j        }d}	 t          |j        dd          pt          t          |dd          pd          }t          |dd          }|r4|r2|t          |          t          |dd          t          |dd          d}n# t          $ r d}Y nw xY w	 d	d
lm}  |||d          S # t          $ r*}t          
                    d|           d| cY d}~S d}~ww xY w)zHandle /suggestions in the gateway.

        Delegates to the shared handler so CLI and gateway never drift. The
        origin is built from the event source so an accepted suggestion's job
        delivers back to this chat/thread.
        r   Nr   r_   r  r  rd  r_   r  r  rd  r   )handle_suggestions_commandr1   r	  rl	  zsuggestions command failed: %szSuggestions command failed: )r/  rV   r  r-   r_   rU   r.   hermes_cli.suggestions_cmdr  r/   r0   )	r  r  r  r  r	  r_   r  r  rs  s	            r6   r  z)GatewayRunner._handle_suggestions_commandH  sl      &&((.B5577	v>>l#gfV`bdFeFeFkikBlBlHfi66G G  ("7||!(d!C!C!(d!C!C	   	 	 	FFF		6MMMMMM--d69UUUU 	6 	6 	6LL91===5!55555555	6s0   A=B3 3CCC 
D$D	D	Dc                 @  K   |                                 pd                                }|j        }d}	 t          |j        dd          pt          t          |dd          pd          }t          |dd          }|r4|r2|t          |          t          |dd          t          |dd          d}n# t          $ r d}Y nw xY w	 d	d
lm}  |||d          S # t          $ r9}t          
                    d|           d	dlm}	  |	d|           cY d}~S d}~ww xY w)a
  Handle /blueprint in the gateway.

        Delegates to the shared handler so CLI, TUI, and gateway never drift.
        Returns a BlueprintCommandResult: ``text`` is shown to the user, and if
        ``agent_seed`` is set the dispatch site rewrites ``event.text`` to the
        seed and falls through to the agent (the ``/steer`` pattern) so the
        agent gathers the slot values conversationally. Origin is built from the
        event source so a directly created blueprint job delivers back to this chat.
        r   Nr   r_   r  r  rd  r  r   )handle_blueprint_commandr1   r  zblueprint command failed: %s)BlueprintCommandResultzCron blueprint command failed: )r/  rV   r  r-   r_   rU   r.   hermes_cli.blueprint_cmdr	  r/   r0   r
  )
r  r  r  r  r	  r_   r  r	  rs  r
  s
             r6   r  z'GatewayRunner._handle_blueprint_command4H  s      &&((.B5577	v>>l#gfV`bdFeFeFkikBlBlHfi66G G  ("7||!(d!C!C!(d!C!C	   	 	 	FFF		QIIIIII++DSSSS 	Q 	Q 	QLL7;;;GGGGGG))*OA*O*OPPPPPPPP		Qs0   A=B3 3CCC 
D$.DDDc                 `   	 t          | j        t                    r| j        pi                     di           nt	          | j        di           pi }|s'ddlm}  |            pi                     d          pi }t          |                    dd          pd          S # t          $ r Y dS w xY w)a%  Resolve the configured /goal turn budget for gateway sessions.

        GatewayRunner.config is a GatewayConfig dataclass, not the full
        user config mapping. Top-level config blocks such as ``goals`` are
        therefore only available through hermes_cli.config.load_config().
        goalsr   r7  r`  rI  )	rR   rX   rS   rT   r-   rg  r8  rF  r.   )r  	goals_cfgr8  s      r6   _goal_max_turns_from_configz)GatewayRunner._goal_max_turns_from_configZH  s    	 dk400="''444T['266<" 
  E999999([]]0b55g>>D"	y}}["55;<<< 	 	 	22	s   BB 
B-,B-c                   K   	 ddl m} n3# t          $ r&}t                              d|           Y d}~dS d}~ww xY w	 | j                            |j                   d{V }n3# t          $ r&}t                              d|           Y d}~dS d}~ww xY wt          |dd          pd}|sdS | 	                                } |||	          |fS )
zReturn a GoalManager bound to the session for this gateway event.

        Returns ``(manager, session_entry)`` or ``(None, None)`` if the
        goals module can't be loaded.
        r   r  zgoal manager unavailable: %sNr  z'goal manager: session lookup failed: %sr%   r   r%   default_max_turns)
r  r  r.   r/   r0   r	  r  r  r-   r  )r  r  r  r5   r1  sidr`  s          r6   _get_goal_manager_for_eventz)GatewayRunner._get_goal_manager_for_eventoH  s%     	4444444 	 	 	LL7===:::::		"&":"P"PQVQ]"^"^^^^^^^MM 	 	 	LLBCHHH:::::	 m\488>B 	:4466	{cYGGGVVs'    
;6;%A% %
B/BBr  c                   K   |                      |          }|s,t                              dt          |dd                     dS 	 |                     |          }n# t
          $ r d}Y nw xY w|                    |j        ||           d{V }|=t          |dd          s.t                              dt          |dd	                     dS dS dS )
zCSend a /goal judge status line back to the originating chat/thread.$goal continuation: no adapter for %sr_   Nr  r  T)goal continuation: status send failed: %sr  r  )	r	  r/   r0   r-   r	  r.   r  r  r   )r  r  r  r  r   r  s         r6   _send_goal_status_noticez&GatewayRunner._send_goal_status_noticeH  s     **622 	LL?Q[]aAbAbcccF	77??HH 	 	 	HHH	 ||FNGh|OOOOOOOOgfi&F&FNN;99     s   A A,+A,c                 H   K                                   }|s,t                              dt          dd                     dS d fd}	                                }n# t
          $ r d}Y nw xY w|rt          |d          r	 d}t          |di                               |          }|t          |dd          }|                    |||	           dS # t
          $ r%}t                              d
|           Y d}~nd}~ww xY w |             d{V  dS )a  Send a /goal status line after the main response is delivered.

        The gateway message handler returns the agent response to the platform
        adapter, which sends it after this method's caller has returned.  For a
        natural Discord/Telegram reading order, goal status belongs after that
        send.  Platform adapters provide a one-shot post-delivery callback for
        exactly this boundary; when unavailable, fall back to direct awaited
        delivery rather than silently dropping the notice.
        r  r_   Nr'   c                     K   	                                 d {V  d S # t          $ r(} t                              d| d           Y d } ~ d S d } ~ ww xY w)Nr  Tr   )r  r.   r/   r   )r5   r  r  r  s    r6   _deliverzHGatewayRunner._defer_goal_status_notice_after_delivery.<locals>._deliverH  s      `33FGDDDDDDDDDDD ` ` `JCZ^_________`s   # 
AAAr  _active_sessions_hermes_run_generationr  zAgoal continuation: post-delivery callback registration failed: %srX  )	r	  r/   r0   r-   r  r.   r   rT   r  )	r  r  r  r  r  r  r  r  r5   s	   ```      r6   (_defer_goal_status_notice_after_deliveryz6GatewayRunner._defer_goal_status_notice_after_deliveryH  s      **622 	LL?Q[]aAbAbcccF	` 	` 	` 	` 	` 	` 	` 	`	66v>>KK 	 	 	KKK	  	g77,MNN 	gg!
 *<bAAEEkRR%!(1I4!P!PJ77) 8   
  g g g`beffffffffg hjjs+   A( (A76A7AC   
D*D

Dr  c                  K   	 ddl m} n3# t          $ r&}t                              d|           Y d}~dS d}~ww xY wt          |dd          pd}|sdS |                                 } |||          }|                                sdS 	 ddl m}	  |	            }
n# t          $ r d}
Y nw xY w|	                    |pdd	|

          }|
                    d          pd}|r||                     ||           d{V  |
                    d          sdS |
                    d          pd}|r|dS 	 |                     |          }|                     |          }|r9|r9t          |t          j        |dd          }|                     |||           dS dS dS # t          $ r&}t                              d|           Y d}~dS d}~ww xY w)a  Run the goal judge after a gateway turn and, if still active,
        enqueue a continuation prompt for the same session.

        Called from ``_handle_message_with_agent`` at turn boundary, AFTER
        the response has been delivered. Safe when no goal is set.

        We use the adapter's pending-message / FIFO machinery so any real
        user message that arrives simultaneously is handled by the same
        queue and takes priority naturally.
        r   r  z/goal continuation: goals module unavailable: %sNr%   r   r  )gather_background_processesT)user_initiatedbackground_processesr  should_continuecontinuation_prompt)r   r  r  r4  r  z%goal continuation: enqueue failed: %s)r  r  r.   r/   r0   r-   r  r  r   evaluate_after_turnrT   r  r	  r  r:  r;  r	  r  )r  r1  r  r  r  r5   r  r`  mgr
_gather_bg	_bg_procsr\  r|  r	  r  r  
cont_events                    r6   r  z*GatewayRunner._post_turn_goal_continuationH  s     "	4444444 	 	 	LLJCPPPFFFFF	 m\488>B 	F4466	kSIFFF}} 	F	RRRRRR"
II 	 	 	III	 ** b!* + 
 

 ll9%%+  	M6%??LLLLLLLLL||-.. 	F344: 	F	G..v66G55f==J D: D)!,!1!##'  
 "":z7CCCCCD D D D  	G 	G 	GLL@#FFFFFFFFF	Gs;    
;6;B B-,B-6A#F 
G)G

Gc                     t          | dd          }|dS t          |d          r|j        rt          |j                  S t          |d          r|j        r|j        j        S dS )z5Extract Discord guild_id from the raw message object.r(  Nguild_idguild)r-   r   r+  rF  r,  r   )r  rV  s     r6   _get_guild_idzGatewayRunner._get_guild_idI  st     e]D11;43
## 	% 	%s|$$$3   	 SY 	 9<trB   c                 d   K                         |j                  }t          |d          sdS                      |          }|sdS |                    ||j        j                   d{V }|sdS t          |d          r j        |_        t          |d          r j        |_	        t          |d          r
 fd	|_
        	 |                    |           d{V }n# t          $ rs}t                              d
|           d|_        t          |                                          }d|v sd|v sd|v rdt"          j         dcY d}~S d| cY d}~S d}~ww xY w|rt'          |j        j                  |j        |<   t          |d          r!|j                                        |j        |<   d j                             |j        j        |j        j                  <                                                          ||j        j        d           d|j         dS d|_        dS )z.Join the user's current Discord voice channel.join_voice_channelz2Voice channels are not supported on this platform.z,This command only works in a Discord server.Nz(You need to be in a voice channel first.r  _on_voice_disconnect_voice_mode_getterc                     j                                                 t          j        t          |                     d          S )Nr  )r  rT   r  r  r|  rU   )r  r  s    r6   r   z:GatewayRunner._handle_voice_channel_join.<locals>.<lambda>>I  s6    9I9M9M 0#g,,??: : rB   z Failed to join voice channel: %spynaclnacldaveyz@Voice dependencies are missing (PyNaCl / davey). Install with: `z -m pip install PyNaCl`zFailed to join voice channel: _voice_sourcesr  T)r  zJoined voice channel **zL**.
I'll speak my replies and listen to you. Use /voice leave to disconnect.zFFailed to join voice channel. Check bot permissions (Connect + Speak).)r	  r  r   r-  get_user_voice_channelr  rX  r  _handle_voice_timeout_cleanupr0  r1  r/  r.   r/   r   rU   rW   rm   rv  rF  r  _voice_text_channelsto_dictr6  r  r  r_   r  r  r   )r  r  r  r+  voice_channelr  rs  	err_lowers   `       r6   _handle_voice_channel_joinz(GatewayRunner._handle_voice_channel_join%I  s     **5<88w 455 	HGG%%e,, 	BAA%<<el*
 
 
 
 
 
 
 
  	>== 7344 	M,0,LG)7233 	N+/+MG( 7011 	* * * *G&	8#66}EEEEEEEEGG 		8 		8 		8NN=qAAA,0G)AI9$$)(;(;w)?S?SN&)nN N N      8A77777777		8  
	589M5N5NG(2w 011 J38<3G3G3I3I&x0]bDT__U\-BELDXYYZ""$$$..w8LVZ.[[[\-*< \ \ \
 )-%WWs+   C" "
E,AE
EEEEc                 z  K   |                      |j                  }|                     |          }|rt          |d          sdS t          |d          r|                    |          sdS 	 |                    |           d{V  n2# t          $ r%}t                              d|           Y d}~nd}~ww xY wd| j	        | 
                    |j        j        |j        j                  <   |                                  |                     ||j        j        d           t          |d	          rd|_        d
S )z Leave the Discord voice channel.leave_voice_channelzNot in a voice channel.is_in_voice_channelNzError leaving voice channel: %sr  Tr2  r  zLeft voice channel.)r	  r  r-  r   r@  r?  r.   r/   r   r  r  r_   r  r  r  r  )r  r  r  r+  rs  s        r6   _handle_voice_channel_leavez)GatewayRunner._handle_voice_channel_leave^I  sp     **5<88%%e,, 	-ww0EFF 	-,,w 566 	-g>Y>YZb>c>c 	-,,	A--h7777777777 	A 	A 	ANN<a@@@@@@@@	A Z_)>@TUUV   ++GU\5ITX+YYY7344 	1,0G)$$s   .B
 

B9B44B9c                     d| j         |                     t          j        |          <   |                                  | j                            t          j                  }|                     ||d           dS )zCalled by the adapter when a voice channel times out.

        Cleans up runner-side voice_mode state that the adapter cannot reach.
        r  TrA  N)r  r  r  r|  r  r{  rT   r  )r  r  r  s      r6   r8  z+GatewayRunner._handle_voice_timeout_cleanupuI  so    
 HM)97CCD   -##H$455++GWt+LLLLLrB   r+  r  r  c                    ddl m} t          j        dd|                                                                          }t          j        dd|          }|sdS t          j                    d||f}t          | d	d
          }t          |t                    s	i }|| _        fd|                    |g           D             }|D ]d\  }	}
|
|k    r|||<    dS t          |
          dk    r>t          |          dk    r+ |d
|
|                                          dk    r|||<    dS e|                    |f           |dd
         ||<   dS )ar  Suppress repeated STT outputs for the same recent utterance.

        Voice capture can occasionally emit the same utterance twice a few
        seconds apart, which creates a second queued agent run and overlapping
        spoken replies. Dedup exact and near-exact repeats per guild/user over a
        short window while allowing genuinely new turns through.
        r   )SequenceMatcher\s+rn  z[^\w\s]r   Fg      (@r  Nc                 0    g | ]\  }}|z
  k    ||fS r,  r,  )r?   r  txtra  r  s      r6   r  z@GatewayRunner._is_duplicate_voice_transcript.<locals>.<listcomp>I  s:     
 
 
CRx>)) I)))rB   Tr  r  )difflibrE  r<   r   rV   rW   r,   rb  r-   rR   rS   r  rT   r   ratiors   )r  r+  r  r  rE  r  r  recent_storerecentr  priorra  r  s              @@r6   _is_duplicate_voice_transcriptz,GatewayRunner._is_duplicate_voice_transcriptI  s    	,+++++VFC44::<<BBDD
VJJ77
 	5n!t%@$GG,-- 	:L-9D*
 
 
 
 
'++C44
 
 
  	  	 HAu
""$*S!tt5zzRC
OOr$9$9"?4
;;AACCtKK(.L%44sJ'((("233KSurB   c           	      *  K   | j                             t          j                  }|sdS |j                            |          }|sdS t          |di                               |          }|r=t          j        |          }t          |          |_	        t          |          |_
        nEt          t          j        t          |          t          |          t          |          d          }|                     |          st                              d|           dS |                     |||          r't                              d|||dd                    dS 	 |j                            |          }|rS|dd                             d	d
                              dd          }	|                    d| d|	            d{V  n# t(          $ r Y nw xY wddlm}
 d}t          |dd          }t/          |          rE	  |t          |                    }t1          |t                    r|nd}n# t(          $ r d}Y nw xY wt3          ||t4          j         |
|d          |          }|                    |           d{V  dS )zHandle transcribed voice from a user in a voice channel.

        Creates a synthetic MessageEvent and processes it through the
        adapter's full message pipeline (session, typing, agent, TTS reply).
        Nr6  channel)r_   r  r  r  r}  z/Unauthorized voice input from user %d, ignoringz?Suppressing duplicate voice transcript for guild=%s user=%s: %sr+    z	@everyoneu   @​everyonez@hereu   @​herez**[Voice]** <@z>: r   )SimpleNamespace_resolve_channel_prompt)r+  r,  )r  r   r  r(  r  )r{  rT   r  r|  r9  r-   r%  	from_dictrU   r  r  r	  r/   r0   rO  r  _clientget_channelrJ  r  r.   typesrS  r  rR   r:  r;  r  r
  )r  r+  r  r  r  
text_ch_idsource_datar  rQ  	safe_textrS  r  resolverr4  r  s                  r6   rX  z)GatewayRunner._handle_voice_channel_inputI  s       -##H$455 	F155h??
 	F g'7<<@@JJ 	",[99F \\FN"7||F"!)JGg,,#  F ''// 	LLJGTTTF..x*MM 	KKQ4C4 	   F	o11*==G M&uu-55kCTUU]]^egtuu	ll#KG#K#K	#K#KLLLLLLLLL 	 	 	D	 	*))))) )-7$=tDDH 	&&#8C
OO44-7#-F-F!PD & & &!%&$*'FFF)
 
 
 $$U+++++++++++s%   "A/G 
GG1H= =IIr  r  r  c                 ^   |r|                     d          rdS |j        j        }|                     |j        j        |          }| j                            |          }|j        t          j	        k    }| j
                            |j        j                  }	d}
|	rFt          |	d          r6	 t          |	                    |                    }
n# t          $ r d}
Y nw xY w|dk    p|dk    o|p|du o|
}|s/t                              d||
||j        j        j                   dS d}t%          t'          |                    D ]5\  }}|                    d          d	k    rt)          |          d
z
  |z
  } n6|
||d         n|}t+          d |D                       }|rdS |r|sdS dS )a  Decide whether the runner should send a TTS voice reply.

        Returns False when:
        - voice_mode is off for this chat
        - response is empty or an error
        - agent already called text_to_speech tool (dedup)
        - voice input and base adapter auto-TTS already handled it (skip_double)
          UNLESS streaming already consumed the response (already_sent=True),
          in which case the base adapter won't have text for auto-TTS so the
          runner must handle it.
        zError:F_should_auto_tts_for_chatr  r  NzIAuto voice reply skipped: mode=%s adapter_auto_tts=%s chat=%s platform=%sr{  r  rk   c              3      K   | ]K}|                     d           dk    o-t          d |                     d          pg D                       V  LdS )r{  r  c              3   r   K   | ]2}|                     d           pi                      d          dk    V  3dS )r  r   r  Nr)  )r?   tcs     r6   rA   zCGatewayRunner._should_send_voice_reply.<locals>.<genexpr>.<genexpr>0J  s[         
##)r..v66:JJ     rB   r  N)rT   r  )r?   r|  s     r6   rA   z9GatewayRunner._should_send_voice_reply.<locals>.<genexpr>.J  s       
 
  GGFOO{*   77<006B    
 
 
 
 
 
rB   T)r   r  r  r  r_   r  rT   r  r;  r  r{  r   r   r^  r.   r/   r0   r   r  r  r   r  )r  r  r  r  r  r  	voice_key
voice_modeis_voice_inputr  adapter_auto_ttsshouldlast_user_idxr  r|  turn_messageshas_agent_ttss                    r6   r9  z&GatewayRunner._should_send_voice_replyI  s6   $  	8..x88 	5,&OOEL$97CC	%)))44
,0AA-##EL$9::  	)ww(CDD 	))#'(I(I'(R(R#S#S   ) ) )#(   ) 5  9l*=~9
 d"7'7 	  	LL[,gu|7L7R   5  8 899 	C 	CFAswwv&(( #N 3 3a 7! ;UU ):G:S}~~66Yg 
 
 %
 
 
 
 
  	5  	, 	5ts   ."C C C c                 H    t          t          | j        dd                    S )zFReturn whether inbound voice/STT transcripts should be echoed to chat.stt_echo_transcriptsT)r   r-   rX   r"  s    r6   ri  z*GatewayRunner._should_echo_stt_transcriptsCJ  s    GDK)?FFGGGrB   r   c                   K   d}d}	 ddl m}m}  ||dd                   }|s3	 ||hdhz
  D ]'}	 t          j        |           # t
          $ r Y $w xY wdS t          |j        j                  }t          j
        |||           d{V }		 t          j        |	          }
nt# t          j        t          f$ r[ t                              d|	r
|	dd         n|	           Y ||hdhz
  D ]'}	 t          j        |           # t
          $ r Y $w xY wdS w xY w|
                    d|          }|
                    d	          rt          j                            |          sat                              d
|
                    d                     	 ||hdhz
  D ]'}	 t          j        |           # t
          $ r Y $w xY wdS |                     |j                  }|                     |          }|rRt-          |d          rBt-          |d          r2|                    |          r|                    ||           d{V  n|rt-          |d          ro|                     |          }|                     |j        |          }|t7          |          }d|d<   nddi}|j        j        |||d} |j        di | d{V  n4# t<          $ r'}t                              d|d           Y d}~nd}~ww xY w||hdhz
  D ]'}	 t          j        |           # t
          $ r Y $w xY wdS # ||hdhz
  D ]'}	 t          j        |           # t
          $ r Y $w xY ww xY w)zEGenerate TTS audio and send as a voice message before the text reply.Nr   )r  _strip_markdown_for_ttsr*  )r   output_pathz.Auto voice reply TTS returned invalid JSON: %sr   r	  r  zAuto voice reply TTS failed: %sr  play_in_voice_channelr@  
send_voiceTr  )r  
audio_pathrJ  r   zAuto voice reply failed: %sr   r,  )tools.tts_toolr  rm  rq   rD  ru   r>  r  r_   r  r  r  r  r  rU  r/   r   rT   rx   isfiler	  r-  r   r@  ro  r=  r	  rS   r  rp  r.   )r  r  r   rq  actual_pathr  rm  tts_textr  result_jsonr  r  r+  r	  r	  send_kwargsrs  s                    r6   r:  zGatewayRunner._send_voice_replyGJ  s     
C	SSSSSSSS..tETE{;;H t !+.$7  IaLLLL   D g 4EL4IJJJ ' 1#(
! ! !      KK00()4   Ofq  RCQ\]a^a]aQbQb  xC  D  D  DT !+.$7  IaLLLL   D Y
 !**[*==K::i(( {0K0K @&**WBUBUVVVH !+.$7  IaLLLL   D E ..u|<<G ))%00H 8)@AA8)>??8  33H==8 33HkJJJJJJJJJJ 8WWl;; 8#;;EBB">>u|\ZZ *"&{"3"3K,0K))#+T"2K$|3"- , +	/ / )g(77;777777777 	L 	L 	LNN8!dNKKKKKKKK	L !+.$7  IaLLLL   D j+.$7  IaLLLL   Ds   K A
AA6K B$ #K $=D!K -D
DDDA;K F11
F>=F>DK L. 
K9K4/L. 4K99L. L
L)(L).M :MM 
M	M M	M c                 &  K   ddl m} ddlm 	 d|v }ddlm}m} |                    |          \  }}	 |j        |          }|	                    |	           | 
                    |j        |                     |                    }
h d}h d}g }g }|D ]\\  }} ||          j                                        }||v r|s|s|                    |           E|                    ||f           ]|rp	 fd|D             }|                    |j        j        ||
	           d
{V  n8# t$          $ r+}t&                              d|j        |           Y d
}~nd
}~ww xY w|D ]\  }}	  ||          j                                        } ||j        j        ||          r)|                    |j        j        ||
           d
{V  nU||v r)|                    |j        j        ||
           d
{V  n(|                    |j        j        ||
           d
{V  # t$          $ r+}t&                              d|j        |           Y d
}~d
}~ww xY wd
S # t$          $ r&}t&                              d|           Y d
}~d
S d
}~ww xY w)u  Extract explicit MEDIA: tags from a response and deliver them.

        Called after streaming has already sent the text to the user, so the
        text itself is already delivered — this only handles file attachments
        that the normal _process_message_background path would have caught.

        Unlike the non-streaming path in ``gateway/platforms/base.py`` (which
        also auto-detects bare local paths via ``extract_local_files``), this
        post-stream rescan is EXPLICIT-ONLY. The visible reply has already
        been streamed verbatim, so a bare path string here was either (a)
        already shown to the user as text, or (b) stale tool/inspected
        content that was never part of the intended visible reply. Promoting
        such paths into uploads after the fact sent files the model never
        asked to deliver (#20834). Only ``MEDIA:`` directives — the explicit
        attachment contract — trigger post-stream uploads.
        r   r   )rO
  z[[as_document]])r  should_send_media_as_audio   .3gp.avi.mkv.mov.mp4.webm   .gif.jpg.png.jpeg.webpc                 0    g | ]}d  |           dfS )zfile://r   r,  )r?   r  _quotes     r6   r  z>GatewayRunner._deliver_media_from_response.<locals>.<listcomp>J  s/    OOOa444b9OOOrB   )r  imagesr   Nz0[%s] Post-stream image batch delivery failed: %s)is_voicer  rq  r   r  
video_pathr   r  r	  r   z*[%s] Post-stream media delivery failed: %sz'Post-stream media extraction failed: %s)pathlibr   urllib.parserO
  r  r  ry  r  filter_media_delivery_pathsextract_imagesr	  r  r=  r  rW   rs   send_multiple_imagesr  r.   r/   r   r   r_   rp  
send_videosend_document)r  r  r  r  r   force_document_attachmentsr  ry  r  cleaned_thread_meta_VIDEO_EXTS_IMAGE_EXTSrz  non_image_media
media_pathr  r  r  rs  r  s                       @r6   r;  z*GatewayRunner._deliver_media_from_responseJ  s%     , 	!     000000R	I
 *;h)F&^^^^^^^^#*#8#8#B#B KI-I+VVK ""7+++;;EL$JfJfglJmJmnnLKKKKDDDK !#K$&O(3 C C$
Hd:&&-3355;&& ( ' : '  &&z2222#**J+ABBBB 	hhOOOO;OOOF!66 % 4%!- 7          
 ! h h hNN#UW^Wcefggggggggh )8 b b$
Hb$z**17799C11%,2GW_``` %00$)L$8'1%1 1          
 ++%00$)L$8'1%1 1           &33$)L$8&0%1 4         
 ! b b bNN#OQXQ]_`aaaaaaaab+b b0  	I 	I 	INNDaHHHHHHHHH	Ism   C$I  66D- ,I  -
E"7!EI  E""
I  -B8H&%I  &
I0!II  II   
J*JJr	  r%  r  r  r  r  c           	      B  K   t          t          | dd          dd          s |                     ||||||           d{V S |                     |          }t          |          5  |                     ||||||           d{V cddd           S # 1 swxY w Y   dS )a>  Profile-scoping wrapper around the background agent task.

        When multiplexing is active, resolve the inbound source's profile and
        run the whole task inside ``_profile_runtime_scope`` so credentials
        resolve from that profile's secret scope. Mirrors the pattern in
        ``_run_agent``.
        rX   Nr  F)r-   _run_background_task_innerr  r  )r  r	  r  r  r  r  r  r}  s           r6   _run_background_taskz"GatewayRunner._run_background_taskJ  s3       wtXt446JERR 	88)9:{         <<VDD#L11 	 	88)9:{       	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	s   ' BBBc                    #$%&'()*+,K   ddl m# |pg }|pg }                               }|s#t                              dj                   dS                      |          }	 t                      ,                     ,          \  }	}
|
	                    d          s)|
                    j        d d|	           d{V  dS t          j                  (dd
lm} t           |,(                    %,	                    d          pi }|	                    d          pd$ j        )t#                      '                     |	          ** _                                        _                             ||	|
          +|&|rg }t/          |          D ]L\  }}|t1          |          k     r||         nd}|                    d          r|                    |           M|rP	                      ||           d{V &n2# t8          $ r%}t                              d|           Y d}~nd}~ww xY w#$%&'()* +,fd}                     |           d{V }|r|	                    dd          nd}|s"|r |	                    d          rd|d          }|r|                    |          \  }}ddlm }  |j!        |          }|"                    |          \  }}|dd         t1          |          dk    rdndz   }d| d}|r'|
                    j        ||z   |           d{V  n*|s(|s&|
                    j        |dz   |           d{V  |pg D ]:\  }}	 |#                    j        |||           d{V  +# t8          $ r Y 7w xY wddlm$} h d}h d }|pg D ]\  } }!tJ          j&        '                    |           d!         (                                }"	  |j        |"|!          r$|)                    j        | |"           d{V  ns|"|v r$|*                    j        | |#           d{V  nK|"|v r$|+                    j        | |$           d{V  n#|,                    j        | |%           d{V  # t8          $ r Y w xY wdS |dd         t1          |          dk    rdndz   }|
                    j        d| d&|           d{V  dS # t8          $ rg}t          -                    d'           	 |
                    j        d d(| |           d{V  n# t8          $ r Y n
w xY wY d}~dS Y d}~dS d}~ww xY w))zCExecute a background agent task and deliver the result to the chat.r   r  z0No adapter for platform %s in background task %sN)r  r  r  u   ❌ Background task z, failed: no provider credentials configured.r  _get_platform_toolsr   r  )r  r  r  r   r  z,Background task vision enrichment failed: %sc                  (    d&dd         id         t                    i ddddddd	d
d	j        d                    d          d                    d          d                    d          d                    d          d                    d          d                    dd          d                    d          ddd
j        d
j        d
j        d
j        d
j        d 
j        d!
j	        d"t          	j        d#	j                  d$	                                } 	 |                     %          	                    |            S # 	                    |            w xY w)'Nr  r  r  r  Tr  Fr  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r%   r_   r  r  r  r  r  r}  rd  r3   r*   r  )rU  r  r,  )r]  r]  rT   r  r  r  r  r  r}  rd  r-   r)   rn  r  r'
  )r   rs  r  r  enriched_promptr  r  r  r  r  r  r  r  r  s    r6   r  z:GatewayRunner._run_background_task_inner.<locals>.run_sync_K  sg     $W- + /{;;   $2>	
  $t %*E &6%5 '8&7 &6%5 "&!3!3 '1nn5H&I&I&I ')ffVnnn ')ffX&6&6&6 %'FF7OOO #%&&...  137KU0S0S0S!" .0VV4E-F-F-F#$  'w%& *\'( #NN)* !' 2 2+, %..-. #NN/0 %..12 %..34 %..56  't'7@PQQQ7: $(#?#?#A#A#A; >9 11%4 ' 2  
 11%8888D11%8888s   E: :Fr  r  zError: r  r  r   u&   ✅ Background task complete
Prompt: "z"

r
  z(No response generated))r  r(  captionr   )ry  r  rz  rk   r  r  )r  
image_pathr   r  z"

(No response generated)zBackground task %s failedz	 failed: ).r  rs  r	  r/   r   r_   r	  rQ   rX  rT   r  r  r=  hermes_cli.tools_configr  r  rY  rq  rZ  r[  r\  r]  rc  r  r   r   rs   rg  r.   r&
  r  r  r  r  r  
send_imagery  rq   rx   r  rW   rp  r  send_image_filer  r   )-r  r	  r  r  r  r  r  r  _thread_metadatar  r  r  rl  rz  r  rx   r  rs  r  r  r  r  r  r  text_contentr  headerr(  alt_text_should_send_media_as_audior  r  r  r  r  rs  r  r  r  r  r  r  r  r  r  s-   ` ``                               @@@@@@@@@@r6   r  z(GatewayRunner._run_background_task_innerK  s%	      	&%%%%%%2
!'R**622 	NNMv`ghhhF;;FDTUUv	.00K$($G$G' %H % %!E> "%%i00 llN`7```- #         
 /@@LCCCCCC%&9&9+|&T&TUU#006BI ).A B B Jd'B466N#EEU  F     &6D"!%!C!C6!C!R!RD88WWJ %O Z (44 1 1GAt./#k2B2B.B.BKNNE''11 1#**4000 ZZ040P0P"K1 1 + + + + + + % Z Z Z'UWXYYYYYYYYZ&9 &9 &9 &9 &9 &9 &9 &9 &9 &9 &9 &9 &9 &9 &9 &9 &9P  ==hGGGGGGGGF;AIvzz"2B777rH 7 76::g+>+> 76VG_66  M(/(=(=h(G(G%XFFFFFFM1MkZZ'.'='=h'G'G$ "+#f++2B2BKQ7QQQ !,, & & 5!1 '          
    !,, & &)B B!1 '          -3Lb 	 	'Ix%00$*N&/$,%5	 1           %         IHHOOO.9.?R  )J	7++J77:@@BBD66viXX ")"4"4(.+5)9 #5 # #        
 "[00")"4"4(.+5)9 #5 # #        
 "[00")"9"9(.+5)9 #: # #         #*"7"7(.*4)9 #8 # #       
 %   7 < !"+#f++2B2BKll"Nkgkkk- #             		 		 		8'BBBll"NH7HHQHH- #          
          		s   /A$T D*T  H T 
I'IT ID:T $N,+T ,
N96T 8N99AT B)R54T 5
S?T ST A	T 
VU>8)U"!U>"
U/,U>.U//U>>Vc                 b  K   |                      |          }t          |dd          }|t          |d          sddiS 	 |                                 d{V n0# t          $ r# t
                              dd           ddicY S w xY wd	t          ffd
}d |d           |d          dS )z?Read Telegram private-topic capability flags via Bot API getMe._botNget_mecheckedFz1Failed to fetch Telegram getMe topic capabilitiesTr   r   c                    t          |           rt          |           S t          dd           }t          |t                    r| |v r|                    |           S t          t                    r                    |           S d S )N
api_kwargs)r   r-   rR   rS   rT   )r   r  mes     r6   _fieldz>GatewayRunner._get_telegram_topic_capabilities.<locals>._fieldK  s    r4   )r4((( \488J*d++ ,
0B0B!~~d+++"d## $vvd||#4rB   has_topics_enabledallows_users_to_create_topics)r  r  r  )r	  r-   r   r  r.   r/   r0   rU   )r  r  r  botr  r  s        @r6    _get_telegram_topic_capabilitiesz.GatewayRunner._get_telegram_topic_capabilitiesK  s     **622gvt,,;gc844;u%%	&zz||######BB 	& 	& 	&LLLW[L\\\u%%%%	&	 	 	 	 	 	 	 "(&)=">">-3V4S-T-T
 
 	
s   A *B	B	c                 H  K   |                      |          }||j        sdS d}t          |dd          }t          |          rR	  |t	          |j                  d           d{V }n,# t
          $ r t                              dd           Y nw xY w|sdS d}	 |                    |j        ddt          |          i	           d{V }t          |d
d          }n,# t
          $ r t                              dd           Y nw xY w|sdS t          |dd          }|t          |d          sdS 	 |                    t	          |j                  t	          |          d           d{V  dS # t
          $ r  t                              dd           Y dS w xY w)zJCreate/pin the managed System topic after /topic activation when possible.N_create_dm_topicSystemz&Failed to create Telegram System topicTr   z,System topic for Hermes commands and status.rd  r  r4  z*Failed to send Telegram System topic intror  pin_chat_message)r  r4  disable_notificationz)Failed to pin Telegram System topic intro)r	  r  r-   r  rF  r.   r/   r0   r  rU   r   r  )r  r  r  rd  create_topicr4  send_resultr  s           r6   _ensure_telegram_system_topicz+GatewayRunner._ensure_telegram_system_topic
L  sU     **622?&.?F	w(:DAAL!! 	VV".,s6>/B/BH"M"MMMMMMM		 V V VEPTUUUUUV 	F
	V '>%s9~~6 !- ! !      K
 !lDAAJJ 	V 	V 	VLLEPTLUUUUU	V 	Fgvt,,;gc+=>>;F	U&&FN++z??%) '           
  	U 	U 	ULLDtLTTTTTT	Us7   $A+ +&BBAC" "&D
D8=E7 7&F! F!c           	        K   |                      |          }||j        rt          |d          sdS t          t                                                    j        dz  dz  }|                                sdS 	 |                    |j        t          |          d|j
        rdt          |j
                  ind           d{V  dS # t          $ r  t                              dd	
           Y dS w xY w)zFSend the bundled BotFather Threads Settings screenshot when available.Nr  assetsz'telegram-botfather-threads-settings.jpgu/   BotFather → Bot Settings → Threads Settingsrd  )r  r  r  r   z)Failed to send Telegram topic setup imageTr   )r	  r  r   r   rn   ro   rp   rw   r  rU   rd  r.   r/   r0   )r  r  r  r  s       r6    _send_telegram_topic_setup_imagez.GatewayRunner._send_telegram_topic_setup_image3L  s4     **622?&.?IZ8[8[?F(^^++--4x?Bkk
  "" 	F	U))z??IAGAQ[+s6+;'<'<==W[	 *             	U 	U 	ULLDtLTTTTTT	Us   ;AC &C54C5rL  c                     t          j        ddt          |pd                                                    }|sdS t	          |          dk    r|dd                                         dz   }|S )	zFReturn a Bot API-safe forum topic name from a generated session title.rF  rn  r   Hermes Chatx   Nu   r   )r<   r   rU   rV   r   r  r  rL  r  s      r6   _sanitize_telegram_topic_titlez,GatewayRunner._sanitize_telegram_topic_titleEL  sp    &c%+2&6&677==?? 	! = w<<#dsdm**,,u4GrB   c                     |j         t          j        k    oZ|j        dk    oOt	          t          |dd                    o1t	          |j                  ot	          t          |dd                    S )z>Return True only for Discord threads Hermes just auto-created.r  auto_thread_createdFauto_thread_initial_nameN)r_   r  r|  r}  r   r-   rd  r-  s     r6   r  z*GatewayRunner._is_discord_auto_thread_lanePL  s{     Ox// H H,HWV%:EBBCCH V%&&H WV%?FFGG	
rB   c                     |j         t          j        k    o7t          |j                  o#|j         o|j        dv ot          |dd          du S )aT  Shape-only check: a relay-delivered Discord CHANNEL event whose
        reply the connector MAY auto-thread (title-turn registration gate).

        Deliberately does NOT consult the send-result cache: at registration
        time (before delivery) the feedback can't exist yet. The rename lane
        polls the cache at fire time instead.)r   rQ  delivered_via_upstream_relayFT)r_   r  r|  r   r  rd  r}  r-   r-  s     r6   r  z,GatewayRunner._is_relay_discord_channel_laneZL  si     Ox// OV^$$O$$O  $88O  >FF$N	
rB   c                 L   |j         t          j        k    s|j        sdS t	          |dd          sdS t	          |dd          }|rt          |          dfS |                     |          }t	          |dd          }t          |          sdS 	  |t          |j                            }t          |t                    rSt          |          dk    r@t          d |D                       r't          t          t
          t
          f         |          S dS # t          $ r Y dS w xY w)	uT  (thread_id, initial_name) when the RELAY connector auto-threaded our
        reply to this source's chat — the title-turn sibling of
        _is_discord_auto_thread_lane.

        The marker-based check above only lights up for events ARRIVING IN an
        auto-created thread (turn 2+). The auto-title fires on the FIRST
        exchange, whose source is the PARENT channel event — the thread did
        not exist at ingest, so no markers can be present and the native lane
        check never matches on the relay title turn (staging repro
        2026-07-29: initial titles fine, semantic renames never happened).

        Preferred path: the connector stamps ``prospective_thread_id`` on the
        inbound (the anchor message id, which IS the id of the thread it will
        auto-create). It's deterministic and per-message, so it identifies the
        EXACT thread even when several auto-threads spawn from one channel —
        unlike the send-result cache below, which held a single slot per parent
        chat and so only the FIRST thread in a channel ever renamed (staging
        repro 2026-08-02: thread A renamed, sibling thread B stuck at raw
        text). The connector's own created-name guard (prefer_connector_created)
        enforces no-clobber, so no initial name is needed here.

        Fallback: the connector reports where the reply actually landed on the
        send result (contract §SendResult thread_id/auto_thread_name); the
        relay adapter caches it per chat and this reads it back — kept for
        older connectors that don't stamp prospective_thread_id.
        Nr  Fprospective_thread_idr   auto_thread_info_for_chatr  c              3   @   K   | ]}t          |t                    V  d S r;   r  )r?   xs     r6   rA   z8GatewayRunner._relay_auto_thread_info.<locals>.<genexpr>L  s,      99q
1c**999999rB   )r_   r  r|  r  r-   rU   r	  r  rR   ra  r   r  r   r   r.   )r  r  prospectiver  info_fnr  s         r6   _relay_auto_thread_infoz%GatewayRunner._relay_auto_thread_infoiL  sB   : ?h...fn.4v=uEE 	4f&=tDD 	* $$b))**622'#>EE   	4
	73v~..//D4''3IINN99D99999 # E#s(OT2224 	 	 	44	s   BD 
D#"D#c                     t          j        ddt          |pd                                                    }|sdS t	          |          dk    r%t          |d                                          dz   }|S )a  Return a Discord-safe semantic thread title from a session title.

        Discord thread names are capped at 100 characters measured in UTF-16
        code units (emoji count double), so truncate with the UTF-16 helpers
        rather than Python code-point slices.
        rF  rn  r   r  r  M   r   )r<   r   rU   rV   r@  r<  r  r  s      r6   _sanitize_discord_thread_titlez,GatewayRunner._sanitize_discord_thread_titleL  st     &c%+2&6&677==?? 	! =W""0"==DDFFNGrB   
relay_infoc                   K   |t          j        | j        |           d{V s`|                     |          sdS t	          d          D ]5}|                     |          }| nt          j        d           d{V  6|dS t          | dd          r|                     |          nd}|dS t          |dd          }|dS |r|d         nt          |j
                  }|du}	|	rdnt          |dd          }
|                     |          }|	r|j        rt          |j                  nd}t                              d||	rd	nd
|           	  ||||	|
|           d{V }t                              d|t          |                     dS # t           $ r  t                              dd           Y dS w xY w)u  Best-effort semantic rename of a newly auto-created Discord thread.

        ``relay_info`` is the (thread_id, initial_name) pair from the relay
        connector's send-result feedback — supplied on the title turn, where
        the source is the parent-channel event and carries no auto-thread
        markers (see _relay_auto_thread_info). When absent, the native
        marker-based lane supplies thread identity from the source itself.
        NrI        ?r{  rename_threadr   r  z:discord auto-thread rename: thread=%s lane=%s new_title=%rrelayrC  )prefer_connector_createdonly_if_current_namer  z7discord auto-thread rename result: thread=%s applied=%sz@Failed to rename Discord auto-thread for generated session titleTr   )r  r  r  r  r  r  r`  r-   r	  rU   rd  r  r  r/   r  r   r.   r0   )r  r  r%   rL  r  r  r  r  target_thread_iduse_connector_guard
guard_namer  r  renameds                 r6   -_rename_discord_auto_thread_for_session_titlez;GatewayRunner._rename_discord_auto_thread_for_session_titleL  s      G,=-v-
 -
 '
 '
 '
 '
 '
 '
 66v>> 2YY ) )!99&AA
)EmC((((((((((! 6=dJPT6U6U_$**6222[_?F$?? F,6Q:a==C@P<Q<Q )4 #CDD!;TBB 	
 99%@@ $7S6>SCt 	 	H*8GG		
 	
 	
	l)M )<%/-        G KKI W    
  	l 	l 	lLL[fjLkkkkkk	ls   ?F &F>=F>c                    d}|sdS |                      |          s.|                     |          }||                     |          sdS 	 t          j                    }n!# t
          $ r t          | dd          }Y nw xY w||                                rdS 	 t          j	        |          }n# t          $ r |}Y nw xY wt          |                     ||||          |t          d          }|dS dd}|                    |           dS )	zJSchedule Discord auto-thread rename from the auto-title background thread.Nrg  )r  z1Discord semantic thread rename failed to schedulerw  r'   c                     	 |                                   d S # t          $ r  t                              dd           Y d S w xY w)Nz%Discord semantic thread rename failedTr   r  r.   r/   r0   r  s    r6   _log_rename_failurezSGatewayRunner._schedule_discord_semantic_thread_rename.<locals>._log_rename_failure3M  sX    U

 U U UDtTTTTTTU    &AArX  )r  r  r  r  r	  r  r-   	is_closedr>  rJ  r.   r   r  r/   r  )	r  r  r%   rL  r  r   copied_sourcer   r  s	            r6   rP  z6GatewayRunner._schedule_discord_semantic_thread_renameM  s    
 	F0088 	 55f==J!$*M*M+ +! 	8+--DD 	8 	8 	84$77DDD	8<4>>++<F	#'/77MM 	# 	# 	#"MMM	#)>>z5Z ?   K
 
 
 >F	U 	U 	U 	U 	  !455555s$   A A=<A=B. .B=<B=c                   K   t          j        | j        |           d{V r|j        r|j        sdS |                     |          rdS |                     |          }|t          t          |          dd          }t          |          r\	  ||t          |j                  t          |j                            }n# t          $ r d}Y nw xY wt          |t                    rdS t          | dd          }|	 |                    t          |j                  t          |j                             d{V }|r7t          |                    d          pd          t          |          k    rdS n-# t          $ r  t                               dd	           Y dS w xY w|dS |                     |          }		 t          |d
d          }
|
: |
t          |j                  t          |j                  |	           d{V  dS t          |dd          }|t          |dd          nd}||t          |dd          nd}|dS 	  |t'          |j                  t'          |j                  |	           d{V  dS # t(          t*          f$ r"  ||j        |j        |	           d{V  Y dS w xY w# t          $ r  t                               dd	           Y dS w xY w)zLBest-effort rename of a Telegram DM topic when Hermes auto-titles a session.N_get_dm_topic_infor)   r  r%   r   z5Failed to verify Telegram topic binding before renameTr   rename_dm_topic)r  rd  r   r  edit_forum_topiceditForumTopic)r  message_thread_idr   z8Failed to rename Telegram topic for auto-generated title)r  r  r  r  rd  $_telegram_topic_auto_rename_disabledr	  r-   r   r  rU   r.   rR   rS   r  rT   r/   r0   r  rF  rU  rH  )r  r  r%   rL  r  get_infooperator_topicr3   rD  
topic_namerename_topicr  r  s                r6   (_rename_telegram_topic_for_session_titlez6GatewayRunner._rename_telegram_topic_for_session_title;M  s      &t'CVLLLLLLLL 	TZTb 	jpjz 	F 44V<< 	F **622tG}}.BDIIH!! *%-Xgs6>7J7JCPVP`LaLa%b%bNN  * * *%)NNN* nd33 FT=$77
!	 * E E//!&"233 !F ! !        s7;;|#<#<#BCCs:VVF   T_cddd ?F88??
	d"7,=tDDL'"l//!&"233#         
 '6400CILws,>EEE^b'KN?730@$#G#G#G`d '&&//&)&*:&;&;#           
 z*   &&"N&,&6#              	d 	d 	dLLS^bLcccccc	ds\   1C CC>A8E9 9&F#"F# AJ? ?J? 8J	 	/J<8J? ;J<<J? ?&K)(K)c                    t          | dd          r:t          | j        dd          r$| j        j                            |j                  nd}|dS t          |dd          pi }|                    d          }|dS t          |t                    r|S t          |t                    r(|                                	                                dv S t          |          S )zReturn True when operator disabled per-topic auto-rename for this Telegram chat.

        Controlled via ``gateway.platforms.telegram.extra.disable_topic_auto_rename``.
        Default is False (auto-rename enabled, preserves prior behaviour).
        rX   Nr#  Fr  disable_topic_auto_rename>   rM   rN   rO   rP   )
r-   rX   r#  rT   r_   rR   r   rU   rV   rW   )r  r  r%  r  r   s        r6   r  z2GatewayRunner._telegram_topic_auto_rename_disabledM  s     tXt,,18kSW1X1XDK!%%fo666 	
 5gt44:		566=5eT"" 	LeS!! 	G;;==&&((,FFFE{{rB   c                    |r|                      |          sdS |                     |          rdS 	 t          j                    }n!# t          $ r t          | dd          }Y nw xY w||                                rdS 	 t          j        |          }n# t          $ r |}Y nw xY wt          |                     |||          |t          d          }|dS dd}|                    |           dS )z>Schedule a topic rename from the auto-title background thread.Nrg  z.Telegram topic title rename failed to schedulerw  r'   c                     	 |                                   d S # t          $ r  t                              dd           Y d S w xY w)Nz"Telegram topic title rename failedTr   r  r  s    r6   r  zPGatewayRunner._schedule_telegram_topic_title_rename.<locals>._log_rename_failureM  sX    R

 R R RADQQQQQQRr  rX  )r  r  r  r	  r  r-   r  r>  rJ  r.   r   r  r/   r  )r  r  r%   rL  r   r  r   r  s           r6   rJ  z3GatewayRunner._schedule_telegram_topic_title_renameM  sM     	D88@@ 	F44V<< 	F	8+--DD 	8 	8 	84$77DDD	8<4>>++<F	#'/77MM 	# 	# 	#"MMM	#)99-UZ[[H	
 
 
 >F	R 	R 	R 	R 	  !455555s#   A A$#A$ B B$#B$r  c                    t          | d          si | _        t          |j        pd          }|sdS ddl}|                                }| j                            |d          }||z
  | j        k     rdS || j        |<   dS )zRate-limit the BotFather Threads Settings screenshot.

        If a user sends /topic repeatedly while Threads Settings are still
        off, we shouldn't keep re-uploading the screenshot every time.
        _telegram_capability_hint_tsr   Tr   Nr  F)r   r  rU   r  r,   rb  rT   $_TELEGRAM_CAPABILITY_HINT_COOLDOWN_Sr%  s         r6   %_should_send_telegram_capability_hintz3GatewayRunner._should_send_telegram_capability_hintM  s     t;<< 	302D-fn*++ 	4oo044WcBB:AAA558)'2trB   c                     	 dS )Nuz  /topic — enable multi-session DM mode (one bot, many parallel chats)

Usage:
  /topic             Enable topic mode, or show status if already on
  /topic help        Show this message
  /topic off         Disable topic mode and clear topic bindings
  /topic <id>        Inside a topic: restore a previous session by ID

How it works:
1. Run /topic once in this DM — Hermes checks BotFather Threads
   Settings are enabled and flips on multi-session mode.
2. Tap All Messages at the top of the bot and send any message.
   Telegram creates a new topic for that message; each topic is
   an independent Hermes session (fresh history, fresh context).
3. The root DM becomes a system lobby — send /topic, /status,
   /help, /usage there. Normal prompts go in a topic.
4. /new inside a topic resets just that topic's session.
5. /topic <id> inside a topic restores an old session into it.r,  r"  s    r6   _telegram_topic_help_textz'GatewayRunner._telegram_topic_help_textM  s    M	
 	
rB   c                 \  K   | j         sddlm}  |t          d                    S t	          |j        pd          }|sdS 	 | j                             |t	          |j        pd                     d{V }n# t          $ r d	}Y nw xY w|sd
S 	 | j         	                    |           d{V  n6# t          $ r)}t                              d           d| cY d}~S d}~ww xY wdD ]>}t          | |d          }t          |t                    r|                    |d           ?	 dS )z5Cleanly disable topic mode for a chat via /topic off.r   )format_session_db_unavailablez,gateway.shared.session_db_unavailable_prefix)r  r   zCould not determine chat ID.r  NFz@Multi-session topic mode is not currently enabled for this chat.r  z%Failed to disable Telegram topic modezFailed to disable topic mode: )r#  r  u   Multi-session topic mode is now OFF for this chat.

Existing topics in Telegram aren't removed — they'll just stop being gated as independent sessions. The root DM works as a normal Hermes chat again. Run /topic to re-enable later.)r)   r  r  r   rU   r  r  r  r.   disable_telegram_topic_moder/   r   r-   rR   rS   r$  )r  r  r  r  currently_enabledr5   r  stores           r6   %_disable_telegram_topic_mode_for_chatz3GatewayRunner._disable_telegram_topic_mode_for_chatM  s      	kBBBBBB00:h8i8ijjjjfn*++ 	211	&&*&6&U&UFN0b11 'V ' ' ! ! ! ! ! !  	& 	& 	& %	&  	VUU	:">>w>OOOOOOOOOO 	: 	: 	:DEEE9C99999999	:
 T 	) 	)DD$--E%&& )		'4(((G	
 	
s0   6A; ;B
	B
!B4 4
C'>C"C'"C'c           
      H  K   g d}	 | j                             t          |j                  t          |j                  d           d {V }n.# t
          $ r! t                              dd           g }Y nw xY w|r|                    d           |D ]}t          |	                    d          pd	          }t          |	                    d
          pd          }t          |	                    d          pd	          
                                }d| d| d}|r|d| z  }|                    |           |                    d	dddd|d         	                    d           dg           n|                    g d           d                    |          S )N)z*Telegram multi-session topics are enabled.r   zTo create a new Hermes chat, open All Messages at the top of this bot interface and send any message there. Telegram will create a new topic for it.r   r  )r  r  limitz)Failed to list unlinked Telegram sessionsTr   zPrevious unlinked sessions:r   r   rL  zUntitled sessionr  z- u    — `r   r	  zTo restore one:]1. Create or open a topic. To create a new one, open All Messages and send any message there..2. Send /topic <session-id> inside that topic.zExample: Send /topic r   z inside a topic.)z-No previous unlinked Telegram sessions found.r   z$To restore a previous session later:r  r  r   )r)   (list_unlinked_telegram_sessions_for_userrU   r  r  r.   r/   r0   rs   rT   rV   extendrD   )	r  r  r;  rb  r	  r%   rL  r  r#  s	            r6   #_telegram_topic_root_status_messagez1GatewayRunner._telegram_topic_root_status_messageN  s     
 
 
	!-VVFN++FN++ W        HH
  	 	 	LLDtLTTTHHH	  	LL6777# # # T!2!2!8b99
GKK00F4FGGgkk)44:;;AACC6E66666 .-G---DT""""LL!o@O(=(=OOO     LL       yys   AA (A;:A;raw_session_idc                   K   |j         }| j                            |                                           d{V }|sd|                                 S | j                            |           d{V }|sd|                                 S t          |                    d          pd          dk    rdS t          |                    d          pd          t          |j                  k    rdS | j                            |	           d{V }| j        	                    t          |j
                  t          |j                  
           d{V }|r|r|                    d          |k    rdS |                     |          }	 | j                            t          |j
                  t          |j                  t          |j                  ||d           d{V  n*# t          $ r}	dt          |	          v rY d}	~	dS  d}	~	ww xY w| j                            |           d{V p|}
d}	 t!          | j                            |           d{V           D ]T}|                    d          dk    r9|                    d          r$t          |                    d                    } nUn# t$          $ r d}Y nw xY wd|
 }|r|d| z  }|S )zBRestore an existing Telegram-owned Hermes session into this topic.NzSession not found: r  r   r7  zNThat session is not a Telegram session and cannot be restored into this topic.r  z3That session does not belong to this Telegram user.r5  r  r%   z9That session is already linked to another Telegram topic.restored)r  rd  r  r  r%   managed_modezalready linkedr{  r  r  zSession restored: z

Last Hermes message:
)r  r)   resolve_session_idrV   rh  rU   rT   r  #is_telegram_session_linked_to_topicr  r  rd  r  r0  rH  get_session_titler  get_messagesr.   )r  r  r  r  r%   r	  linkedcurrent_bindingr  r5   rL  last_assistantr  r  s                 r6   _restore_telegram_topic_sessionz-GatewayRunner._restore_telegram_topic_sessionJN  s     +>>~?S?S?U?UVVVVVVVV
 	BA)=)=)?)?AAA(44Z@@@@@@@@ 	BA)=)=)?)?AAAw{{8$$*++z99ccw{{9%%+,,FN0C0CCCHH'KKWaKbbbbbbbb $ 0 K K''&*++ !L !
 !
 
 
 
 
 
 
  	S" So&9&9,&G&G:&U&URR226::	"66FN++f.//FN++'%' 7            	 	 	3s88++RRRRRR	
 &88DDDDDDDDR
	"#$*:*G*G
*S*S$S$S$S$S$S$STT  ;;v&&+55'++i:P:P5%(Y)?)?%@%@NE 	" 	" 	"!NNN	" 0// 	FE^EEEHs2   AG- -
H7HHH<BJ? ?KKc           
      V	  K   t          j                    }	 ddlm}m}m}m} |5  t          |                                          }ddd           n# 1 swxY w Y   |	                    d|           d{V  |	                    d|           d{V }|5  t          |                                          }	ddd           n# 1 swxY w Y   |	|z
  }
||	z
  }|	|z  }t          d          g}|rD|                    t          dd                    t          |                                         |
rD|                    t          dd                    t          |
                                         |rD|                    t          d	d                    t          |                                         |	s#|                    t          d
                     n?|                    t          dt          |          t          |	                               	 ddlm} t!          | dd          }t!          | dd          }||r|5  t#          |                                          D ]F\  }}	 t'          |t(                    r|d         n|}n# t*          $ r Y 2w xY w|9 ||d           G	 ddd           n# 1 swxY w Y   n2# t*          $ r%}t,                              d|           Y d}~nd}~ww xY wg }|
r8|                    dd                    t          |
                                |r8|                    dd                    t          |                                |r8|                    dd                    t          |                                |rt          |           dnd}|rd                    |          dz   nd}dd| | dd}	 | j                            |j                   d{V }| j                            |j        |           d{V  n# t*          $ r Y nw xY wd                    |          S # t*          $ r6}t,                              d|           t          d |!          cY d}~S d}~ww xY w)"a  Actually disconnect, reconnect, and notify MCP tool changes.

        Split out from ``_handle_reload_mcp_command`` so the confirmation
        wrapper can invoke the same path whether the user confirmed via
        button, text reply, or has the confirm gate disabled.
        r   )shutdown_mcp_serversdiscover_mcp_tools_serversr~	  Nzgateway.reload_mcp.headerzgateway.reload_mcp.reconnectedr   )nameszgateway.reload_mcp.addedzgateway.reload_mcp.removedz!gateway.reload_mcp.none_connectedz"gateway.reload_mcp.tools_available)r  servers)refresh_agent_mcp_toolsr  r  T)r  z8Failed to update cached agent tools after MCP reload: %szAdded servers: zRemoved servers: zReconnected servers: z MCP tool(s) now availablezNo MCP tools availablez. r   r  z,[IMPORTANT: MCP servers have been reloaded. zD. The tool list for this conversation has been updated accordingly.]r  r   zMCP reload failed: %szgateway.reload_mcp.failed)r  )r  r	  tools.mcp_toolr   r!  r"  r~	  rt   rg  r  r   rs   rD   r  r   r%  r-   r  r  rR   ra  r.   r/   r0   r	  r  r  r5  r%   r   )r  r  r   r   r!  r"  r~	  old_servers	new_toolsconnected_serversaddedr  reconnectedr;  r%  r  r  	_sess_keyrR  r  _excchange_partstool_summarychange_detail
reload_msgr1  rs  s                              r6   _execute_mcp_reloadz!GatewayRunner._execute_mcp_reloadN  s~      '))a	;````````````  3 3!(--//223 3 3 3 3 3 3 3 3 3 3 3 3 3 3
 &&t-ABBBBBBBBB #2249KLLLLLLLLI  9 9$'$8$8!9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 &3E!$55G+k9K2334E hQ?tyyQWXcQdQdGeGefffggg \Q96RW==AYAYZZZ[[[ `Q;499VT[__C]C]^^^___$ |QBCCDDDDQC3y>>cfgxcycyzzz{{{BBBBBB ~t<<%d,?FF*v*$ M M15fllnn1E1E M M-Iv)6@6O6O)[U[#, ) ) ) ()%~ ( 43FtLLLLL!MM M M M M M M M M M M M M M M$    N        L R##$Pdiiu6N6N$P$PQQQ V##$T		&//8R8R$T$TUUU ^##$\DIIf[FYFY<Z<Z$\$\]]]LUsc)nnHHHH[sL>JRDIIl33d::PRM l-  lYe  l  l  l J&*&>&T&TUZUa&b&b b b b b b b.CC!,j              99U### 	; 	; 	;NN2A6660:::::::::	;s   Q( "AQ( AQ( A=Q( "C:Q( C

Q( C
EQ( '.K 'K=JK
J*'K)J**K?K KK KK Q( 
L!L<Q( LC0Q( 7AQ Q( 
QQ( QQ( (
R(2+R#R(#R(r   ra  r9  c                <  K   d}	 |                                  }t          |t                    r|                    d          nd}t          |t                    r#t	          |                    dd                    }n# t
          $ r Y nw xY w|s              d{V S |                     |j                  dt          ffd}	| 	                    |j        j
                  }
d d| d	|
 d
|
 d|
 d}|                     ||||	           d{V S )u  Gate a destructive session slash command (/new, /reset, /undo).

        ``execute`` is an async callable ``execute() -> str | EphemeralReply``
        that performs the destructive action.  If the
        ``approvals.destructive_slash_confirm`` config gate is off, ``execute``
        runs immediately (returning its result).  Otherwise this routes
        through ``_request_slash_confirm`` — native yes/no buttons on
        Telegram/Discord/Slack, text fallback elsewhere.

        Three-option resolution:

          - ``once``  — run ``execute`` and return its result
          - ``always`` — persist ``approvals.destructive_slash_confirm: false``,
                        then run ``execute``
          - ``cancel`` — return a "cancelled" message; do not run ``execute``
        Tr9  Ndestructive_slash_confirmchoicec                   K   | dk    rd dS d}| dk    r	 ddl m} t           |dd                    }|rt                              d	           nt                              d
           n2# t          $ r%}t                              d|           Y d }~nd }~ww xY w              d {V }| dk    r#|rd}nd}t          |t                    r||z   S |S |S )Nr  u   🟡 /z# cancelled. Conversation unchanged.Fr	  r   )save_config_valuez#approvals.destructive_slash_confirmz8User opted out of destructive slash confirm (session=%s)z[Could not persist destructive_slash_confirm=false (session=%s); config.yaml is not writablez5Failed to persist destructive_slash_confirm=false: %su   

ℹ️ Future /clear, /new, /reset, and /undo will run without confirmation. Re-enable via `approvals.destructive_slash_confirm: true` in config.yaml.u   

⚠️ Could not save that preference (config.yaml is not writable), so /clear, /new, /reset, and /undo will ask again next time. To silence it permanently, set `approvals.destructive_slash_confirm: false` in config.yaml.)	r;  r7  r   r/   r  r   r.   rR   rU   )	r5  	persistedr7  r5   r  noter   rb  r  s	         r6   _on_confirmzCGatewayRunner._maybe_confirm_destructive_slash.<locals>._on_confirm+O  s~     !!LLLLLI!!555555 !%))*OQVWW! !I ! 
V'   
 H'  
 !   NNOQT        #799______F!! V DW  fc** )!D=( Ms   AA2 2
B!<BB!u   ⚠️ **Confirm /z**

u   

Choose:
• **Approve Once** — proceed this time only
• **Always Approve** — proceed and silence this prompt permanently
• **Cancel** — keep current conversation

_Text fallback: reply `zapprove`, `zalways`, or `z	cancel`._)r  r   rL  r  handler)_read_user_configrR   rS   rT   r   r.   r  r  rU   _typed_command_prefix_forr_   _request_slash_confirm)r  r  r   rL  ra  rb  confirm_requiredrk  r9  r:  r  prompt_messager  s     `  `      @r6   r  z.GatewayRunner._maybe_confirm_destructive_slashO  s     4  	((**C0:30E0EO,,,4I)T** Z#'	6QSW(X(X#Y#Y  	 	 	D	   	# ??????"225<@@4	c 4	 4	 4	 4	 4	 4	 4	 4	l ++EL,ABBT T TT T ')T T 68T T GIT T T 	 00" 1 
 
 
 
 
 
 
 
 	
s   A8B 
BBc                |  K   ddl m} |j        }|                     |          }t	          | dd          }	|	 ddl}
|
                    d          }	|	| _        t          |	           }|	                    ||||           | 
                    |          }|                     ||                     |                    }d}|v	 |                    |j        |||||           d{V }|rt	          |dd          rd	}n9# t          $ r,}t                               d
||j        |           Y d}~nd}~ww xY w|rdS |S )aR  Ask the user to confirm an expensive slash command.

        ``handler`` is an async callable ``handler(choice: str) -> str``
        where ``choice`` is ``"once"``, ``"always"``, or ``"cancel"``.
        The handler runs on the event loop when the user responds; its
        return value is sent back as a gateway message.

        Returns a short acknowledgment string to send immediately (before
        the user's response).  If buttons rendered successfully the ack
        is ``None`` (buttons are self-explanatory); if we fell back to
        text the message itself IS the ack.
        r   rL  r  Nrk   F)r  rL  r  r  rR  r   r  Tz*send_slash_confirm failed for %s on %s: %s)r  rM  r  r  r-   r  r   r  nextr  r	  r	  r=  send_slash_confirmr  r.   r/   r0   r_   )r  r  r   rL  r  r;  r  r  r  counterr  rR  r  r   used_buttonsbutton_resultr5   s                    r6   r>  z$GatewayRunner._request_slash_confirmsO  s     * 	>=====226::
 $ 8$???**** &&q))G*1D'W'
 	##KWgNNN**62233FD<X<XY^<_<_``&-&@&@"N# +)% 'A ' ' ! ! ! ! ! ! ! (W]Iu%M%M (#'L   @V_c         	4s   ;C? ?
D5	"D00D5c                 z    	 ddl m}  |            }t          |t                    r|ni S # t          $ r i cY S w xY w)zRead the user's raw config.yaml (cached) for gate lookups.

        Used by slash-confirm gates that must reflect on-disk state changes
        (e.g. a prior "Always Approve" click) without a gateway restart.
        r   r7  )rg  r8  rR   rS   r.   )r  r8  rk  s      r6   r<  zGatewayRunner._read_user_configO  sa    	555555+--C$S$//733R7 	 	 	III	s   (+ ::r	  c                 ~   |                      t          |dd          t          |dd          t          |dd          t          |dd          |pt          |dd                    }t          |dd          t          j        k    r6t          |dd          }|r#t	          |pi           }t          |          |d	<   |S )
z@Build the metadata dict platforms need for thread-aware replies.r_   Nr  rd  r}  r4  r}  r	  scope_idslack_team_id)r	  r-   r  r  rS   rU   )r  r  r	  r   team_ids        r6   r	  z)GatewayRunner._thread_metadata_for_sourceO  s     33FJ--FIt,,FK..fk488 3 Zwv|UY7Z7Z 4 
 
 6:t,,>>fj$77G 9B//,/LL)rB   r	  r}  c                    |dS d|i}|                      |||||          r3d|d<   t          |          }|r	|dvr||d<   |t          |          |d<   |t          j        k    r|t          |          |d	<   |S )
zGBuild thread metadata for synthetic sends that only have routing state.Nrd  r}  r  T telegram_dm_topic_reply_fallback>   r   rM   direct_messages_topic_idtelegram_reply_to_message_idr4  )_is_telegram_dm_topic_targetrU   r  r  )	r  r_   r  rd  r}  r	  r  r   r  s	            r6   r	  z)GatewayRunner._thread_metadata_for_targetO  s     4$/#;,, - 
 
 	T <@H78 i..C ;s)++7:34".;>?R;S;S78x~%%*=*I &))<%=%=H\"rB   rN  c                r   | t           j        k    s|dS |dk    rdS ||rt          t          |          dd          }t	          |          ri	  ||t          |          t          |                    }t          |t                    S # t          $ r t          
                    dd           Y nw xY wdS )z>Return True when a target is a Telegram private DM topic lane.NFr~  Tr  z,Failed to inspect Telegram DM topic metadatar   )r  r  r-   r   r  rU   rR   rS   r.   r/   r0   )r_   r  rd  r}  r  get_dm_topic_info
topic_infos          r6   rR  z*GatewayRunner._is_telegram_dm_topic_targetO  s     x(((I,=54 7 'W7KT R R)** 88!2!27CLL#i..!Y!YJ &j$777 ! ` ` `LL!OZ^L_____` us   'B &B43B4c                      t          |           S )zBReturn the platform-specific reply anchor for GatewayRunner sends.)r=  )r  s    r6   r=  z%GatewayRunner._reply_anchor_for_eventP  s     'u---rB   c                    t          | dd          }|r|                                sdS 	 t          j        |                                           | _        dS # t          $ r t                              d           Y dS w xY w)z;Ensure a background task is watching for update completion._update_notification_taskNz;Skipping update notification watcher: no running event loop)	r-   r  r  ri  _watch_update_progressrX  r  r/   r0   )r  existing_tasks     r6   r`  z1GatewayRunner._schedule_update_notification_watch9P  s    &A4HH 	!3!3!5!5 	F	X-4-@++--. .D***  	X 	X 	XLLVWWWWWW	Xs   +A $B ?B       @      @r  stream_intervalc                   "#$%&'()K   t           dz  }t           dz  }t           dz  }t           dz  }t           dz  }t          j                    ''                                |z   }	d#d%d}
d(||fD ]#}|                                r	 t          j        |                    d                    }|                    d	          }|                    d
          %|                    d          }|                    d          }
|                    d          }|                    d          }|rO%rMt          |          )| j
                            )          #|                     )%|||#          (|
s| d% }
 n# t          $ r Y w xY w%#r%sSt                              d           |                                s|                                r'                                |	k     r|                                r|                                  d{V rdS t          j        |           d{V  |                                s|                                r'                                |	k     |                                s|                                rE|                                s1|                    dd           |                                  d{V  dS dt$          dt$          fd"d}'                                &d$d6"#$%&'()fd}'                                |	k     r|                                r|                                rW	 |                    d          }t'          |          |k    r$||d         z  $t'          |          }n# t(          $ r Y nw xY w |             d{V  	 |                    d                                          pd}t-          |          }|dk    r.#                    %dt1          ()                     d{V  n@#                    %d                    |          t1          ()                     d{V  t                              d||
           n2# t          $ r%}t                              d|           Y d}~nd}~ww xY w|||||fD ]}|                    d !           t           d"z                      d !           |                     |
          }|d#|j        _        dS |                                rW	 |                    d          }t'          |          |k    r$||d         z  $t'          |          }n# t(          $ r Y nw xY w$                                r+'                                &z
  |k    r |             d{V  |
r|                     |
          nd}|                                r|
r||j        j        s	 t          j        |                    d                    }|                    d$d          }|                    d%d          }|r. |             d{V  d#}t?          tA          #          d&d          e	 #!                    %|||
t1          ()          '           d{V  d }n2# t          $ r%}t          "                    d(|           Y d}~nd}~ww xY w|sT|rd)| d*nd}t?          #d+d,          } #                    %d-| | d.|  d/|  d0t1          ()                     d{V  d | #                    |
          j        _        t                              d1|
|dd2                    n># t
          j$        t(          f$ r%}t          "                    d3|           Y d}~nd}~ww xY wt          j        |           d{V  '                                |	k     |                                st                              d4|           |                    dd            |             d{V  	 #                    %d5t1          ()                     d{V  n# t          $ r Y nw xY w|||||fD ]}|                    d !           t           d"z                      d !           |                     |
          }!|!d#|!j        _        dS dS dS )7a  Watch ``hermes update --gateway``, streaming output + forwarding prompts.

        Polls ``.update_output.txt`` for new content and sends chunks to the
        user periodically.  Detects ``.update_prompt.json`` (written by the
        update process when it needs user input) and forwards the prompt to
        the messenger.  The user's next message is intercepted by
        ``_handle_message`` and written to ``.update_response``.
        r$  r%  .update_output.txt.update_exit_coderH  Nr  rJ  r_   r  r}  r  rd  r4  r	  r  zOUpdate watcher: cannot resolve adapter/chat_id, falling back to completion-only124r   r'   c                 $    ddl m}  ||           S )Nr   
strip_ansi)tools.ansi_striprd  )r   rd  s     r6   _strip_ansiz9GatewayRunner._watch_update_progress.<locals>._strip_ansiP  s$    333333:d###rB   r   r   c            	        K                                    sddS                                             d
                                	sdS dfdt          dt                              D             } | D ]f}	                     d| dt                    	           d{V  5# t          $ r%}t                              d
|           Y d}~_d}~ww xY wdS )z!Send buffered output to the user.r   N  c                 *    g | ]}||z            S r,  r,  )r?   r  clean	max_chunks     r6   r  zOGatewayRunner._watch_update_progress.<locals>._flush_buffer.<locals>.<listcomp>P  s&    VVVeAa)mO,VVVrB   r   r  r  rc   r  zUpdate stream send failed: %s)	rV   r,   r  r   r  r   r.   r/   r0   )chunkschunkrs  rj  rk  rf  r  bufferr  last_stream_timer   r   r_   s      @@r6   _flush_bufferz;GatewayRunner._watch_update_progress.<locals>._flush_bufferP  s_      <<>> K''--//EF#yy{{ IVVVVVeAs5zz96U6UVVVF E EE!,,,,,,!=hQY!Z!Z!Z '          
 ! E E ELL!@!DDDDDDDDEE Es   1B99
C(C##C(rM   u   ✅ Hermes update finished.rc   r  u(   ❌ Hermes update failed (exit code {}).z&Update finished (exit=%s), notified %sz$Update final notification failed: %sTrB  rG  Fr	  r(  send_update_prompt)r  r	  r(  r  r   z%Button-based update prompt failed: %sz (default: rT  r  r;  u"   ⚕ **Update needs your input:**

z	

Reply `zapprove` (yes) or `z)deny` (no), or type your answer directly.z!Forwarded update prompt to %s: %sr  z Failed to read update prompt: %sz$Update watcher timed out after %.0fsu-   ❌ Hermes update timed out after 30 minutes.rX  )%r;  r  r	  r,   rw   r  r  r   rT   r  r{  r	  r.   r/   r   r_  r`  r  rU   r   ru   rV   rF  r  r   formatr  rD  r  r  r  r-   r   rq  r0   r  r  )*r  r  r]  r  pending_pathclaimed_pathrn  exit_code_pathr  r	  r  rx   r  r
  r}  rd  r4  
bytes_sentrp  r  exit_code_rawr  rs  r  _up_done_up_pending_stateprompt_dataprompt_textr(  sent_buttonsbtn_errdefault_hintr  _up_timeout_staterf  r  rn  r  ro  r   r   r_   s*                                     @@@@@@@@r6   rY  z$GatewayRunner._watch_update_progressFP  s      $&<<#&DD"%99%(;;"%::'))99;;( !<0 	 	D{{}} "j)I)IJJG#*;;z#:#:L%kk)44G 'K 8 8I")++m"<"<K 'K 8 8I!(\!:!:J# F F#+L#9#9"&-"3"3H"="=#'#C#C$#%&/0:$+ $D $ $  + F-9*E*EG*E*EKE    D16  	g 	NNlmmm  &&(( 3L,?,?,A,A 3tyy{{U]G]G]!((** T5S5S5U5U/U/U/U/U/U/U FmM222222222  &&(( 3L,?,?,A,A 3tyy{{U]G]G] ##%% 7)<)<)>)> 7H]H]H_H_ 7))%')BBB44666666666F	$c 	$c 	$ 	$ 	$ 	$ 
99;;	E 	E 	E 	E 	E 	E 	E 	E 	E 	E 	E 	E 	E2 iikkH$$$$&& (%%'' "-"7"7"7"I"Iw<<*44"gjkk&::F),WJ"   #moo%%%%%%%N$2$<$<g$<$N$N$T$T$V$V$]Z]M #M 2 2I A~~%ll#9%A(U]%^%^%^ +           &ll#FMMiXX%A(U]%^%^%^ +         
 KK H)U`aaaa  N N NNN#I1MMMMMMMMN 'k(+7 . .AHHH---- 22::d:KKK33K@@'@EH'= !!## )33W3EEG7||j00'*++"66%(\\
   D ||~~ &499;;1A#Ao"U"U#moo%%%%%%% :EN((555$  ""$$ 1H 1H)5-8N 6,H"&*[-B-BG-B-T-T"U"UK"-//(B"?"?K)ooi<<G" &h ,moo-------',"4==2FMMY
_&-&@&@,3+6,30;-I(]e-f-f-f 'A '" '" !" !" !" !" !" !" !" 04#, _ _ _ &-TV] ^ ^ ^ ^ ^ ^ ^ ^_+ 
GN+V+C+C+C+C+CTVL!(2H#!N!NB"),, '!A#.!A0<!A !A*,!A !AAC!A !A !A *FhYa)b)b)b #/ # #        >B ++' $%:$GVabecebeVfggg,g6 H H HLL!CQGGGGGGGGH -.........i iikkH$$n $$&& 	KNNA7KKK%%eg%>>>-//!!!!!!!llC9(XVVV #          
    "L+$k3 * *D))))..66$6GGG $ 8 8 E E ,EJ!,BBB%	K 	K" -,s   C7F
FF*AN0 0
N=<N=C	R 
S
%SS
AV 
VVB^! #1[ ^! 
\[?:^! ?\B^! !_7__)-b 
b$#b$c                 (  K   t           dz  }t           dz  }t           dz  }t           dz  }|                                s|                                sdS d}|}	 |                                r	 |                    |           n# t          $ rv |                                s_Y |rZ|                    d           |                    d           |                    d           |                    d           dS dS Y nww xY w|                                s_	 |rZ|                    d           |                    d           |                    d           |                    d           dS dS t          j        |                    d	                    }|                    d
          }|                    d          }	|                    d          }
|                    d          }|                    d          }|                                st          
                    d           d}|}|                    |           	 |rZ|                    d           |                    d           |                    d           |                    d           dS dS |                    d	                                          pd}t          |          }d}|                                r|                    d	          }t          |          }| j                            |          }|s|	rt          
                    d|           d}|}|                    |           	 |rZ|                    d           |                    d           |                    d           |                    d           dS dS |r|	r|                     ||	||
||          }ddlm}  ||                                          }|r4t%          |          dk    rd|dd         z   }|dk    rd| d}nd| d}n|dk    rd}nd}|                    |	|t)          ||                      d{V  t          
                    d!||	|           n2# t*          $ r%}t                              d"|           Y d}~nd}~ww xY w|rX|                    d           |                    d           |                    d           |                    d           n`# |rY|                    d           |                    d           |                    d           |                    d           w w xY wdS )#a  If an update finished, notify the user.

        Returns False when the update is still running so a caller can retry
        later. Returns True after a definitive send/skip decision.

        This is the legacy notification path used when the streaming watcher
        cannot resolve the adapter (e.g. after a gateway restart where the
        platform hasn't reconnected yet).
        r$  r%  r_  r`  FTrB  r  rJ  r_   r  r}  rd  r4  z2Update notification deferred: update still runningrM   r   z:Update notification deferred: %s adapter not connected yetr	  r   rc  rh  rJ  iTNu!   ✅ Hermes update finished.

```
r  u   ❌ Hermes update failed.

```
u(   ✅ Hermes update finished successfully.u]   ❌ Hermes update failed. Check the gateway logs or run `hermes update` manually for details.rc   r  z0Sent post-update notification to %s:%s (exit=%s)z#Post-update notification failed: %s)r;  rw   rJ  r  rD  r  r  r   rT   r/   r  rV   rF  r  r{  r	  re  rd  r   r  r   r.   r   )r  rs  rt  rn  ru  cleanupactive_pending_pathr  r
  r  r}  rd  r4  rw  r  r  r_   r  r   rd  r|  rs  s                         r6   r_  z'GatewayRunner._send_update_notification<Q  s      $&<<#&DD"%99%(;;""$$ 	\-@-@-B-B 	5*_	7""$$ $ ((6666( $ $ $'..00 $#j  7#**d*;;;##t#444""d"333%%%66666	7 7m$ $$ "((** f  7#**d*;;;##t#444""d"333%%%66666	7 7c j!7!7!7!I!IJJG";;z22Lkk),,GK00IK00I \22J!((** PQQQ&2#$$\222J  7#**d*;;;##t#444""d"333%%%66666	7 7G +44g4FFLLNNURUMM**I F!!## A$...@@  --Hm''11G w  P     &2#$$\222N  7#**d*;;;##t#444""d"333%%%66666	7 7K  !7 !;;'(2# <   877777#F++1133 
z6{{T))!&!7 A~~RVRRRP6PPP!^^DCCyCll9(XVVV #         
 F 	    	E 	E 	ENN@!DDDDDDDD	E  7#**d*;;;##t#444""d"333%%%666	  7#**d*;;;##t#444""d"333%%%6666	7 tsp   R% /B R% D#R% R% DR% ;CR% 2CR% CR% $T2 %
S/S
T2 ST2 2AVc           
        K   t           dz  }|                                sdS 	 t          j        |                    d                    }|                    d          }|                    d          }|                    d          }|                    d          }|                    d	          }|r|s	 |                    d
           dS t          |          }t          || j	        | j
                  }	|	4t                              d|           	 |                    d
           dS | j	        j                            |          }
|
;|
j        s4t                              d|           	 |                    d
           dS |                     ||||||	j                  }|                    d          d
u rkt%          |pi           }|                    d          rt'          |d                   |d<   |                    d          rt'          |d                   |d<   |	                    |t'          |          dt+          ||                     d{V }|Xt-          |dd
          du rEt                              d||t-          |dd                     	 |                    d
           dS t                              d||           t'          |          t'          |          |rt'          |          ndf|                    d
           S # t0          $ r<}t                              d|           Y d}~|                    d
           dS d}~ww xY w# |                    d
           w xY w)zANotify the chat that initiated /restart that the gateway is back.r:  Nr  rJ  r_   r  r}  rd  r4  TrB  z6Restart notification skipped: no live transport for %szJRestart notification suppressed: %s has gateway_restart_notification=falser	  r  r  rJ  u;   ♻ Gateway restarted successfully. Your session continues.rc   r  r  Fz3Restart notification to %s:%s was not delivered: %sr  r	  z"Sent restart notification to %s:%szRestart notification failed: %s)r;  rw   r  r  r   rT   rD  r  r/  rX   r{  r/   r0   r#  r	  r  r	  r  rS   rU   r  r   r-   r   r.   )r  notify_pathr  r
  r  r}  rd  r4  r_   r_  r%  r   r  rs  s                 r6   ra  z(GatewayRunner._send_restart_notificationQ  s	     "%;;!!## 	4G	0:k33W3EEFFD88J//Lhhy))G--I--I,//J w | $/////y  --H28T[$-XXI L    j $/////g  ;044X>>L'0Y'`    Z $/////W 77#$.!) 8  H xx6774??B//88I&& ?*-d9o*>*>HY'88J'' A+.tJ/?+@+@HZ($>>GM5hRRR	 *        F !gfi&F&F%&O&OI FG-JKK	    $///// KK4  
 |$$c'lli4YC	NNNUYY
 $////	  	 	 	NN<a@@@444$/////		 $////sF   BL' AL' 2AL' DL' AL' '
M-1M(M0 (M--M0 0Nr&  r'  c                  K   t                      }|pt                      }d}| j        j                                        D ]F\  }}|j        }|r|j        st          || j        | j                  }|5|j        s!t          
                    d|j                   ]|j        t          |j                  |j        rt          |j                  ndf}	|	|v s|	|v r	 |                     ||j        |j        |j                  }
|j        r3t#          |
pi           }
|j        r
|j        |
d<   |j        r
|j        |
d<   t)          |
|          }||j        r2|                    |t          |j                  ||           d{V }n3|j                            t          |j                  |           d{V }|Kt-          |d	d
          du r8t                              d|j        |j        t-          |dd                     |                    |	           t          
                    d|j        |j                   	# t2          $ r2}t                              d|j        |j        |           Y d}~@d}~ww xY w|S )a3  Notify configured home channels that the gateway is back online.

        The notification is best-effort and sent once per connected platform
        home channel. ``skip_targets`` lets startup avoid duplicate messages
        when a more specific restart notification is queued for the same chat.
        u3   ♻️ Gateway online — Hermes is back and ready.NzWHome-channel startup notification suppressed: %s has gateway_restart_notification=falser  r  rJ  rc   r  r  TFz6Home-channel startup notification failed for %s:%s: %sr  r	  z/Sent home-channel startup notification to %s:%s)rt   rX   r#  r  home_channelr  r/  r{  r	  r/   r  r   rU   rd  r	  r  is_relayrS   r  rJ  r   r  r-   r   rv   r.   )r  r'  	deliveredskippedr  r_   r%  rX  r_  r  r   r  r  r5   s                 r6   rb  z6GatewayRunner._send_home_channel_startup_notificationsR  s      :=	'#%%G&*k&;&A&A&C&C @	 @	"Hl,D t| 28T[$-XXI < mN   nc$,&7&7PTP^9hT^9L9L9LdhiF  Fi$7$7,;;LN%-	 <   % =#HN33H| ;.2l+} =/3}, <XPX Y Y Y ,	0B,#,>> DL))!.	 $2 $ $      FF $-#4#9#9#dl:K:KW#U#UUUUUUUF%'&)T*J*Je*S*SNNP 1NOO	   f%%%ENL   
    LNL	        s   D,I
;I


J'JJc                    ddl m} t          | dd          pi }|                    |j        j                  }t          |dd          } ||j        j        j        |j        j        |j        j        rt          |j        j                  nd|j        j
        pd|j        j        rt          |j        j                  nd|j        j        rt          |j        j                  nd|j        j        rt          |j        j                  nd|j        |j        j        rt          |j        j                  ndt          |j        dd          pd|d	          S )
a@  Set session context variables for the current async task.

        Uses ``contextvars`` instead of ``os.environ`` so that concurrent
        gateway messages cannot overwrite each other's session state.

        Returns a list of reset tokens; pass them to ``_clear_session_env``
        in a ``finally`` block.
        r   )set_session_varsr{  Nsupports_async_deliveryTr   r  )r_   r  r}  r  rd  r  r  r  r4  r  async_deliverycron_session)r  r  r-   rT   r  r_   r   r  r}  rU   r  rd  r  r  r  r4  )r  r   r  	_adaptersr~  _async_deliverys         r6   r  zGatewayRunner._set_session_envUR  sP    	=<<<<< D*d339r	==!899!(,EtLL^,2N*181IQGN,---rn.4"7>~7OWc'.2333UW3:>3IQC.///r7>~7OWc'.2333UW+9@9RZs7>4555XZGNIr::@b*
 
 
 	
rB   r(	  c                 (    ddl m}  ||           dS )z>Restore session context variables to their pre-handler values.r   )clear_session_varsN)r  r  )r  r(	  r  s      r6   r/  z GatewayRunner._clear_session_envzR  s+    >>>>>>6"""""rB   c                    K   t          j                    }t                      } |j        |                                 |j        |g|R   d{V S )zJRun blocking work in the thread pool while preserving session contextvars.N)r  r	  r   r  _get_executorrq
  )r  funcr  r   r  s        r6   r&
  z+GatewayRunner._run_in_executor_with_contextR  sx      '))nn)T)  G
 	
 
 
 
 
 
 
 
 
 	
rB   c                 p   t          | dd          }|t          j                    }|| _        |5  t          | dd          rt	          d          t          | dd          }|t          |dd          r(t
          j                            dd	
          }|| _        |cddd           S # 1 swxY w Y   dS )z:Return the gateway-owned executor for blocking agent work.ro  Nrq  Fz.Gateway is shutting down; executor unavailablerp  	_shutdownr  rm
  )max_workersthread_name_prefix)	r-   ro  r  ro  r  
concurrentfuturesThreadPoolExecutorrp  r  rt	  executors      r6   r  zGatewayRunner._get_executorR  s   t-t44<>##D"&D 
	 
	t0%88 U"#STTTt[$77H78[%#H#H%-@@ "'7 A   "*
	 
	 
	 
	 
	 
	 
	 
	 
	 
	 
	 
	 
	 
	 
	 
	 
	 
	s   A.B++B/2B/c                 (   t          | dd          }|dS |5  d| _        t          | dd          }d| _        ddd           n# 1 swxY w Y   |dS 	 |                    dd           dS # t          $ r |                    d           Y dS w xY w)zBStop the gateway-owned executor without touching the loop default.ro  NTrp  F)r  cancel_futures)r  )r-   rq  rp  r  rU  r  s      r6   rF  z GatewayRunner._shutdown_executorR  s   t-t44<F 	" 	"%)D"t[$77H!DN	" 	" 	" 	" 	" 	" 	" 	" 	" 	" 	" 	" 	" 	" 	"
 F	*5>>>>> 	* 	* 	*5))))))	*s#    AAAA- - BB)r  r  r  r  r  r  c                   	 ddl m} ddlm}m} ddlm}	 t          |t                    r|n	 |	            }
|pd	                                }|pd	                                }d}| p| }|dup|}|r)|r&	 | 
                    |||
          \  }}|s)t          |t                    r|	                                }t          |t                    r|                    d          nd}t          |t                    r|                    d	          nd}|s)t          |t                    r|	                                }t          |t                    r|	                                }n2# t          $ r%}t                              d
|           Y d}~nd}~ww xY w|s
 |            }|s
 |            } ||||
|          S # t          $ r&}t                              d|           Y d}~dS d}~ww xY w)ai  Resolve image-input routing for the effective model this turn.

        Returns ``"native"`` (attach pixels on the user turn) or ``"text"``
        (pre-analyze with vision_analyze and prepend the description). See
        agent/image_routing.py for the full decision table.

        Gateway sessions can have /model overrides that live outside
        config.yaml. Image preprocessing runs before AIAgent sets the
        auxiliary_client runtime globals, so resolve the same per-session
        runtime bundle the upcoming agent turn will use instead of consulting
        only the persisted default model.
        r   )decide_image_input_mode)_read_main_model_read_main_providerr7  r   Nr  r  r~  uO   image_routing: session runtime resolution failed, falling back to config — %s)r~  u;   image_routing: decision failed, falling back to text — %sr   )r  r  r0
  r  r  rg  r8  rR   rS   rV   rX  rU   rT   r.   r/   r0   )r  r  r  r  r  r  r  r  r  r8  rk  resolved_providerresolved_modelresolved_requested_providerneeds_session_runtimehas_session_identityr~  r  runtime_providerruntime_requested_providerr5   s                        r6   re  z&GatewayRunner._decide_image_input_modeR  s   *2	CCCCCCTTTTTTTT555555!+K!>!>Q++KKMMC!)R 6 6 8 8#kr0022N*,'(9$9$O=O!#)#5#D $ )= 151T1T%$/$' 2U 2 2.J
 * <jS.I.I <)3)9)9););ISTbdhIiIi's~'9'9*'E'E'Eos$ &nd;;"**+?@@@! /
 - E<Lc1R1R E,<,B,B,D,D)!"<cBB Y6P6V6V6X6X3    LLi        % :$7$7$9$9!! 4!1!1!3!3**!#>	     	 	 	LLVX[\\\66666	sC   A5G 8C2E+ *G +
F5FG F)G 
G4G//G4	user_textrz  c                 l  K   ddl m} ddlm} d}g }|D ]}	 t                              d|            |||           d{V }t          j        |          }	|	                    d          r>|	                    d	d
          }
 ||
          }
|	                    d|
 d| d           n|	                    d| d           # t          $ r>}t                              d|           |	                    d| d           Y d}~d}~ww xY w|r d                    |          }|r| d| S |S |S )a  
        Auto-analyze user-attached images with the vision tool and prepend
        the descriptions to the message text.

        Each image is analyzed with a general-purpose prompt.  The resulting
        description *and* the local cache path are injected so the model can:
          1. Immediately understand what the user sent (no extra tool call).
          2. Re-examine the image with vision_analyze if it needs more detail.

        Args:
            user_text:   The user's original caption / message text.
            image_paths: List of local file paths to cached images.

        Returns:
            The enriched message string with vision descriptions prepended.
        r   )vision_analyze_tool)sanitize_contextzDescribe everything visible in this image in thorough detail. Include any text, code, data, objects, people, layout, colors, and any other notable visual information.zAuto-analyzing user image: %s)r(  user_promptNr  analysisr   z0[The user sent an image~ Here's what I can see:
zA]
[If you need a closer look, use vision_analyze with image_url: z ~]z[The user sent an image but I couldn't quite see it this time (>_<) You can try looking at it yourself with vision_analyze using image_url: ro  zVision auto-analysis error: %sz[The user sent an image but something went wrong when I tried to look at it~ You can try examining it yourself with vision_analyze using image_url: r   )tools.vision_toolsr  agent.memory_managerr  r/   r0   r  r  rT   rs   r.   r  rD   )r  r  rz  r  r  analysis_promptenriched_partsrx   rv  r  r   rs  r  s                r6   rg  z)GatewayRunner._enrich_message_with_visionR  s#     * 	;:::::9999998 	  	 	D<dCCC$7$7" /% % %       K00::i(( "(**Z"<"<K"2"2;"?"?K"))0K 0 0&*0 0 0    #))H@DH H H  
    =qAAA%%D<@D D D         	[[00F 2 11i111Ms   B.C
D4D

Dr{  c                 l  K   t                      fd|D             }t          | j        dd          sg }|D ]n}t          j                            |          }t          |           d{V }|r|                    d| d| d           U|                    d| d           o|s|g fS d	                    |          }d
}|r|	                                |k    r|g fS |r	| d	| g fS |g fS 	 ddl
m}	m}
 nm# t          $ r`}t                              d|           d}d
}|r!|	                                |k    r	|g fcY d}~S |r| d	| g fcY d}~S |g fcY d}~S d}~ww xY wg }g }|D ]}	 t                              d|           t#          j        |	|           d{V }|                    d          sMt#          j        |
|           d{V }|                    d          rt                              d|           |}|d         rc|d         }|pd	                                s|                    d           |                    |           |                    d| d           ny|                    dd          }t                              d||           ddlm}  |t          j                            |                    }|                    d| d           # t.          $ rm}t                              d|           ddlm}  |t          j                            |                    }|                    d| d           Y d}~d}~ww xY w|rDd	                    |          }d
}|r|	                                |k    r||fS |r	| d	| |fS ||fS ||fS )aF  
        Auto-transcribe user voice/audio messages using the configured STT provider
        and prepend the transcript to the message text.

        Args:
            user_text:   The user's original caption / message text.
            audio_paths: List of local file paths to cached audio files.

        Returns:
            A tuple of ``(enriched_text, successful_transcripts)``:
              - ``enriched_text``: the message string with transcription wrappers
                prepended (same as before).
              - ``successful_transcripts``: the raw transcript strings for audio
                clips that were successfully transcribed, in input order. Empty
                list if every clip failed or STT is disabled. Callers can use
                this to echo transcripts back to the user before the agent loop.
        c                 F    g | ]}|v                     |          |S r,  )rv   )r?   r  r   s     r6   r  zDGatewayRunner._enrich_message_with_transcription.<locals>.<listcomp>US  s-    SSSQ$txxPQ{{qrB   stt_enabledTNz [The user sent a voice message: z (duration: z)]ro  r   z.(The user sent a message with no text content)r   )transcribe_audiotranscribe_audio_local_fallbackz$Transcription module unavailable: %sz([voice message could not be transcribed]zTranscribing user voice: %sr  z6Configured STT failed for %s; recovered with local STTr  r   u   [The user sent a voice message but it came through empty or inaudible — speech-to-text returned no words. Do not guess at the content; ask the user to resend or type it out.]r  r  r  z%Voice transcription failed for %s: %srF  zR[voice message could not be transcribed automatically; the audio is available at: zTranscription error: %s)rt   r-   rX   rq   rx   abspathr  rs   rD   rV   tools.transcription_toolsr  r  ModuleNotFoundErrorr/   r  r0   r  r  rT   r  rj  rG  r.   )r  r  r{  notesrx   abs_pathduration_strr  _placeholderr  r  rs  unavailable_noter  r	  r  r  r  r  rG  r  r   s                        @r6   rh  z0GatewayRunner._enrich_message_with_transcription>S  s     , uuSSSS+SSSt{M488 	E# Q Q7??400%:8%D%DDDDDDD QLLa8aaQ]aaa    LL!OH!O!O!OPPPP % "}$[[''FKL "Y__..,>>rz! 6 11i112552:	(         # 	( 	( 	(LL?CCCIKL ,Y__..,>>'+++++++ @*;;	;;R???????#R'''''''	( ,. @	 @	D?:DAAA&01A4HHHHHHHHzz),, 
*%,%67& &            H  ||I.. *T    "*)$ (!'!5J ',"3355 !&--9   !*11*=== #))*;j*;*;*;<<<<"JJw@@E KK GuUUURRRRRR!<!<RW__T=R=R!S!SJ"))D6@D D D      6:::NNNNNN889N9NOO
%%@2<@ @ @         		2[[00F LL 6Y__..,>>555 J 11i113III111000sW   4C= =
E'<E"E'	
E"E'E"E'"E'4CK2B(K22
M)<A"M$$M)c                     g }t          |dd          pg }t          |          D ]*\  }}t          ||          r|                    |           +|S )z7Return STT-eligible paths from a pending voice message.r  N)r-   r  r  rs   )r  r  r{  r  r  rx   s         r6   r	  z(GatewayRunner._pending_event_audio_pathsS  se    !#UL$77=2
 ,, 	) 	)GAt(22 )""4(((rB   c                   K   t          |d          r4t          |d          }t          |dg           pg }|t          |          fS |                     |          }|s||nt          |dd          pdg fS ||nt          |dd          pd}|                     ||           d{V \  }}t          |d|           t          |dt          |                     ||fS )aW  Transcribe a pending audio event once and cache the result on the event.

        Voice follow-ups can be inspected first by the interrupt monitor and
        later consumed by the pending-drain path.  Both need the same transcript,
        but only one STT call and one transcript echo should happen for the
        platform message.
        r@   _gateway_pending_stt_transcriptsNr   r   )r   r-   r  r	  rh  r
  )	r  r  r  cached_textcached_transcriptsr{  r   r	  r	  s	            r6   r  z2GatewayRunner._transcribe_pending_audio_event_onceS  s9      5566 	9!%)DEEK!(0RTV!W!W!][]%7 8 88855e<< 	f ) 599GE6SW<X<X<`\`ceee%1yyvr8R8R8XVX6:6]6]7
 7
 1
 1
 1
 1
 1
 1
-- 	2MBBB94@V;W;WXXX444rB   
Transcriptr   r	  transcriptsr	  c                  K   |r|                                  r|dS t          t          |dd          pd          }||d         }t          |d|t	          |          z              |D ]]}		 |                    |j        d|	 d|           d{V  +# t          $ r&}
t          	                    d||
           Y d}
~
Vd}
~
ww xY wdS )a  Echo pending-event STT transcripts to the chat at most once.

        The already-echoed transcripts are tracked as a COUNT rather than a
        single boolean.  ``merge_pending_message_event`` can append a second
        voice note to an event whose first transcript was already echoed and
        invalidates the transcription cache; the re-run transcription then
        returns the earlier transcripts as a prefix of the new list, so
        echoing only the unsent tail suppresses the repeat while still
        surfacing the newly merged note.  A count rather than a set of seen
        values because two separate notes that transcribe identically are two
        distinct deliveries and both must be echoed.
        N_gateway_pending_stt_echoedr   rE  r  r  z%s echo failed (non-fatal): %s)
ri  rF  r-   r
  r   r  r  r.   r/   r0   )r  r  r  r  r  r   r	  already_echoedunsenttxecho_excs              r6   "_echo_pending_stt_transcripts_oncez0GatewayRunner._echo_pending_stt_transcripts_onceS  s>     . 	4466	 FWU,I1MMRQRSS^__-4ns6{{6RSSS 	V 	VBVllN%%%%% #          
  V V V={HUUUUUUUUV	V 	Vs   -'B
CC  Cr  c                  K   |                      |          s|g fS 	 |                     ||           d{V \  }}|t          u r)|                     ||                     |                    n|}	|                     |||||	|           d{V  |p||fS # t          $ r*}
t                              d||
           |g fcY d}
~
S d}
~
ww xY w)a]  Transcribe a pending voice event and echo transcripts once.

        Unified helper for all interrupt/monitor/backup/drain paths that need
        to transcribe a pending voice event and echo the transcript to chat.
        Returns ``(enriched_text, transcripts)`` so the caller can feed the
        enriched text into ``agent.interrupt()`` or the pending-drain flow.

        If the event has no STT-eligible media, returns ``(text, [])`` unchanged.
        The caller is responsible for the ``_build_media_placeholder`` fallback
        when ``text`` is empty and the event has non-audio media.
        Nr  z%s transcription failed: %s)	r	  r  _UNSETr	  r=  r  r.   r/   r   )r  r  r  r  r   r	  r   r	  r  	echo_meta	trans_excs              r6   r	  z0GatewayRunner._transcribe_and_echo_pending_voiceT  sY     * ..u55 	8O	/3/X/X0 0 * * * * * *&M; V## 88,,U33   *2  99"' :          !(D+55 	 	 	NN8+yQQQ8OOOOOO	s   A9B 
C!C CCr  c                    ddl m} t          |                    d          pd                                          }d}d}d}|r	 | j                                         | j        j                            |          }|rt          |dd          r|j	        S n3# t          $ r&}t                              d||           Y d}~nd}~ww xY w|                     |          }	|	|	S t          |          }
|
r|
d         }|
d	         }|
d
         }t          |                    d          p|pd                                                                          }t          |                    d	          p|pd                                                                          }t          |                    d
          p|pd                                          }|r|r|s5t                              d|||||                    dd                     dS 	 t#          |          }|j        t&          vrN	 ddlm} |                    |j                  st/          |          n# t          $ r t/          |          w xY wn,# t          $ r t                              d|           Y dS w xY w ||||t          |                    d          pd                                          pdt          |                    d          pd                                          pdt          |                    d          pd                                          pd          S )a  Resolve the canonical source for a synthetic background-process event.

        Prefer the persisted session-store origin for the event's session key.
        Falling back to the currently active foreground event is what causes
        cross-topic bleed, so don't do that.
        r   )r%  r  r   r	  Nz>Synthetic process-event session-store lookup failed for %s: %sr_   r}  r  zcSynthetic event source unresolvable: session_key=%r platform=%r chat_type=%r chat_id=%r evt_type=%sr   r  r  z9Synthetic process event has invalid platform metadata: %rrd  r  r  )r_   r  r}  rd  r  r  )rP  r%  rU   rT   rV   rf  r	  r  r-   r	  r.   r/   r0   r	  r  rW   r   r  r   r   rF  r  r  rH  )r  r  r%  r  derived_platformderived_chat_typederived_chat_idr  r5   cached_sourcer
  r.  r}  r  r_   r  s                   r6   _build_process_event_sourcez)GatewayRunner._build_process_event_sourceGT  s    	211111#''-006B77==?? 	5
"11333*377DD (WUHd;; ( <'   T        !;;KHHM($$(55G 5#*:#6 $+K$8!"))"4CGGJ//I3CIrJJPPRRXXZZ,,G0AGRHHNNPPVVXX	cggi((AOArBBHHJJ 	I 	W 	NN ]Iw$$   4	..H ~%===4KKKKKK,::8>JJ 8(7778  4 4 4$]3334 	 	 	NNK   44	 }#''+..4"55;;==E	**0b117799AT#''+..4"55;;==E
 
 
 	
sC   AB 
C	#CC	J 4/I$ #J $I>>J %J+*J+r  c                   K   |                      |          }|spt          |                    d          pd                                          }|sIt          |                    d          pd                                          }|rt	          |          |}|r| j                            t          j                  }ddlm	}m
} |q ||          sf	 t                              d|            ||||           d{V  d	S # t          $ r'}	t                              d
||	           Y d}	~	dS d}	~	ww xY wt                              d|           dS t                              d|                    dd                     dS t          |j        d          r|j        j        nt          |j                  }
d}| j                                        D ]\  }}|j        |
k    r|} n|sdS ddlm	}  ||          sddlm
} t          |                    d          pd                                          pt          |j        pd          }	 t                              d|            ||||           d{V  d	S # t          $ r'}	t                              d
||	           Y d}	~	dS d}	~	ww xY w	 i }t          |                    d          pd                                          }|r||d<   t)          |t*          j        |d	t          |                    d          pd                                          pd|          }t                              d|
|j        |j                   |                    |           d{V  d	S # t          $ r&}	t                              d|	           Y d}	~	dS d}	~	ww xY w)a  Inject a watch/completion notification as a synthetic message event.

        Routing must come from the queued event itself, not from whatever
        foreground message happened to be active when the queue was drained.
        Returns ``True`` after adapter acceptance, ``False`` after a retryable
        adapter failure, and ``None`` when the event has no gateway route. This
        is not a transactional boundary: a process crash after adapter
        acceptance can still cause durable at-least-once replay.
        origin_session_idr   r  Nr   )adapter_supports_pushdeliver_wakeuI   Watch pattern notification — waking api_server session %s via self-post)r   r%   Tz;Watch notification self-post wake failed for session %s: %sFzZDropping watch notification for raw session %s: no api_server adapter to self-post throughzCDropping watch notification with no routing metadata for process %sr%   r  r   )r  )r  parent_session_idr  r4  )r   r  r  r	  r4  r   uA   Watch pattern notification — injecting for %s chat=%s thread=%sr   )r  rU   rT   rV   r  r{  r  r  gateway.waker  r  r/   r  r.   r   r   r_   r   r  r  r:  r;  r	  rd  r
  r  )r  r  r  r  raw_sidrK  r  r  r  rs  r.  r  r
  _wake_push_okr   r  synth_events                    r6   r3  z(GatewayRunner._inject_watch_notificationT  s      11#66 *	 #''"566<"==CCEEG "#''-006B77==?? "-c22:!G -++H,?@@LLLLLLLL&/D/DW/M/M&%7#  
 +l7PWXXXXXXXXXX#t$ % % %-#Q  
  %uuuuu% >  
 tNNUi00   418'1R1Rl--X[\b\kXlXlM'')) 	 	DAqw-'' (  	4GGGGGG}W%% 	 211111#''"566<"==CCEEbV^Ma_aIbIbG'  
 #l7PPPPPPPPPPt   Q  
 uuuuu	H #CGG,?$@$@$FB G G M M O O  C1B-.&(-sww|44:;;AACCKt!  K KKS 	   ((5555555554 	 	 	LLA1EEE55555	sI   /D	 	
D:D55D:/J	 	
J:J55J:>CN 
O OOc                 D   t          |                     d          pd          }|dk    r-t          |                     d          pd          }|r||dfndS |dk    rBt          |                     d          pd          }|                     d          }|r||||fS dS )	a  Return a producer-stable identity when one is available.

        Delegation UUIDs identify one producer completion. Process session IDs
        are normally unique too, but include the persisted spawn epoch so an
        explicitly reused ID represents a distinct process incarnation. Legacy
        process events without ``started_at`` are delivered without deduplication
        rather than risking suppression of a real completion.
        r   r   r  delegation_idNr  r%   r  )rU   rT   )r  r  producer_idr  s       r6   _completion_delivery_identityz+GatewayRunner._completion_delivery_identityU  s     swwv,"--)))cggo66<"==K2=GHk2..4G|##cggl339r::K..J ;z5 +z::trB   r  c                 H  K   t          | dd          }|dS 	 |                    |           d{V }n.# t          $ r! t                              d|d           Y dS w xY w|dS |                    d          sd	S |                    d
          dk    rdS 	 |                    |           d{V }|r||k    rdS |                    |           d{V }n.# t          $ r! t                              d|d           Y dS w xY w||                    d          rdS d	S )u0  Classify an async-completion delivery target before adapter acceptance.

        Returns one of:

        - ``"deliver"`` — the spawning session is live, or ended by a
          compression rotation with a verified live continuation. The inner
          #55578 resolver (:meth:`_resolve_async_delegation_session`) still
          owns the actual route retarget; this pre-flight only proves the
          completion is deliverable so the durable ack stays honest.
        - ``"terminal"`` — the spawning session is gone for good (unknown, or
          ended at an explicit user boundary such as /new). Delivery can never
          succeed; the durable row should be terminally dropped rather than
          falsely acknowledged as delivered or replayed forever as pending.
        - ``"retry"`` — transient uncertainty (session DB unavailable, lookup
          error, or a compression rotation caught mid-flight before its
          continuation exists). The claim should be released so a later
          consumer can retry; the attempt cap bounds the churn.
        r)   Nro  z7Async-completion pre-flight parent lookup failed for %sTr   r  r  deliverr  rK   z4Async-completion pre-flight tip lookup failed for %s)r-   rh  r.   r/   r0   rT   r  )r  r  r3   rp   tip_session_idtips         r6   _classify_completion_targetz)GatewayRunner._classify_completion_targetU  s     & T=$77
7	%112CDDDDDDDDFF 	 	 	LLI!D     77	 >:zz*%% 	9::l##}44:	#-#A#ABS#T#TTTTTTTN! ^7H%H%H w"..~>>>>>>>>CC 	 	 	LLF!D     77	 ;#''*--;7ys'   5 'A A #C ?C 'DDc                 	  K   |                      |          }d}d}|                    d          dk    rt          |                    d          pd          }|r	 ddlm} dt          |            dt          d	                                          j         } |||          sd
S n4# t          $ r'}t                              d||           Y d
}~dS d
}~ww xY wt          |                    d          pd                                          }|r|                     |           d
{V }	|	dk    rbt                              d|pd|           |r@	 ddlm}
  |
||           n,# t          $ r t                              dd           Y nw xY wd
S |	dk    rD|r@	 ddlm}  |||           n,# t          $ r t                              dd           Y nw xY wdS |Y| j        5  || j        v s	|| j        v r	 d
d
d
           d
S | j                            |           d
d
d
           n# 1 swxY w Y   d}	 |                     ||           d
{V }|dur||;|s9| j        5  | j                            |           d
d
d
           n# 1 swxY w Y   |rB|sA	 ddlm}  |||           S # t          $ r t                              dd           Y S w xY wS S d}|| j        5  | j                            |           d
| j        |<   t/          | j                  | j        k    r8| j                            d           t/          | j                  | j        k    8d
d
d
           n# 1 swxY w Y   |rG	 ddlm}  |||           n3# t          $ r&}t                              d||           Y d
}~nd
}~ww xY w	 |;|s9| j        5  | j                            |           d
d
d
           n# 1 swxY w Y   |rD|sD	 ddlm}  |||           dS # t          $ r  t                              dd           Y dS w xY wdS dS # |;|s9| j        5  | j                            |           d
d
d
           n# 1 swxY w Y   |rB|sA	 ddlm}  |||           w # t          $ r t                              dd           Y w w xY ww w xY w)a  Deliver once per live gateway, or return False for a retry.

        ``True`` means this caller reached adapter acceptance, ``False`` means
        injection failed and the claim was released for retry, and ``None``
        means either another same-lifecycle caller owns/delivered the producer
        event or the event has no gateway route. No cross-process exactly-once
        guarantee is claimed.
        r   r   r  r  r   )claim_completion_deliveryrk	  r  r  Nz/Could not claim durable async completion %s: %sFr  r  zAsync delegation %s targets permanently-gone session %s; terminally dropping delivery (result remains in the delegation records).z<legacy>)drop_completion_deliveryz'Could not drop durable completion claimTr   ro  )release_completion_deliveryz*Could not release durable completion claimr  )complete_completion_deliveryz5Could not acknowledge durable async completion %s: %s)r  rT   rU   r  r  r   
__import__r  r  r.   r/   r   rV   r  r  r0   r  rw  rx  ry  rv   r3  r  r   rz  r  r  )r  r  r  identitydurable_claim_iddurable_delegation_idr  r5   r  verdictr  r  r4  injection_resultr  s                  r6    _deliver_completion_notificationz.GatewayRunner._deliver_completion_notificationPU  s"	      55c:: "776??000$'(@(@(FB$G$G!$ !!PPPPPP']"T((']']Z=O=O=U=U=W=W=[']']$44-/?  $  $t$ ! ! ! !NNI-s   !55555! !$CGG,?$@$@$FB G G M M O O  )! !% @ @AR S SSSSSSSj((NN/ .;=N	   ( 
WWWWWW44 57G     )   "LL I)- )     
  4g%%' 
ZZZZZZ77 57G     )   "LL L)- )     
 !5/ C C DDD4#HHHC C C C C C C C 488BBBC C C C C C C C C C C C C C C ,	^%)%D%DZQT%U%UUUUUUUt++'< #H#3 K K8@@JJJK K K K K K K K K K K K K K K ^ ^^RRRRRR//-/?    ! ^ ^ ^LL!MX\L]]]]]^^ ^A H#3 R R8@@JJJFJD9(CDABB=> > =EE5EQQQ DABB=> >	R R R R R R R R R R R R R R R   
SSSSSS00-/?    !   NNO-s       
 #H#3 K K8@@JJJK K K K K K K K K K K K K K K ^ ^^RRRRRR//-/?     ! ^ ^ ^LL!MX\L]]]]]]^^ ^ ^ ^ #H#3 K K8@@JJJK K K K K K K K K K K K K K K ^ ^^RRRRRR//-/?    ! ^ ^ ^LL!MX\L]]]]]^^ ^sF  AB+ +
C5CCE, ,&FF#F6 6&GG-H4H44H8;H8!Q .JJ	J	%J88&K! K!&Q 1A:M7+Q 7M;;Q >M;?Q N Q 
O"O>Q OQ O>>PPP" "&QQSR:SR

SR
SR)(S)&SSSSc                 `   |                     d          rdS t          |                     dd          pd          }|sdS |                     dd          |d<   |                     dd          |d<   |                     dd          |d<   |                     d          r|d         |d<   dS dS )a  Fill platform/chat_id/thread_id/chat_type on an async-delegation event.

        Async-delegation completion events only carry ``session_key`` (the
        daemon worker has no access to the per-message routing metadata the
        terminal background watcher captures at spawn time). Parse the
        session_key into the routing fields ``_build_process_event_source``
        expects. Best-effort: a CLI-origin event (empty session_key) is left
        as-is and simply won't route on the gateway.
        r_   Nr  r   r}  r  rd  )rT   r  )r  r  r  s      r6    _enrich_async_delegation_routingz.GatewayRunner._enrich_async_delegation_routingU  s     77: 	F#CGGM2$>$>$D"EE 	F **Z44J!::k266KIr22I::k"" 	3%k2C	3 	3rB   c                   K   t          j        d           d{V  ddlm} | j        r	 g }g }|j                                        s	 |j                                        }n# t          $ r Y naw xY w|	                    d          dk    r|
                    |           n|
                    |           |j                                        |D ]}|j                            |           |D ]}|                     |           t          |          }|s)	 |                     ||           d{V }|du r|j                            |           e# t          $ r?}|j                            |           t                              d|           Y d}~d}~ww xY wn2# t          $ r%}t                              d	|           Y d}~nd}~ww xY wt          j        |           d{V  | j        dS dS )
u  Drain async-delegation completions and inject them as new turns.

        Background subagents (``delegate_task(background=true)``) run on the
        async-delegation daemon executor — they have no per-process watcher
        task, so their completion events would only be seen by the post-turn
        queue drain. This watcher covers the IDLE case: when a background
        subagent finishes while no agent turn is running, its result still
        re-enters the originating session promptly.

        Mirrors the CLI's idle ``process_loop`` drain. Stays silent when the
        queue has nothing for us; ignores non-async event types (those are
        handled by ``_run_process_watcher`` / the post-turn drain).
        r  Nr   r  r   r  Fz$Async delegation injection error: %sz"Async delegation watcher error: %s)r  r`  r  r  rf  r  r  r  r.   rT   rs   r  r  r  r  r/   r  r0   )	r  r  r  r  async_eventsr  r  r  rs  s	            r6   rj  z'GatewayRunner._async_delegation_watcherU  s      mABBBBBBm  	*F !.4466 ,!2==??$   wwv*<<<$++C0000s+++ .4466 , # 2 2C(,,S1111' P PC99#>>>!Ec!J!JJ% ! P*.*O*OPZ\_*`*`$`$`$`$`$`$`	$--044S999$ P P P,00555%KQOOOOOOOOPP  F F FA1EEEEEEEEF-)))))))))A m  	*  	*  	*  	*  	*sf   F$ 
A$ #F$ $
A1.F$ 0A11B*F$ :EF$ 
F !5FF$ F  F$ $
G.GGr`
  c                 .  K   ddl m} |d         }|d         }|                    dd          }|                    dd          }|                    dd          }|                    d	d          }|                    d
d          }	|                    dd          }
t          |                    d          pd                                          pd}|                    dd          }|                                 }t                              d||||           |dk    rZ|sX	 t          j	        |           d{V  |                    |          }||j
        rn:t                              d|           dS d}	 t          j	        |           d{V  |                    |          }|nt          |j                  }||k    }|}|j
        rddl m}m} |rv|                    |          s`ddlm} ddlm} t'          |dd          pd}|j        r ||j                  nd} |||          }t)          |          }d}t          |          |k    rK|| d         }|                    d          }|dk    r||dz   d         n|}dt          |           d| }n|}i ddd|d|d|d |                    d d          d|d	|d
|	d|
d|d!t'          |d!d          d|d"|j        d#t'          |d#d$          d%t'          |d%d          d&|} ||          }|snF|                     ||           d{V }|du rאn"|                    |          rt                              d'|           n|d(v p|d)k    o|j        d*v}|r|j        r|j        d+d         nd} | r#ddlm}  || t'          |dd          pd          } d,| d-|j         d.|  d/}!d}"| j                                        D ]\  }#}$|#j        |k    r|$}" n|"rk|ri	 |rd	|ind}%|"                    ||!t9          |%|0          1           d{V  n2# t:          $ r%}&t                              d2|&           Y d}&~&nd}&~&ww xY wn|r|d3k    r|s|j        r|j        d4d         nd} | r#ddlm}  || t'          |dd          pd          } d,| d5|  d/}!d}"| j                                        D ]\  }#}$|#j        |k    r|$}" n|"rk|ri	 |rd	|ind}%|"                    ||!t9          |%|0          1           d{V  n2# t:          $ r%}&t                              d2|&           Y d}&~&nd}&~&ww xY wt                              d6|           dS )7u  
        Periodically check a background process and push updates to the user.

        Runs as an asyncio task. Stays silent when nothing changed.
        Auto-removes when the process exits or is killed.

        Notification mode (from ``display.background_process_notifications``):
          - ``all``    — running-output updates + final message
          - ``result`` — final completion message only
          - ``error``  — final message only when exit code != 0
          - ``off``    — no messages at all
        r   r  r%   check_intervalr  r   r_   r  rd  r  r  r4  Nnotify_on_completeFzCProcess watcher started: %s (every %ss, notify=%s, agent_notify=%s)r  Tz"Process watcher ended (silent): %s)r  r  )redact_terminal_outputrc  r   rR  r   r   rk   u'   [… output truncated — showing last z chars]
r   r  r}  r  r  completion_reasonexitedtermination_sourcer  ug   Process watcher: completion for %s already consumed via wait/log — skipping raw notification (#65379)>   r  r  r  >   Nr   iz[Background process z finished with exit code z~ Here's the final output:
ro  rc   r  zWatcher delivery error: %sr  iz is still running~ New output:
zProcess watcher ended: %s)r  r  rT   rU   rV   rM	  r/   r0   r  r`  r  r   output_bufferr  is_completion_consumedr   r  re  rd  r-   r   r  r  r  r{  r  r   r  r   r.   r  )'r  r`
  r  r%   r  r  r.  r  rd  r  r  r4  agent_notifynotify_moder	  last_output_lencurrent_output_lenhas_new_outputr  	_pr_checkr  rd  _command_raw_LIMIT_tail_nlr  completion_evtr  r  rP  
new_outputrs  r  r  r
  	send_metars  s'                                          r6   r)  z"GatewayRunner._run_process_watcherV  s      	<;;;;;\*
+,kk-44J33++i,,KKR00	++i,,KKR00	\228b99??AAIT
{{#7??>>@@Z (K	G 	G 	G %mH---------*..z::?gn?	
 LL=zJJJFP	F-)))))))))&**:66G!$W%:!;!;//AN0O~ EF
 nmmmmmmm /	(H(H(T(T /CCCCCC;;;;;;&w	2>>D"H@G@U]::g&;<<<[]D11$AADB8LLH
 "F4yy6)) $fWXX#jj..36"99cAghh%eUee^cee#&&$j& &{& #M	&
 $W[[b%A%A& "7& $Y& "7& $Y& %j& %gg|T&J&J& "8& $W%6& ,WW>QS[-\-\& -gg?SUW.X.X&  !$!&N$ "=!<^!L!LJ% &*&K&K"N' ' ! ! ! ! ! !I !E)) ! 33J?? LLN"  
   #44 W#w.U73DI3U  ! JBIBW!_!6uvv!>!>]_J! GGGGGG%;%;&B(G(G(M2& &
Cz C CT[Te C C5?C C C ! #G $ 3 3 5 5 " "17m33&'G!E 4  	J7 	JJDM(Wi(@(@SWI"),, ' ,)EiZg)h)h)h #/ # #        
  ) J J J"LL)EqIIIIIIIIJ FK5$8$8$8 >E=RZW245599XZ
 CCCCCC!7!7"GGY$C$C$Ir" "J2: 2 2$.2 2 2   M//11  DAqw-//"# 0  	Fw 	FF@I$S[)$<$<t	%ll#(%A)Vc%d%d%d +          
 % F F F%A1EEEEEEEEF_P	Fd 	0*=====s0   "5Q 
R"RR5U 
U5U00U5))r  r3  )r  r|  )rK   r  )rK   rL   )rK   	threshold)rK   model_thresholds)rK   threshold_tokens)rK   codex_gpt55_autoraise)rK   codex_app_server_auto)rK   target_ratio)rK   protect_last_n)rK   proactive_prune_tokens)rK    proactive_prune_min_result_chars)rK   "proactive_prune_min_reclaim_tokens)rK   min_tail_user_messages)r   r  )re  r  )rR  r  )rR  rT  )rR  rU  )rR  rV  _CACHE_BUSTING_CONFIG_KEYSzhoncho.peer_namezhoncho.ai_peerzhoncho.pin_peer_namezhoncho.runtime_peer_prefixzhoncho.user_peer_aliases_HONCHO_CACHE_BUSTING_MEMOc                 $    d | j         D             S )Nc                     i | ]}|d S r;   r,  )r?   r  s     r6   r  zDGatewayRunner._empty_honcho_cache_busting_config.<locals>.<dictcomp>W  s    DDDcTDDDrB   )_HONCHO_CACHE_BUSTING_KEYS)clss    r6   "_empty_honcho_cache_busting_configz0GatewayRunner._empty_honcho_cache_busting_configW  s    DDS%CDDDDrB   c                 r   	 ddl m}m}  |            }	 |                                j        }n# t
          $ r d}Y nw xY wt          |          |f}| j                            |          }|t          |          S |
                    |          }|j        pi }|j        |j        t          |j                  |j        pdt#          |t                    r!t%          |                                          ng d}	||	i| _        t          |	          S # t(          $ r |                                 cY S w xY w)z<Extract Honcho identity keys, memoized by honcho.json mtime.r   )HonchoClientConfigresolve_config_pathN)rj  r   r!  )plugins.memory.honcho.clientr)  r*  statst_mtime_nsru   rU   r"  rT   rS   from_global_configuser_peer_aliases	peer_nameai_peerr   pin_peer_nameruntime_peer_prefixrR   r  r  r.   r'  )
r&  r)  r*  rx   mtime_nsmemo_keyr  hcfgaliasesr_  s
             r6   $_extract_honcho_cache_busting_configz2GatewayRunner._extract_honcho_cache_busting_configW  sj   	<\\\\\\\\&&((D 99;;2       D		8,H377AAF!F||#%88T8JJD,2G$(N"&,(,T-?(@(@.2.F.L"GQRY[_G`G`,hF7==??,C,C,Cfh F /7-?C*<< 	< 	< 	<99;;;;;	<s3   D / D >D >>D =BD D65D6c                    i }t          |t                    r|ni }| j        D ]\  }}|                    |          }|dk    r(t          |t                    r|dk    r|nd|| d| <   Ht          |t                    r|                    |          || d| <   {d|| d| <   	 ddlm} t          |dd          |d<   n# t          $ r d|d<   Y nw xY wt          |d	d
          }t          |t                    r@|                                dk    r(|                    |                                            n'|                    |                                            |S )al  Pull values that must bust the cached agent.

        Returns a flat dict keyed by 'section.key'.  Missing config keys and
        non-dict sections yield None values, which still contribute to the
        signature (so 'absent' vs 'present-and-null' differ).

        The live tool registry generation is included too.  MCP reloads and
        dynamic MCP tool-list changes mutate the registry without necessarily
        changing config.yaml.  Cached AIAgent instances freeze their tool
        schemas at construction time, so a registry generation change must
        rebuild the agent before the next turn.
        rR  r  Nr   r   )registry_generationztools.registry_generationre  r  honcho)rR   rS   r   rT   r   tools.registryr:  r-   r.   r   rU   rW   r  r8  r'  )	r&  r  rs
  rk  sectionr  section_valr:  r  s	            r6   re  z+GatewayRunner._extract_cache_busting_config$W  s    !'T::Bkk: 		/ 		/LGS'''**K-''J{D,I,I' :=	9I9I++tw&&&&''K.. /*5//#*>*>w&&&&''*.w&&&&''	4///////6xPT/U/UC+,, 	4 	4 	4/3C+,,,	4
 3*55h$$ 	A)9)9X)E)EJJs??AABBBBJJs==??@@@
s   *C CCr  r  ephemeral_promptr  r  r  c                    ddl }ddl}	t          |                    dd          pd          }
|
r9|                    |
                                                                          nd}t          |pi                                           }|		                    | ||                    dd          |                    dd          |                    dd          |                    dd          |rt          |          ng |pd|t          |pd          t          |pd          t          |          gd	t          
          }|                    |                                                                          dd         S )u:  Compute a stable string key from agent config values.

        When this signature changes between messages, the cached AIAgent is
        discarded and rebuilt.  When it stays the same, the cached agent is
        reused — preserving the frozen system prompt and tool schemas for
        prompt cache hits.

        ``cache_keys`` is an optional flat dict of additional config values
        that should invalidate the cache when they change.  Callers pass
        the output of ``_extract_cache_busting_config(user_config)`` so
        edits to model.context_length / compression.* in config.yaml are
        picked up on the next gateway message without a manual restart.

        ``user_id`` and ``user_id_alt`` are the runtime user identities
        carried by the current message's gateway source.  They participate
        in the cache key because the Honcho memory provider freezes them
        into ``HonchoSessionManager`` at first-message init (see
        ``plugins/memory/honcho/__init__.py::_do_session_init``).  Without
        them in the signature, a shared-thread session_key (one in which
        ``build_session_key`` intentionally omits the participant ID,
        e.g. ``thread_sessions_per_user=False``) would reuse the cached
        AIAgent across distinct users, causing the second user's messages
        to be attributed to the first user's resolved Honcho peer.  This
        broke #27371's per-user-peer contract in multi-user gateways.
        Per-user agent rebuilds in shared threads trade prompt-cache
        warmth for correct memory attribution.
        r   Nr  r   r  r  r~  r  T)	sort_keysr(  r  )r  r  rU   rT   r  r  r  r  r  r  r   )r  r  r  r@  r  r  r  r  r  _j_api_key_api_key_fingerprint_cache_keys_sortedblobs                 r6   rd  z%GatewayRunner._agent_config_signatureOW  s   L 	#""""""" w{{9b117R88PX`w~~hoo.?.?@@JJLLL^`#Z%52$<$<$>$>??xx$J++J++0"55J++,<D'(((" !&B"GMr""K%2&& '((#& +  
 
. ~~dkkmm,,6688"==rB   c                    |                      |          }||j        j        dS t          | dd          }|dS 	 |                    |          }n-# t
          $ r  t                              dd           Y dS w xY w|sdS |                    d          |                    d          |                    d          d	}|                    d          }|r	 t          |          }|                    d
          |d
<   |                    d          |d<   |                    d          |d<   |                    d          s|                    d          |d<   n-# t
          $ r  t                              d|d           Y nw xY w|| 
                    |          j        _        t                              d||                    d          |pd           dS )u  Lazily restore a persisted /model override after a gateway restart.

        ``_session_model_overrides`` is in-memory only, so before persistence
        a restart silently reverted every session to the global default model.
        The non-secret parts (model/provider/base_url) are written through to
        the session store when /model runs (and cleared on /new); here we read
        them back on first use and re-resolve credentials via the normal
        runtime provider resolution — api_key is never persisted to disk.

        No-op when an in-memory override already exists (live state wins) or
        when the store has nothing persisted (e.g. the user ran /new, which
        clears both the in-memory dict and the persisted field).
        Nrf  z/Failed to read persisted session model overrideTr   r  r  r  )r  r  r  r  r  r  zdCredential re-resolution failed for persisted override (provider=%s); using credential-less overridezIRehydrated persisted /model override for session=%s: model=%s provider=%sr   )r  rB  rC  r-   get_model_overrider.   r/   r0   rT   r  r  r  )r  r  _rehydrate_stater
  r8  rD  r  r  s           r6   rG  z/GatewayRunner._rehydrate_session_model_overrideW  s/     33K@@( -<HFot44=F	00==II 	 	 	LLAD     FF		
  	F]]7++!j11!j11$
 $

 ==,, 	
DXNN&-kk)&<&<#'.{{:'>'>$.5kk:K.L.L*+||J// C+2;;z+B+BHZ(   Dt       HPK((5DWg..B	
 	
 	
 	
 	
s$   A &A<;A<BE 'F	F	c                    |                      |          }|r|j        j        nd}|s||fS |                    d|          }dD ]}|                    |          }||||<   |                    d          rO|                    d          :|                    d          r%t	          |                    d                    |d<   ||fS )a  Apply /model session overrides if present, returning (model, runtime_kwargs).

        The gateway /model command stores per-session overrides in
        ``_session_model_overrides``.  These must take precedence over
        config.yaml defaults so the switched model is actually used for
        subsequent messages.  Fields with ``None`` values are skipped so
        partial overrides don't clobber valid config defaults.
        Nr  )r  r  r  r  r  r  r  r  )r  rB  rC  rT   r  )r  r  r  r  _apply_staterD  r  r  s           r6   rH  z+GatewayRunner._apply_session_model_overrideW  s     //<<?KU<,;;QU 	).((We,,U 	* 	*C,,s##C&)s#y))	""#455=Z(( > 1NZ((1 1N,- n$$rB   c                 |    |                      |          }|r|j        j        nd}|du|t          |          nddS )z<Capture a gateway session override before a one-turn switch.N)had_overriderD  )r  rB  rC  rS   )r  r  _snap_staterD  s       r6    _snapshot_session_model_overridez.GatewayRunner._snapshot_session_model_overrideW  sS    ..{;;>IS;+::t$D0*2*>XD
 
 	
rB   r	  c                 ,   |sdS |                     d          rBt          |                     d          pi           |                     |          j        _        n#|                     |          }|d|j        _        |                     |           dS )z?Restore the session override captured before a one-turn switch.NrN  rD  )rT   rS   r  rB  rC  r  r  )r  r  r	  
_rst_states       r6   r=  z-GatewayRunner._restore_session_model_overrideW  s     	F<<'' 	>KOZ((.BL LD,,9HH 11+>>J%9=
'6  -----rB   agent_modelc                     |                      |          }|r|j        j        nd}|duo|                    d          |k    S )zGReturn True if *agent_model* matches an active /model session override.Nr  )r  rB  rC  rT   )r  r  rS  
_ims_staterD  s        r6   _is_intentional_model_switchz*GatewayRunner._is_intentional_model_switchX  sK    --k::
=GQ:*99Tt#LW(=(=(LLrB   r  c                j   |sdS ||                      ||          sdS |                     |          }|i|j        j        }|B	 |                                 n,# t
          $ r t                              dd           Y nw xY w|j                                         | 	                                 dS )u  Pop ALL per-running-agent state entries for ``session_key``.

        Replaces ad-hoc ``del self._running_agents[key]`` calls scattered
        across the gateway.  Those sites had drifted: some popped only
        ``_running_agents``; some also ``_running_agents_ts``; only one
        path also cleared ``_busy_ack_ts``.  Each missed entry was a
        small, persistent leak — a (str_key → float) tuple per session
        per gateway lifetime.

        Use this at every site that ends a running turn, regardless of
        cause (normal completion, /stop, /reset, /resume, sentinel
        cleanup, stale-eviction).  Per-session state that PERSISTS
        across turns (``_session_model_overrides``, ``_voice_mode``,
        ``_pending_approvals``, ``_update_prompt_pending``) is NOT
        touched here — those have their own lifecycles.

        When ``run_generation`` is provided, only clear the slot if that
        generation is still current for the session.  This prevents an
        older async run whose generation was bumped by /stop or /new from
        clobbering a newer run's state during its own unwind.  Returns
        True when the slot was cleared, False when an ownership guard
        blocked it.
        FNz%Failed to release active session slotTr   )
r.  r  r  r  releaser.   r/   r0   r  r	  )r  r  r  r  r  s        r6   r
  z*GatewayRunner._release_running_agent_stateX  s    :  	5%d.J.J/
 /
% 5((55J$E MMOOOO    LL?$ !      J
 	##%%%ts   A &BBc                 H   |sdS t          | dd          }|                     |          }||dS |j        }|j        |j        |k    rdS |j        }d|_        d|_        	 |                    |          S # t          $ r  t                              dd           Y dS w xY w)uI  Release the turn lease acquired by (``session_key``, ``run_generation``).

        Companion to the acquisition in ``_handle_message_with_agent``
        (#64934). The token map is keyed by (routing key, run generation), so
        this can only ever free the lease its own turn acquired — a stale
        unwind whose generation was bumped by /stop or /new pops ITS token,
        and the registry's identity check refuses it if a newer turn already
        holds the lease. Idempotent and safe for bare test runners built via
        ``object.__new__`` (getattr defaults).
        Frr  NzFailed to release turn leaseTr   )	r-   r  r  r  r  rY  r.   r/   r0   )r  r  r  r:  r  r  r  s          r6   r  z!GatewayRunner._release_turn_leaseKX  s      	5466((55=H,5z#t'<'N'N5  $	##E*** 	 	 	LL7$LGGG55	s   "A7 7&B! B!new_session_idc                 .   |r|sdS t          | dd          }|                     |          }||dS |j        }|j        |j        |k    rdS 	 |                    |j        |          S # t          $ r  t                              dd           Y dS w xY w)u  Follow a mid-turn session_id rotation with the held turn lease.

        Compression (session-hygiene pre-compression or the agent's own
        compressor) can rotate ``session_entry.session_id`` while this turn
        is in flight. The turn's flush targets the NEW id, so the
        serialization boundary must follow it — otherwise an alias routing
        key resolving the new id (topic tip-walk onto the fresh child) could
        start a concurrent turn the lease never sees (#64934 rotation-alias
        window). Call at every site that reassigns session_entry.session_id
        mid-turn. Fail-open no-op when there is no held token.
        Frr  NzFailed to rebind turn leaseTr   )	r-   r  r  r  r  rebindr.   r/   r0   )r  r  r  r[  r:  r  r  s          r6   r'  z GatewayRunner._rebind_turn_leasehX  s      	. 	5466((55=H,5z#t'<'N'N5	??4#3^DDD 	 	 	LL6LFFF55	s   A* *&BBc                \   |sdS |                      |          }||j                                         t          D ]>}t	          | |d          }t          |t                    r|                    |d           ?|                     |           t          
                    d||           dS )u  Clear ALL conversation-scoped per-session state for ``session_key``.

        THE single conversation-boundary funnel. Call this — and nothing
        else — whenever a session_key crosses a conversation boundary:
        /new, /resume, auto-reset (idle/daily/suspended), expiry
        finalization, and the compression-exhausted auto-reset.

        Why a funnel: these boundaries used to each carry a hand-copied
        pop-list of the per-session dicts, and the lists drifted every time
        a new dict was added (#48031, #58403, #10702, #35809 were all
        "boundary X forgot dict Y" bugs — e.g. /new cleared the /model
        override but not the /model --once restore snapshot). Adding a new
        conversation-scoped dict now means adding its attribute name to
        _CONVERSATION_SCOPED_STATE below; every boundary picks it up
        automatically.

        Scope rules:
        - Conversation-scoped (cleared here): model/reasoning overrides,
          one-turn restore snapshots, pending model notes, last-resolved
          model cache, queued follow-up events, and the boundary security
          state (approvals, /yolo, slash-confirm, update prompts).
        - Turn-scoped (NOT cleared here): _running_agents/_ts, slot leases,
          turn-lease tokens — owned by _release_running_agent_state and the
          dispatch finally.
        - Idle agent-cache eviction is NOT a conversation boundary: the
          session is still alive and a resumed turn rebuilds from these
          overrides. Only true boundaries call this.

        Safe on bare test runners built via ``object.__new__`` (every
        access is getattr-guarded).
        Nz&Cleared conversation scope for %s (%s))r  rB  r  rt  r-   rR   rS   r$  &_clear_session_boundary_security_stater/   r0   )r  r  rj  r  r  r
  s         r6   r  z'GatewayRunner._clear_conversation_scopeX  s    @  	F ((55$$&&& / 	- 	-DD$--E%&& -		+t,,,33K@@@4k6	
 	
 	
 	
 	
rB   c                 b   |sdS t          | dd          }t          |t                    r|                    |d           |                     |          }|d|j        _        d|j        _        	 ddlm	} n# t          $ r d}Y nw xY w|J	 |                    |           n3# t          $ r&}t                              d||           Y d}~nd}~ww xY w	 ddlm} n# t          $ r Y dS w xY w	  ||           dS # t          $ r'}t                              d||           Y d}~dS d}~ww xY w)	zHClear per-session control state that must not survive a boundary switch.Nr%  Fr   rL  z?Failed to clear slash-confirm state for session boundary %s: %sr.  z:Failed to clear approval state for session boundary %s: %s)r-   rR   rS   r$  r  r  r9  r  r  rM  r.   r  r/   r0   r  r	  )r  r  pending_skills_reload_notes
_sec_stater  rs  _clear_approval_sessions          r6   r_  z4GatewayRunner._clear_session_boundary_security_stateX  s    	F&-0$'
 '
# 1488 	?'++K>>>--k::
!.2J!+:?J!7	&AAAAAAA 	& 	& 	&!%	&)"((5555   U       	OOOOOOO 	 	 	FF		##K00000 	 	 	LLL        	sT   1A8 8BBB# #
C-CCC 
C,+C,0C= =
D.D))D.c                     |sdS |                      |          j        }t          |j                  dz   |_        |j        S )ae  Claim a fresh run generation token for ``session_key``.

        Every top-level gateway turn gets a monotonically increasing token.
        If a later command like /stop or /new invalidates that token while the
        old worker is still unwinding, the late result can be recognized and
        dropped instead of bleeding into the fresh session.
        r   rk   )r  r  rF  r  )r  r  r  s      r6   r  z+GatewayRunner._begin_session_run_generationX  sH      	1((55@
$'
(A$B$BQ$F
!((rB   c                n    |                      |          }|rt                              d|||           |S )z7Invalidate any in-flight run token for ``session_key``.u-   Invalidated run generation for %s → %d (%s))r  r/   r  )r  r  rj  r  s       r6   r  z0GatewayRunner._invalidate_session_run_generationX  sG    77DD
 	KK?	   rB   r  c                     |sdS |                      |          }||j        j        nd}t          |          t          |          k    S )zEReturn True when ``generation`` is still current for ``session_key``.TNr   )r  r  r  rF  )r  r  r  r  rf  s        r6   r.  z%GatewayRunner._is_session_run_currentY  sN     	4((555:5F%"11A7||s:..rB   c                     |r|r|dS 	 t          |di                               |          }| t          |dt          |                     dS dS # t          $ r Y dS w xY w)zDBind a gateway run generation to the adapter's active-session event.Nr  r  )r-   rT   r
  rF  r.   )r  r  r  r  interrupt_events        r6   r,  z*GatewayRunner._bind_adapter_run_generation	Y  s      	k 	Z-?F	%g/A2FFJJ;WWO*)A3z??SSSSS +* 	 	 	DD	s   AA 
A A )release_running_stater  r  ri  c          	      p   K   sdS                                 }|r|j        j        nd}d}d}	|r;|t          ur2t	          ||           t          |dd          }t          |dd          }	                     |          |rG|	Et          j        t          ||	fd fddd	|dd
          d          
                                                      |          }
t          t          |
          dd          }|
rt          |          r                     |          }	 t          j        |          j        }d|v p*t%          d |                                D                       }n# t(          t*          f$ r d}Y nw xY w|r$|
                    |j        |           d{V  n!|
                    |j                   d{V  |
r%t1          |
d          r|
                               |d|j        _        |r,                                                                dS dS )zFInterrupt the current run and clear queued session state consistently.Nr   r  r  r6  gateway_turn_interruptc                  0                                    S r;   r.  )_generation_at_interruptr  r  s   r6   r   z<GatewayRunner._interrupt_and_clear_session.<locals>.<lambda>AY  s    0L0L#%=1 1 rB   r  gateway-turn-reaper-r   T)r  r  r  r   r  interrupt_session_activityr   c              3   F   K   | ]}|j         t          j        j        u V  d S r;   r-  r2  s     r6   rA   z=GatewayRunner._interrupt_and_clear_session.<locals>.<genexpr>PY  sC       ? ? J'"3"??? ? ? ? ? ?rB   Fr  r  )r  r  r   ri  r   r-   r  ro  rp  r  rr  r	  r   r  r	  r/  r]  r^  r  r_  rU  rH  rp  r  r   r  r  pending_command_textr
  r  )r  r  r  r  r  ri  
_iac_statero	  _process_task_id_process_baseliner  rp  r   paramsaccepts_metadatarn  s   ``             @r6   r   z*GatewayRunner._interrupt_and_clear_sessionY  s2       	F--k::
1;E
--  	]2III"=2BCCC&>    !(?! ! $(#J#J 3 $K $
 $
   	 1 =3&(9:6) ) ) ) ) )  D,<SbS,ACC   eggg**622%,MM7&
 &
"  	Vx :;; 	V77??H) *+EFFQ#-#7 $3 ? ?!'? ? ? < <   z* ) ) )#(   ) V88( 9           88fnUUUUUUUUU 	5ww(=>> 	5''444!9=J!6  	2--k::: $$[11111	2 	2s   *AE3 3F	F	c                   K   | j         |sdS t          | dd          }t          | dd          }|r|dS 	 | j                             |           d{V }|r|                    dd          nd}n# t          $ r Y dS w xY w|dS |5  |                    |          }t          |t                    rt          |          dk    rz|d         t          urkt          |          dk    r|d         nd}|||k    r	 ddd           dS |d         |k    r,||d         |d         |f||<   n|d         |d         ||f||<   ddd           dS # 1 swxY w Y   dS )	u  Re-baseline a cached agent's stored message_count after THIS turn.

        The cross-process coherence guard (#45966) compares the session's
        on-disk ``message_count`` against the count snapshotted next to the
        cached agent, and rebuilds the agent on a mismatch.  But the snapshot
        is taken at agent-BUILD time — before this turn writes its own user +
        assistant (+ tool) rows — and the cache entry is never rewritten on a
        reuse.  So without this re-baseline, THIS process's own turn would
        grow ``message_count`` and the very next turn would see a mismatch
        and rebuild the agent — every turn, for every conversation — silently
        destroying the per-conversation prompt caching the cache exists to
        protect.

        Call this once a turn has completed and the agent has flushed its
        rows to the SessionDB.  It snapshots the now-current count (which
        includes this process's own writes) so the guard only fires when a
        DIFFERENT process changes the transcript out from under us.  The
        ``_sig`` is left untouched; only the count element is refreshed, and
        only when the same agent is still cached (no rebuild/eviction raced
        in between).  Fail-safe: any DB error leaves the snapshot as-is, which
        at worst costs one unnecessary rebuild on the next turn.

        When the cache entry records a ``session_id`` (4-tuple form, #54947)
        that differs from the current ``session_id`` — meaning the cache
        was built for a DIFFERENT conversation under the same ``session_key``
        — the snapshot is intentionally left untouched.  Overwriting it with
        the current session's count would corrupt the original conversation's
        baseline and cause the next switch back to fire the cross-process
        guard spuriously.  Fail-safe: the legacy 3-tuple shape (no
        ``session_id``) is still re-baselined as before.
        Nr  r  r  r   r  r  rk   )	r)   r-   rh  rT   r.   rR   ra  r   ri  )	r  r  r%   r  r  r  _liver  _snapshot_sids	            r6   r8  z0GatewayRunner._refresh_agent_cache_message_countmY  s"     D #:#Fd$7>>~t44 	fnF	".:::FFFFFFFFI9BLIMM/1555EE 	 	 	FF	=F 	 	ZZ,,F
 65))KK!OO1I%<<< .1[[1__q		$ ,*1L1L!	 	 	 	 	 	 	 	" !9%%$, 06ay&)U.K{++ #1Ivay%/{+1	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	s*   :A2 2
B ?B 	A3E	8EEEr  c                 j    |r|sdS t          |          |                     |          j        _        dS )zDStage per-turn must-deliver notes for the next agent run (one-shot).N)r  r  rB  sidecar_notes)r  r  r  s      r6   r+  z-GatewayRunner._set_pending_turn_sidecar_notesY  s;     	% 	FFJ5kkK((5CCCrB   c                     |sg S |                      |          }|g S |j        j        }g |j        _        t          |t                    rt	          |          ng S r;   )r  rB  r|  rR   r  )r  r  r  stageds       r6   r  z1GatewayRunner._consume_pending_turn_sidecar_notesY  sa     	I((55=I#1+-()&$77?tF|||R?rB   c                    |j         t          j        k    rdS | j                            t          j                  }|                     |          }|r|rt          |d          sdS 	 |                    |          pd}n-# t          $ r  t          
                    dd           Y dS w xY wd}|r-|                     |          }|j        j        }||j        _        |||ndk    rdS |sdS d| d	S )
ay  Return a ``[Voice channel now: ...]`` note when VC state changed.

        Compares the live Discord voice-channel context against the last
        value delivered for this session and returns a note only on change
        (including leaving the channel).  Unchanged state returns ``None`` so
        the per-turn member/speaking serialization cannot churn the prompt.
        Nget_voice_channel_contextr   z!voice-channel context read failedTr   z5[Voice channel now: not connected to a voice channel]z[Voice channel now: ro  )r_   r  r|  r{  rT   r-  r   r  r.   r/   r0   r  rB  vc_last)	r  r  r  r  r  r+  vc_nowvc_prev	_vc_states	            r6   r*  z)GatewayRunner._voice_channel_sidecar_noteY  s3    ?h...4-##H$455%%e,, 	W 	:U)V)V 	4	66x@@FBFF 	 	 	LL<tLLLL44	  	4++K88I,4G-3I"*!4gg"==4 	KJJ/f////s   (B   &B*)B*r  c                    |                      ||          }d}|r%|                     |          }|r|j        j        nd}||d         |k    r|d         S t	          ||          }|r!||f|                     |          j        _        |S )uk  Return the session-context prompt, pinned per session.

        Key hit → the pinned bytes are reused VERBATIM (immunizes the
        composed system prompt against renderer nondeterminism); key miss →
        re-render ``build_session_context_prompt`` and re-pin (a legitimate
        cache bust: rename, topic edit, /sethome, redact_pii flip, ...).
        Nr   rk   )r  )_ephemeral_change_keyr  rB  ephemeral_pinr(  r  )r  r   r  r  _eph_key_eph_pin
_pin_stater   s           r6   r  z,GatewayRunner._pinned_session_context_promptY  s     --gzBB 	U11+>>J@JTz.<<PTHHQK8$;$;A;+G
KKK 	KD,,9G rB   c                    ddl }| j        }|j        r|j        j        nd}d}d}|j        t          j        k    rtddlm}  |            rdnd}t          |j	        pd          t          |j
        pd          t          |j        pd          t          |j        pd          |j        rdndf}d}|j        t          j        k    rddlm}	  |	            rdnd}	 dd	lm}
 t           |
                      }n# t$          $ r d}Y nw xY w|t          |j        pd          t          |j        pd          t          |j        pd          t          |j        pd          t          |j        pd          t          |j        pd          t          |j        pd          t          t1          |d
d          pd          t3          | j                  |||t7          d | j        D                       t7          d | j                                        D                       t3          |          |f}|                    tA          |          !                    d                    "                                S )u  Hash the exact inputs ``build_session_context_prompt`` renders.

        This key decides when the pinned per-session context-prompt bytes are
        reused verbatim vs re-rendered.  The maintained invariant (guarded by
        the parity test in tests/gateway/test_prompt_tail_freeze.py): any
        input whose change alters the rendered bytes MUST appear here —
        omission means a stale pinned prompt (cosmetic staleness); inclusion
        of an extra field only costs a spurious re-render.
        r   Nr   r,  rT  rM   r  )_slack_tools_loaded)display_hermes_homer  c              3   $   K   | ]}|j         V  d S r;   r  r  s     r6   rA   z6GatewayRunner._ephemeral_change_key.<locals>.<genexpr>@Z  s$      ??a!'??????rB   c           
   3      K   | ]M\  }}|j         t          t          |d d          pd          t          t          |dd          pd          fV  NdS )r   r   r  N)r   rU   r-   )r?   r  hcs      r6   rA   z6GatewayRunner._ephemeral_change_key.<locals>.<genexpr>AZ  s{         Ar	 GFB//5266Ir228b99     rB   r  )#r  r  r_   r   r  r|  rP  rU  rU   r+  r  rd  r  r4  r  r  r  r  r.   r}  r  
chat_topicr  r  r-   r   shared_multi_user_sessionra  connected_platformshome_channelsr  r  r   r  r  )r   r  r  srcr_   discord_idsdiscord_toolsrU  slack_toolsr  r  home_display	key_tuples                r6   r  z#GatewayRunner._ephemeral_change_keyY  s    	n),=3<%%2<8+++======#8#8#:#:CCCMCL&B''C&,"--CM'R((CK%2&& ~.3	K  <8>));;;;;;!4!4!6!6?##CK	<<<<<<224455LL 	 	 	LLL	 !r""#$$#$$#$$$"%%#$$!r""Y--344233??7#>?????   %288::     1
	4 ~~d9oo44W==>>HHJJJs   C8 8DDc           	         |                      |          }|d|j        _        d|j        _        t	          | dd          }d}|r6|5  | j                            |d          }ddd           n# 1 swxY w Y   n)t	          | dd          }||                    |d          }t          |t                    r
|r|d         n|}|	|t          u rdS d | 
                                D             }t          |          |v rdS 	 t          j        | j        |fddt          |          dd          	                                           dS # t"          $ r, 	 |                     |           Y dS # t"          $ r Y Y dS w xY ww xY w)
u  Remove a cached agent for a session (called on /new, /model, etc).

        Pops the entry AND soft-releases the evicted agent's LLM client
        pool so the httpx connection (sockets + held buffers) is freed
        promptly rather than waiting on CPython GC — AIAgent holds
        reference cycles (callbacks, tool state) that delay refcount
        collection, so a manual release is required to keep gateway RSS
        flat across many /new, /model, undo and reset operations (#29298,
        same leak class as #25315).

        The release is soft (``release_clients()``): it frees the client
        pool and per-turn child subagents but PRESERVES the session's
        terminal sandbox, browser daemon, and tracked bg processes (keyed
        on task_id), because the session may resume with a freshly-built
        agent.  Call sites that want a hard teardown (true conversation
        boundaries like /new) already call ``_cleanup_agent_resources``
        before evicting; ``release_clients`` is idempotent and safe to
        run again after that (the client is already None).

        Cleanup runs on a daemon thread so we never block holding
        ``_agent_cache_lock`` on slow socket teardown — mirrors the
        cap-enforcer and idle-sweeper paths.
        Nr  r  r   c                 H    h | ]\  }}||t           ut          |           S r;   ri  r   r?   r  r
  s      r6   r/  z4GatewayRunner._evict_cached_agent.<locals>.<setcomp>~Z  <     
 
 
1}*A!A!A qEE!A!A!ArB   Tzagent-evict-r  r  )r  rB  r  r  r-   r  r$  rR   ra  ri  r#  r   ro  rp  rq  rU   rr  r.   )r  r  _evict_stater~	  r  r  r   running_idss           r6   r  z!GatewayRunner._evict_cached_agentNZ  s1   6 //<<#6:L%304L%-1488 	8 C C+//TBBC C C C C C C C C C C C C C C T>488F! **[$77(%88QWQ

'=E%<<<F
 
1133
 
 

 e99##F	7X;C$4$4SbS$9;;	  
 eggggg 	 	 	00777777   	s=   A//A36A3AE 
FE11
F ;F?F  Finterrupt_depthc                     |dk    rHddl m} t          j                    | _        d| _        |j        | _        t          | d          rd| _        d| _	        dS )a  Reset per-turn state on a cached agent before a new turn starts.

        ``_last_activity_ts``, ``_last_activity_desc``, and
        ``_last_activity_provenance`` are only reset for fresh external
        turns (depth 0); they are a semantic triple - description and
        provenance describe the activity *at* ts, so updating one without
        the others would make get_activity_summary() misleading.
        For interrupt-recursive turns all three are preserved so the
        inactivity watchdog can accumulate stuck-turn idle time and fire
        the 30-min timeout (#15654).  The depth-0 reset is still needed:
        a session idle for 29 min would otherwise trip the watchdog before
        the new turn makes its first API call (#9051).
        r   r  zstarting new turn (cached)_last_flushed_db_idxN)
r#  r\  r,   _last_activity_ts_last_activity_descUNKNOWN_last_activity_provenancer   r  _api_call_count)r   r  r\  s      r6   rk  z)GatewayRunner._init_cached_agent_for_turnZ  sm     aAAAAAA&*ikkE#(DE%.@.HE+ u455 /-.* !rB   r  c                 X   |t          |d          sdS t          |dd          dS 	 t          | dd          }|dS |                                 |j                            |          }|dS |                    |          sdS |                    |          rdS t          |dd          }|                    t          |t                    r|nd           t                              d|           dS # t          $ r'}t                              d||           Y d}~dS d}~ww xY w)u  Fire on_session_end extraction before soft-evicting a live agent.

        Soft eviction (``_release_evicted_agent_soft``) deliberately keeps the
        session resumable and does NOT fire ``on_session_end`` — that hook is
        reserved for the true session boundary, tear-down done by
        ``_session_expiry_watcher`` when the session finally expires.

        But the watcher tears down whatever agent it finds in ``_agent_cache``
        at expiry time.  If cache pressure (the LRU cap) soft-evicts a
        finalizable session's agent BEFORE it expires, the watcher later finds
        no cached agent and ``on_session_end`` is silently skipped — memory
        providers never see the transcript (#11205, LRU-cap variant).

        We hold the live, fully-scoped agent right now, so commit its
        end-of-session memory extraction here using the agent's own memory
        manager (correct per-user/chat scoping, no reconstruction).  This uses
        ``commit_memory_session`` — extraction WITHOUT provider teardown — so
        the eviction stays soft and a resumed turn keeps working.

        Only fires for sessions the expiry watcher will eventually finalize
        (finite reset policy).  For ``mode == "none"`` sessions the watcher
        never runs, so there is no missed-boundary to compensate for and we
        skip the commit (the agent is simply released).  Best-effort: any
        failure is swallowed so eviction still proceeds.
        Ncommit_memory_sessionr,
  rf  r  zlCommitted on_session_end extraction before soft-evicting finalizable session=%s (cache pressure, pre-expiry)z)Pre-evict memory commit failed for %s: %s)r   r-   r	  r  rT   is_session_finalizabler  r  rR   r  r/   r0   r.   )r  r   r  r  r  r  r  s          r6    _commit_memory_before_soft_evictz.GatewayRunner._commit_memory_before_soft_evictZ  sp   4 =/F G G=F5+T22:F	OT?D99F~!!###O'',,E}
 0077 ))%00 u&94@@H''Jx4N4N(XTXYYYLLFGJ      	O 	O 	OLLDc2NNNNNNNNN	Os/   C8 0C8 0C8 C8 AC8 8
D)D$$D)c                 \    |                      ||           |                     |           dS )aZ  Commit end-of-session memory (if warranted), then soft-release.

        Runs on the daemon eviction thread so the memory-provider call and the
        client teardown never block the caller's held cache lock. Order matters:
        commit uses the live agent's memory manager before ``release_clients``
        drops the message buffer.
        N)r  rq  )r  r   r  s      r6   _commit_then_release_softz'GatewayRunner._commit_then_release_softZ  s4     	--eS999((/////rB   c                     |dS 	 t          |d          r|                                 n|                     |           n# t          $ r Y nw xY wt          |d          r	g |_        dS dS )u  Soft cleanup for cache-evicted agents — preserves session tool state.

        Called from _enforce_agent_cache_cap and _sweep_idle_cached_agents.
        Distinct from _cleanup_agent_resources (full teardown) because a
        cache-evicted session may resume at any time — its terminal
        sandbox, browser daemon, and tracked bg processes must outlive
        the Python AIAgent instance so the next agent built for the
        same task_id inherits them.
        Nrelease_clientsr  )r   r  r'
  r.   r  )r  r   s     r6   rq  z)GatewayRunner._release_evicted_agent_softZ  s     =F	u/00 5%%'''' --e444 	 	 	D	 5-.. 	)&(E###	) 	)s   :A 
AAc           
         t          | dd          }|dS t          |d          sdS d |                                 D             }t          dt	          |          t
          z
            }g }|dk    rt          |                                          }|d|         D ]c}|                    |          }t          |t                    r
|r|d         nd}|t          |          |v rL|                    ||f           d|D ]\  }}	|                    |d           t	          |          t
          z
  }
|
dk    r/t                              dt	          |          t
          |
           |D ]l\  }}t                              d|t	          |                     |<t#          j        | j        ||fdd	|dd
                                                     mdS )u  Evict oldest cached agents when cache exceeds _AGENT_CACHE_MAX_SIZE.

        Must be called with _agent_cache_lock held.  Resource cleanup
        (memory provider shutdown, tool resource close) is scheduled
        on a daemon thread so the caller doesn't block on slow teardown
        while holding the cache lock.

        Agents currently in _running_agents are SKIPPED — their clients,
        terminal sandboxes, background processes, and child subagents
        are all in active use by the running turn.  Evicting them would
        tear down those resources mid-turn and crash the request.  If
        every candidate in the LRU order is active, we simply leave the
        cache over the cap; it will be re-checked on the next insert.
        r  Nr  c                 H    h | ]\  }}||t           ut          |           S r;   r  r  s      r6   r/  z9GatewayRunner._enforce_agent_cache_cap.<locals>.<setcomp>*[  r  rB   r   uk   Agent cache over cap (%d > %d); %d excess slot(s) held by mid-turn agents — will re-check on next insert.z;Agent cache at cap; evicting LRU session=%s (cache_size=%d)Tzagent-cache-evict-r  r  )r-   r   r#  r  r   _AGENT_CACHE_MAX_SIZEr  rg  rT   rR   ra  r   rs   r$  r/   r   r  ro  rp  r  rr  )r  r  r  excess
evict_planordered_keysr  r  r   r  remaining_over_caps              r6   ru  z&GatewayRunner._enforce_agent_cache_cap[  s#    ~t44>F v}-- 	F

 
1133
 
 
 QF&;;<<"$
A::..L#GVG, 0 0

3$.ue$<$<PPaD$Ek)A)A!!3,////  	" 	"FCJJsD!!!! [[+@@!!NNDF24F   % 	 	JCKKMS[[      98c#2#h88	  
 %'''#	 	rB   c                 b   t          | dd          }t          | dd          }||dS t          j                    }g }d |                                 D             }|5  t          |                                          D ]\  }}t          |t                    r
|r|d         nd}|)t          |          |v r;t          |dd          }	|	O||	z
  t          k    rd}
t          | dd          }	 |.|	                                 |j
                            |          }
n# t          $ r d}
Y nw xY w|
-|+|                    |
          r|                    |
          s|                    ||f           |D ]\  }}|                    |d           	 ddd           n# 1 swxY w Y   |D ]n\  }}t"                              d||t          |d|          z
             t'          j        | j        |fd	d
|dd                                                     ot/          |          S )u  Evict cached agents whose AIAgent has been idle > _AGENT_CACHE_IDLE_TTL_SECS.

        Safe to call from the session expiry watcher without holding the
        cache lock — acquires it internally.  Returns the number of entries
        evicted.  Resource cleanup is scheduled on daemon threads.

        Agents currently in _running_agents are SKIPPED for the same reason
        as _enforce_agent_cache_cap: tearing down an active turn's clients
        mid-flight would crash the request.
        r  Nr  r   c                 H    h | ]\  }}||t           ut          |           S r;   r  r  s      r6   r/  z:GatewayRunner._sweep_idle_cached_agents.<locals>.<setcomp>s[  r  rB   r  rf  z3Agent cache idle-TTL evict: session=%s (idle=%.0fs)Tzagent-cache-idle-r  r  )r-   r,   r#  r  r  rR   ra  r   _AGENT_CACHE_IDLE_TTL_SECSr	  r  rT   r.   r  r  rs   r$  r/   r  ro  rp  rq  rr  r   )r  r  r~	  ra  to_evictr  r  r  r   last_activityr1  r  r  s                r6   r  z'GatewayRunner._sweep_idle_cached_agentsb[  s    ~t441488>U]1ikk "
 
1133
 
 

  4	& 4	&"6<<>>22 12 12
U$.ue$<$<PPaD=e99++ '/BD I I (-'+EEE2 %)M$T?DAAF-!-"11333,2O,?,?,D,DM$ - - -(,- &1"."99-HH / & : := I I / !OOS%L111" & &Q

3%%%%&g4	& 4	& 4	& 4	& 4	& 4	& 4	& 4	& 4	& 4	& 4	& 4	& 4	& 4	& 4	&j # 
	 
	JCKKES75*=sCCC   7X3SbS33	  
 egggg8}}s8   BF&10D"!F&"D1.F&0D11A(F&&F*-F*c                 L   t          j        dd                                          }|r|                    d          S t	                      }|                    d          pi                     d          }|pd                                }|r|                    d          S dS )zReturn the proxy URL if proxy mode is configured, else None.

        Checks GATEWAY_PROXY_URL env var first (convenient for Docker),
        then ``gateway.proxy_url`` in config.yaml.
        GATEWAY_PROXY_URLr   r;  r1   	proxy_urlN)rq   r  rV   r  rQ   rT   )r  r  rk  s      r6   _get_proxy_urlzGatewayRunner._get_proxy_url[  s     i+R006688 	#::c??""$$wwy!!'R,,[99yb!! 	#::c??"trB   scfgr  z(tuple[Any, Optional[Callable[[], None]]]c                   ddl m} d}|j        t          j        k    rt          |d          r||j        f	 dd}t          |dd          }|s|d	k    rt          d
          |r|j	        nd}d}	|j        t          j
        k    rd}d}	|j        t          j        k    r t          t          |dd          pd          nd}
 ||j        |j        ||	|
|j        pdt          |dd          pd          }||fS )uq  Build the shared ``StreamConsumerConfig`` and the optional
        Telegram pause-typing closure used by both agent-run paths.

        ``on_missing_cursor`` controls how platforms whose adapter sets
        ``SUPPORTS_MESSAGE_EDITING = False`` are handled — both semantics
        are preserved verbatim from the pre-refactor call sites:

        - ``"fallback"`` (proxy path): stream anyway with an empty cursor.
        - ``"raise"`` (in-process agent path): raise ``RuntimeError`` so
          the caller's ``except`` skips streaming entirely.

        Returns ``(consumer_cfg, pause_typing_before_finalize)``.
        r   )StreamConsumerConfigNr  r'   c                 0    |                      |           d S r;   )r  )r~  _chat_ids     r6   r  zRGatewayRunner._build_stream_consumer_config.<locals>._pause_typing_before_finalize[  s     ..x88888rB   SUPPORTS_MESSAGE_EDITINGTr  z(skip streaming for non-editable platformr   Ffresh_final_after_secondsr  editr}  )edit_intervalbuffer_thresholdcursorbuffer_onlyr  r_  r}  rX  )ra  r  r_   r  r  r   r  r-   r  r  MATRIXrG  r  r  r_  )r  r  r  r  r  r  r  _adapter_supports_edit_effective_cursor_buffer_only_fresh_final_secsr  s               r6   rb  z+GatewayRunner._build_stream_consumer_config[  sc   * 	A@@@@@(,%?h///GGE\4]4]/ 9 9 9 9 9 ")2Ld!S!S% 	K*;w*F*FIJJJ+AIDKKr ?ho-- "L ("333 '$ ;SAAHSIII 	
 -,,!2$$&7n.fk266<"
 
 
 ;;;rB   rV  c	                    K   	 ddl m}	m}
 n# t          $ r
 dg dg dcY S w xY w                                 }|sdg dg dS 	 ddlm}m} 	  |d          pd                                }n2# |$ r* t          j
        dd                                          }Y nw xY wn7# t          $ r* t          j
        dd                                          }Y nw xY wd	t          f fd
}g }|r|                    d|d           |D ]J}|                    d          }|                    d          }|dv r|r|                    ||d           K|                    d|d           ddi}|rd| |d<   |r||d<   d|dd}d}t          t           dd          dd          }|ddlm}  |            }t%          |j                  }t)                      }ddlm}  |||d          }||j        o
|j        dk    nt          |          }                     ||          }|r	 ddlm}                      |          } | r3                     ||| d !          \  }!}" || |j        |!||"||"          }n2# t          $ r%}#t>                               d#|#           Y d}#~#nd}#~#ww xY wd}$|r&tC          j"        |#                                          }$                     |          } | r4	 | $                    |j        |$           d{V  n# t          $ r Y nw xY wd}%tK          j%                    }&	  |
dd%&          }' |	|''          4 d{V }(|(&                    | d(||)          4 d{V 	 })|)j'        d*k    r|)(                                 d{V }*t>          )                    d+|)j'        ||*dd,                    d-|)j'         d.|*dd/          g dg dcddd          d{V  cddd          d{V  |r|*                                 |$rS	 tC          j+        |$d0'           d{V  S # tB          j,        tB          j-        f$ r |$.                                 Y S w xY wS d}+|)j/        0                                2 3 d{V }, |            st>          1                    d1pd2pd           dg dg te          |          |d3d4c cddd          d{V  cddd          d{V  |r|*                                 |$rS	 tC          j+        |$d0'           d{V  S # tB          j,        tB          j-        f$ r |$.                                 Y S w xY wS |,3                    d5d67          }-|+|-z  }+d8|+v r|+4                    d8d9          \  }.}+|.                                }.|.s4|.5                    d:          r|.d;d         }/|/                                d<k    rn	 tm          j7        |/          }0|0                    d=g           }1|1rP|1d                             d>i           }2|2                    dd          }|r|%|z  }%|r|8                    |           n# tl          j9        $ r Y nw xY wd8|+v te          |+          tt          k    rtw          d?          !6 	 ddd          d{V  n# 1 d{V swxY w Y   ddd          d{V  n# 1 d{V swxY w Y   n# tB          j-        $ r  t          $ r}3t>          <                    d@||3           |%szdA|3 g dg dcY d}3~3|r|*                                 |$rS	 tC          j+        |$d0'           d{V  S # tB          j,        tB          j-        f$ r |$.                                 Y S w xY wS Y d}3~3nd}3~3ww xY w|r|*                                 |$rS	 tC          j+        |$d0'           d{V  n# tB          j,        tB          j-        f$ r |$.                                 Y nuw xY wnp# |r|*                                 |$rS	 tC          j+        |$d0'           d{V  w # tB          j,        tB          j-        f$ r |$.                                 Y w w xY ww xY wtK          j%                    |&z
  }4 |            s7t>          1                    dBpd2pd           dg dg te          |          |d3d4S t>          1                    dC||pdddD         |4te          |%                     |%pdEd|ddF|%dgd9g te          |          ||duot          |%          d4S )GaT  Forward the message to a remote Hermes API server instead of
        running a local AIAgent.

        When ``GATEWAY_PROXY_URL`` (or ``gateway.proxy_url`` in config.yaml)
        is set, the gateway becomes a thin relay: it handles platform I/O
        (encryption, threading, media) and delegates all agent work to the
        remote server via ``POST /v1/chat/completions`` with SSE streaming.

        This lets a Docker container handle Matrix E2EE while the actual
        agent runs on the host with full access to local files, memory,
        skills, and a unified session store.
        r   )ClientSessionClientTimeoutuE   ⚠️ Proxy mode requires aiohttp. Install with: pip install aiohttpr  uH   ⚠️ Proxy URL not configured (GATEWAY_PROXY_URL or gateway.proxy_url))UnscopedSecretErrorr  GATEWAY_PROXY_KEYr   r'   c                  <     sdS                                 S r  rm  r  r  r  s   r6   r  z>GatewayRunner._run_agent_via_proxy.<locals>._run_still_currentJ\  )    %[%t//^LLLrB   r  r  r{  r  >   r  r  r  zContent-Typezapplication/jsonzBearer AuthorizationzX-Hermes-Session-Idzhermes-agentT)r  r  streamNrX   r  r  r0  r  r  r  r  )r  r  rX   r   r  r  r  z+Proxy: could not set up stream consumer: %sr  rS  )r  	sock_readr  z/v1/chat/completions)r  headersr   zProxy error (%d) from %s: %srp  u   ⚠️ Proxy error (z): r  r#   uK   Discarding stale proxy stream for %s — generation %d is no longer currentr  F)r  r  r  r  r  r%   rR  r  rJ  )r  r   rk   zdata: r  z[DONE]r   deltazAProxy SSE stream exceeded max buffer size without a line boundaryz Proxy connection error to %s: %su   ⚠️ Proxy connection error: uK   Discarding stale proxy result for %s — generation %d is no longer currentz>proxy response: url=%s session=%s time=%.1fs response=%d charsrI  z(No response from remote agent)r  )=aiohttpr  r  r+  r  rT  r  r  rV   rq   r  r.   r   rs   rT   r-   r  r  r=  r_   rQ   r2  r1  r  r_  r	  ra  r  r	  rb  r  r/   r0   r  ri  rq
  rc  r,   postr  r   r   r  r  r  rf  r  r  iter_anyr  r   r  rC   r   r  r  r  r  #_GATEWAY_PROXY_SSE_BUFFER_MAX_CHARSrH  r  )5r  r  rV  r  r  r%   r  r  r  _AioClientSessionr  r  r  r  	proxy_keyr  api_messagesr|  r{  r  r  r   r  r  r  r  r  r1  r  r  r  r  r~  r  r  r  stream_taskfull_response_start_timeoutr	  respr  rn  rm  r   r#  r  objr   r  rs  _elapseds5   `     ``                                             r6   _run_agent_via_proxyz"GatewayRunner._run_agent_via_proxy\  s     .	QQQQQQQQQ 	 	 	"i	    	 ''))	 	"l	  	CJJJJJJJJG'Z(;<<BIIKK		& G G GI&92>>DDFF			G 	C 	C 	C	"5r::@@BBIII	C	MD 	M 	M 	M 	M 	M 	M 	M 	M  .0 	On M MNNN 	H 	HC776??Dggi((G,,,,##Tg$F$FGGGV@@AAA $23E"F 	='<'<'<GO$ 	8-7G)* $$
 
  h55{DII=666666#O%%E+FO<<*,,BBBBBB11{
 

 & M6eo6o&& 	 6:5U5UV\^n5o5o 	UUIIIIII33F;; ::"E8.8 ;   AM#@ (='< ( &,!1+H,<*<( ( ($  U U UJGTTTTTTTTU  	F!-.>.B.B.D.DEEK ++F33 	**6>DT*UUUUUUUUUU    Y	)$}1===H((::: A A A A A A Ag"<< 666# (   @ @ @ @ @ @ @ @ {c))+/99;;%6%6%6%6%6%6
: KJtt4D  
 /hT[.g.gU_`dad`dUe.g.g(*)*%'	   @ @ @ @ @ @ @ @ @ @ @ @ @A A A A A A A A A A A A Ab   * ''))) ))!*;DDDDDDDDDDD,g.DE ) ) )&&((((())  F'+|'<'<'>'> , , , , , , ,e1133 "KK m + 2s . 3!   35,.-.)+25g,,.86;$ $  7@ @ @ @ @ @ @ @ @ @ @ @ @A A A A A A A A A A A A Ab   * ''))) ))!*;DDDDDDDDDDD,g.DE ) ) )&&((((())]  %||GI|FF$ #fnn+1<<a+@+@LD&#'::<<D#' ) (#x88 )'+ABBx#'::<<8#;#;$)!)*.*T*:*:C.1ggi.D.DG'. %S07
w0K0K27))Ir2J2J+2 )S,9W,DM/? -S0@0I0I'0R0R0R'+'; !) !) !)$(D!)' #fnn* v;;)LLL", c# #  MS (?'>)@ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @A A A A A A A A A A A A A A A A A A A A A A A A A A AF % 	 	 	 	 	 	LL;YJJJ  &K&K&K "!"	         * ''))) ))!*;DDDDDDDDDDD,g.DE ) ) )&&((((())    	   * ''))) ))!*;DDDDDDDDDDD,g.DE ) ) )&&((((())   * ''))) ))!*;DDDDDDDDDDD,g.DE ) ) )&&((((()) 9;;'!!## 	KK]"s#!   #%"%g,,(&+   	L
(b#2#.#m:L:L	
 	
 	
 ,P/PG44$?? !'ll$"2$">"V4CVCV
 
 	
s   $$B! A. -B! .,BB! BB! !1CC(AI9 9
J(J##J(-"L 
LL6[6 "[$8A)[![$3[6 P;;/Q-,Q-1[Z-A[[$'[6 T///U! U!%B[.A<Y+*[+Y=	:[<Y=	=1[/[$
[	[$[	[$[6 $
[..[6 1[.2[6 5`  6^1'^,6^17`  ]11/^#"^#'`  ,^11`  _* */`` b:ab/b	bb		brl  r  r,  r+  r-  r  c                 f  K   t          t          | dd          dd          s)|                     |||||||||	|
||||           d{V S |                     |          }t          |          5  |                     |||||||||	|
||||           d{V cddd           S # 1 swxY w Y   dS )u  Profile-scoping wrapper around the agent run.

        When multiplexing is active, resolve the inbound source's profile and
        run the whole turn inside ``_profile_runtime_scope`` so config/skills/
        memory resolve to that profile's home AND credentials resolve from that
        profile's secret scope (never the process-global ``os.environ``). When
        multiplexing is off this is a transparent pass-through — zero behavior
        change for single-profile gateways.
        rX   Nr  F)	r  r  rl  r  r  r,  r+  r-  r  )r-   _run_agent_innerr  r  )r  r  rV  r  r  r%   r  r  rl  r  r  r,  r+  r-  r  r}  s                   r6   r-  zGatewayRunner._run_agent0]  si     4 wtXt446JERR 		..&*'!1DT-*%9'=) /          <<VDD#L11 		 		..&*'!1DT-*%9'=) /        		 		 		 		 		 		 		 		 		 		 		 		 		 		 		 		 		 		s   0)B&&B*-B*c                 <   t          | dd          }t          |dd          sdS t          |dd          }|sdS ddlm} 	  |||j        j        t          |dd          |j        t          |d	d          t          |d
d                    }n9# t          $ r, t                              d|j        |j        d           Y dS w xY w|r|j	        S t          
                    d|j        j        |j        t          |d	d          t          |d
d                     dS )u  Resolve the profile name for an inbound source via configured routes.

        Returns ``None`` when multiplexing is off, no routes are configured, or
        no route matches. Callers (``build_source``,
        ``_resolve_profile_home_for_source``) treat ``None`` as "use the
        default/active profile". When ``gateway.profile_routes`` is configured,
        the most specific matching route wins (guild < channel < thread). See
        :mod:`gateway.profile_routing` for matching rules.

        Gated on ``gateway.multiplex_profiles``: routing stamps
        ``source.profile``, which selects the session-key namespace and batch
        keys — but the profile-scoped agent run only activates under
        multiplexing. Without this gate, a configured route with multiplexing
        off would namespace batch/session keys by profile while the agent
        still runs in ``agent:main``, splitting the two out of agreement.
        rX   Nr  Fprofile_routesr   )match_profile_router+  rd  r  )r_   r+  r  rd  r  z@Profile route matching failed for %s/%s, falling back to defaultTr   zONo profile route matched: platform=%s chat_id=%s thread_id=%s parent_chat_id=%s)r-   gateway.profile_routingr  r_   r   r  r.   r/   r   r  r0   )r  r  rX   routesr  matcheds         r6   _profile_name_for_sourcez&GatewayRunner._profile_name_for_sourcea]  sh   " x..v3U;; 	4!1488 	4??????	)). T::!&+t<<&v/?FF  GG  	 	 	NNR$     44	  	#?"]O!6>FK..@PRV0W0W	
 	
 	

 ts   AB 2CCc                 ,   ddl m}m}m} ddlm} d}	 |j        pd                                }|r|}|s|                     |          }|r|}|s |            pd} ||          }|rQ ||          sFt          
                    d||j        j        |j        t          |dd                      |            S |S # t          $ rM t          
                    d	|j        j        |j        t          |dd          |pd
d            |            cY S w xY w)u  Resolve which profile's HERMES_HOME should serve this inbound source.

        Resolution order:
          1. ``source.profile`` — set by /p/<profile>/ URL prefix, per-credential
             adapter ownership, OR profile_routes matching at ``build_source`` time.
          2. ``_profile_name_for_source`` — re-run routing here as a defensive
             fallback for sources that bypass ``build_source``.
          3. The active profile (the multiplexer's own home).
        r   )r  r}  profile_exists)rG  Nr   r(  z\Profile %r does not exist for source %s/%s (guild_id=%s), falling back to global HERMES_HOMEr+  zjFailed to resolve profile directory for source %s/%s (guild_id=%s), falling back to global HERMES_HOME: %sz(no profile)Tr   )r  r  r}  r  r  rG  r  rV   r  r/   r   r_   r   r  r-   r.   )	r  r  r  r}  r  rG  explicit_profiler   profile_dirs	            r6   r  z.GatewayRunner._resolve_profile_home_for_source]  s   	
 	
 	
 	
 	
 	
 	
 	
 	
 	

 	544444  #	%N(b//11D (#'  ,44V<< ,'+$ >..00=I)/$//K 	)t(<(< 	)9$O)NFJ55   '((( 	% 	% 	%NN9%
D11 2N     #?$$$$$	%s   B%B< :B< <ADDc                 W   Ǉȇɇʇˇ͇̇·χЇч҇ӇԇՇևׇ؇هڇۇ܇݇އ߇K                                     r#                     |||||	           d{V S ddlm} ddldt
          f fd}t                      t          j                  ddl	m
} t           |ۦ                    }                    d          pi }|                    d	          pd}                    d
i           }t          |t                    si }ddlm 	 ddlm}  ݉dd          } ||rt'          |          nd           n# t(          $ r Y nw xY w	 ddlm}  ݉dd          } |t          |                     n# t(          $ r Y nw xY w ݉d          }t-          j        d          }t          |t                    r|ni }|                    d          pi }|                    ۦ          pi }|                    d          pi }d|v p1t          |t                    od|v pt          |t                    o|v } |r| s|n|p|pd}! ݉d          pd}"ddlmm}# g  |#ۦ          dddddt6          dt
          dt8          t:                   dz  dt
          dt6          f
ۈ݈fd}$dddd d!t6          d"t6          dz  d#t6          dz  d$t:          dt6          f
͈ψfd%dd&lm}% |!d'voj        |%j         k    }& ݉d(d)          }' !                              }(tE          |(d*d          sd}(|'d+k    rd}(|!d,k    oj        |%j         k    })|)r j#                    nd |$d-d|%j$        h.          }*j        |%j         k    o|*d+k    }+ |$d/d|%j$        h.          },|,d+k    }-|&p|-}.|.r j#                    nd}/dg}0dg}1dg}2dg}3dg}4dg}5j        |%j%        k    r j&                            |%j%                  }6tE          |6d0d          }7t          |7t                    rktO          |6d1          r[|7(                                D ]F\  }8}9t7          |9          t7          j)                  k    r|6*                    |8          r|8|5d<    nGtW          j,                    }:t           ݉d2                    ˉr !                              nd};|;tE          t[          |;          d3d          nd}<|;|<|<t\          j/        u rdd};g dg}=d4}>ta          di d5d6|d7|(d8|'d9|-d:|!d;|"d<|&d=|/d>ړd?|1d@|0dA|3dB|2dC|=dD|>dE˓dFʓdG|dH|dIݓdJdK|d	|dL|)dM|+dN|.dO|4dP|5dQ|:dR|dS|dT|
dU|dVdWdX|dY|	dZ|d[|d\|}?tc           |?          }@|@j2        |?_2        |@j3        |?_3        d}Aj        |%j4        k    r !                              }B|By	 tE          |Bd]d          }Ctk          |C          rt           |C                      }An-t          |Bj6        j7                            d^d                    }An# t(          $ r d}AY nw xY wtq          j        j9        |	|A_          }Dj        |%j%        k    rGtE          d`d          r6tE          dad          r%j9        st7          tE          dad                    nd}E|DrT|Dj9        k    r :                    |	          n4 ;                    j        j)        |DtE          dbd          |	c          nd}F|F|Erdd|	i}Fty          |Fj        e          }Fj        |%j=        |%j$        fv r	j9        r|	s|Er|	nd}Gڈfdf}H|F|?_>        |G|?_?        |@j@        }Idg؉|?_A        dg}Jdg}Kdgdg|J|?_B        |K|?_C        |?_D        |?_E        tW          j,                    }L jF        }M|L|?_G        |M|?_H        |@jI        |?_I        |@jJ        |?_J         !                              }Nj)        }Oj        |%j=        k    rj9        r|	r|D|	dgn`|DrT|Dj9        k    r :                    |	          n4 ;                    j        j)        |DtE          dbd          |	c          ndՉՀ|Erdd|	i|N|?_K        |O|?_L        |?_M        |@jN        |?_N         !                              }P|duo3t7          tE          |dh|                    O                                dik    }Q|P|Qr|PP                    j)                  r	 ddjlQmR}R ddklSmT}S  |S            }T jU        ptW          jV                    }U |R|Pj)        |T|Uլl          }V|VjW        r|Vd<   |VX                                 n2# t(          $ r%}Wt          Z                    dm|W           Y d}W~Wnd}W~Www xY w|@j[        d}X|.rtW          j\         |I                      }Xd}Y|)rtW          j\         |H                      }Yd}Zfdn}[tW          j\         |[                      }Z؈ fdo}\tW          j\         |\                      }]tW          j]                    шш؈ fdp}^tW          j\         |^                      }_t          dqdr          }`|`dk    r|`nd |$dsddt          ҉d+k    rdt          j_                    Ԉǈʈˈ̈Έ҈ԈՈ؈ۈ݈ fdu}atW          j\         |a                      }bddvdwt6          dxt
          dt
          fdy}c	 t          dzd{          }d|ddk    r|dnd}et          d|d}          }f|fdk    r|fnd}gd}hdd~l`ma}i |pd}j|ib                    |j          }k|j|?_c        |k|?_d        t          j]                    t          j]                    }lt          jf                    }m։ցֈ fdnd }n׈؈fd}o|eDt          jg        t          |j|k|e|l|md|nd	d|jdd          d          X                                 tW          ji         j                    |o                    d}pd}q|ed}r	 tW          jk        h|q           d{V \  }s}t|sr̠l                                }rnwѠm                                s`r] !                              }ud         }v|ur=|vr:tO          |ud          r)|un                              r|ujo                                      }w|wr|wjp        nd}x|wrtE          |wdd          pg }y q                    |w          r7 r                    |w|u|xpddj9        r	dj9        ind           d{V \  }x}tn|xs|yrt          |w          }xt          t                    d|_u                                rdnd           |vv                    |x           Ѡ                                 d         }z|z|zw                    d           nd}r	 tW          jk        h|q           d{V \  }s}t|sr̠l                                }rn|lm                                rd}pnǉd         }{d}||{rLtO          |{d          r<	 |{x                                }}|}                    dd          }|n# t(          $ r Y nw xY w|hs|g|||gk    rd}h !                              }~|~rt'          |gdz            pd}t'          |e|gz
  dz            pd}	 |~y                    j)        d| d| dլ           d{V  n2# t(          $ r%}t          Z                    d|           Y d}~nd}~ww xY w|||ek    rFd}pt          jg        t          |j|k|l|m|ndd|jdd          d          X                                 nwѠm                                s`r] !                              }ud         }v|ur=|vr:tO          |ud          r)|un                              r|ujo                                      }w|wr|wjp        nd}x|wrtE          |wdd          pg }y q                    |w          r7 r                    |w|u|xpddj9        r	dj9        ind           d{V \  }x}tn|xs|yrt          |w          }xt          t                    d|_u                                rdnd           |vv                    |x           Ѡ                                 d         }z|z|zw                    d           |prd         }i }|r6tO          |d          r&	 |x                                }n# t(          $ r Y nw xY w|                    dd          }|                    dd          }|                    d          }|                    dd          }|                    dd          }t          {                    d||e||||pd           |rt          |t                     t'          |edz            pd}d| dg}|r$|~                    d| d|dd| d| d	           n#|~                    d| d|dd| d| d	           |~                    d           d                    |          |Jd         r|Jd                             dg           ng ||Kd         pg ddd}rd         }|Jd         }|r|                    d          nd}|tO          |d          r|st                      }	 ddlm}m} tE          |dd          pd}|r||vr |||          }n# t(          $ r Y nw xY w|j        |k    r0                     |j                  s                                |Jd         } !                              }d         }z|z|z                                 	 |z                    d           d{V  n2# t(          $ r%}t          Z                    d|           Y d}~nd}~ww xY w|zju        s1|zw                    d           |z                    d           d{V  |zj        r.|,tE          |dd          }tk          |          r |           d}d}|rP|rMrJt          |          }                     ||          }|                    d          r^|s\|                    d          rG|                    d          }t          |          rt          t                    dpd|           n|}n|r|jp        pd}tE          |dd          pg } q                    |          rF r                    |||dj9        r	dj9        ind           d{V \  }}t|st          |          }n|pt          |          }|r#t          Z                    d|ddą                    |r@|s>|s<|                    dŦ          }|r%|}t          Z                    d|ddą                    |r|                                                    d          r|                                                    dd          }|r"|d         dd         O                                nd}|rB	 ddlm}  ||          rt          t                    d|           d}d}n# t(          $ r Y nw xY w j        r8|s|r4t          t                    dɉpd                                            d}d}|s|r\t          Z                    d|ddą                    |r:tO          |d˦          r*r(|j        v r|j                                                  | j        k    rTt                              d|            !                              }|r|rt1          |jo        |           n(|r&tO          |dͦ          r|                    |           |Jd         p|r|dΜ	 |Xr|X                                 |Yr|Y                                 |_                                 |b                                 |Zro	d         du}|s3|Z                                 	 |Z d{V  n# tV          j        $ r Y nvw xY w	 tW          j        |Zd           d{V  nT# tV          j        tV          j        f$ r6 |Z                                 	 |Z d{V  n# tV          j        $ r Y nw xY wY nw xY wd         }|J|ju        sC|w                    dϦ           	 |                    d           d{V  n# t(          $ r Y nw xY w|]                                 r                     Ц            j        r                     dѦ           |X|Y|_|]|bfD ]#}|r	 | d{V  # tV          j        $ r Y w xY w$S |                    d          }|s܉d         }|r|Zr	 tW          j        |Zd           d{V  n# tV          j        tV          j        f$ r6 |Z                                 	 |Z d{V  n# tV          j        $ r Y nw xY wY n1t(          $ r%}t          Z                    d|           Y d}~nd}~ww xY wt          |rt                    r|rn|pi }t          |                    dӦ                    }|                    dd          } |c|||v          }	 ddlm}  |||          }n# t(          $ r d}Y nw xY w|rt          t                    d։pd           n|rv|st	 t          t                    d׉pd           |y                    j)        |լ           d{V  nQ# t(          $ r%}t                              d|           Y d}~n'd}~ww xY w|rt          t                    dىpd           tE          t[          |          dd          `|                    ۦ          }tk          |          r9	  |            }tG          j        |          r| d{V  n# t(          $ r Y nzw xY wnu|rstO          |dܦ          rc|j                            d          }tk          |          r9	  |            }tG          j        |          r| d{V  n# t(          $ r Y nw xY w|                    d|          }}|}d}d}}d}|tE          |d5d          p}                     |          r                     |          st          t                    d݉pd           ||Xr|X                                 |Yr|Y                                 |_                                 |b                                 |Zro	d         du}|s3|Z                                 	 |Z d{V  n# tV          j        $ r Y nvw xY w	 tW          j        |Zd           d{V  nT# tV          j        tV          j        f$ r6 |Z                                 	 |Z d{V  n# tV          j        $ r Y nw xY wY nw xY wd         }|J|ju        sC|w                    dϦ           	 |                    d           d{V  n# t(          $ r Y nw xY w|]                                 r                     Ц            j        r                     dѦ           |X|Y|_|]|bfD ]#}|r	 | d{V  # tV          j        $ r Y w xY w$S 	                      |          }n/# t(          $ r" t          Z                    dމpddߦ           Y nw xY w                     ||||           d{V }|||Xr|X                                 |Yr|Y                                 |_                                 |b                                 |Zro	d         du}|s3|Z                                 	 |Z d{V  n# tV          j        $ r Y nvw xY w	 tW          j        |Zd           d{V  nT# tV          j        tV          j        f$ r6 |Z                                 	 |Z d{V  n# tV          j        $ r Y nw xY wY nw xY wd         }|J|ju        sC|w                    dϦ           	 |                    d           d{V  n# t(          $ r Y nw xY w|]                                 r                     Ц            j        r                     dѦ           |X|Y|_|]|bfD ]#}|r	 | d{V  # tV          j        $ r Y w xY w$S                      |          }tE          |dTd          }tE          |dd          } !                              }|ZrXVtE          |dd          }|CtE          |dd          }tk          |          r# |          }|r|                    |            !                              }|r4	 |                    j)        լ           d{V  n# t(          $ r Y nw xY w                     |           d{V                       |||||||dz   |||           d{V }ta          ||          |Xr|X                                 |Yr|Y                                 |_                                 |b                                 |Zro	d         du}|s3|Z                                 	 |Z d{V  n# tV          j        $ r Y nvw xY w	 tW          j        |Zd           d{V  nT# tV          j        tV          j        f$ r6 |Z                                 	 |Z d{V  n# tV          j        $ r Y nw xY wY nw xY wd         }|J|ju        sC|w                    dϦ           	 |                    d           d{V  n# t(          $ r Y nw xY w|]                                 r                     Ц            j        r                     dѦ           |X|Y|_|]|bfD ]#}|r	 | d{V  # tV          j        $ r Y w xY w$S 	 |Xr|X                                 |Yr|Y                                 |_                                 |b                                 |Zro	d         du}|s3|Z                                 	 |Z d{V  n# tV          j        $ r Y nvw xY w	 tW          j        |Zd           d{V  nT# tV          j        tV          j        f$ r6 |Z                                 	 |Z d{V  n# tV          j        $ r Y nw xY wY nw xY wd         }|J|ju        sC|w                    dϦ           	 |                    d           d{V  n# t(          $ r Y nw xY w|]                                 r                     Ц            j        r                     dѦ           |X|Y|_|]|bfD ]#}|r	 | d{V  # tV          j        $ r Y w xY w$n# |Xr|X                                 |Yr|Y                                 |_                                 |b                                 |Zro	d         du}|s3|Z                                 	 |Z d{V  n# tV          j        $ r Y nvw xY w	 tW          j        |Zd           d{V  nT# tV          j        tV          j        f$ r6 |Z                                 	 |Z d{V  n# tV          j        $ r Y nw xY wY nw xY wd         }|J|ju        sC|w                    dϦ           	 |                    d           d{V  n# t(          $ r Y nw xY w|]                                 r                     Ц            j        r                     dѦ           |X|Y|_|]|bfD ]#}|r	 | d{V  # tV          j        $ r Y w xY w$w xY wd         }t          |rt                    r|r                    d          s|r                    dԦ          pd}| p|dk    }t          |r                    dӦ                    }t          |otE          |dd                    }d}|rG|sEtE          |dd          }tk          |          r!	  ||          du }n# t(          $ r d}Y nw xY w|rd}t          |r                    d                    } |c|||v          }|s-|s+|s|r't          t                    dpd|||           d|rd<   n|s|s|r||j        }tE          |dd          }|r|dk    r|	 |                     j)        ||d           d{V }tE          |dd          r$d|rd<   t          t                    dpd|           n-t                              dpdtE          |dd                     n# t(          $ r(}t                              dpd|Ħ           Y d}~nd}~ww xY wt          t                    dpd           n|s|r||j        }|r	 |j                            j)        ||rd         d           d{V  d|rd<   t          t                    d|pd           n5# t(          $ r(}t                              dpd|Ħ           Y d}~nd}~ww xY wr|;rrt          |rt                    r|r                    d          stO          |;d          rti          ʦ          Љj)        |;tW          j,                    dȈɈЈfd}	 |;                    |ŉۦ           n2# t(          $ r%}t          Z                    d|Ʀ           Y d}~nd}~ww xY w|rS )a  
        Run the agent with the given message and context.
        
        Returns the full result dict from run_conversation, including:
          - "final_response": str (the text to send back)
          - "messages": list (full conversation including tool calls)
          - "api_calls": int
          - "completed": bool
        
        This is run in a thread pool to not block the event loop.
        Supports interruption via new messages.
        )r  rV  r  r  r%   r  r  r  Nr   r  r'   c                  <     sdS                                 S r  rm  r  s   r6   r  z:GatewayRunner._run_agent_inner.<locals>._run_still_current]  r  rB   r  r   r  r"  r0  )set_tool_preview_max_lentool_preview_length)set_friendly_tool_labelsfriendly_tool_labelsTtool_progressHERMES_TOOL_PROGRESS_MODEr#  tool_progress_overridesr  tool_progress_grouping
accumulate)choose_status_phraseresolve_status_phrase_catalogF)r(  r)  allow_genericr   r(  r)  r	  c                B   |r7t          	j                  }d |D             }||v rt          
|           sdS  
| |          }t          |t                    r0|                                                                dk    r|rdndS t          |          rdndS )z8Return off|raw|generic for a gateway visibility surface.c                 ,    h | ]}t          |          S r,  r-  )r?   items     r6   r/  zPGatewayRunner._run_agent_inner.<locals>._display_surface_mode.<locals>.<setcomp>C^  s0     ! ! ! ,D11! ! !rB   r  genericrV  )ra   r_   r&  rR   rU   rV   rW   r   )r   r(  r)  r	  r3  r4  r   r  r1  r  r  s          r6   _display_surface_modez=GatewayRunner._run_agent_inner.<locals>._display_surface_mode9^  s     - 
!#:6?#K#K ! ! =! ! !
 %55:;V]^^ 6 !5++KwPWXXE%%% =%++--*=*=*?*?9*L*L$1<yyu< KK255U2rB   )r  r  r  r.  r  r  r  c                    	  | |||          S # t           $ r-}t                              d|           | dv rdndcY d }~S d }~ww xY w)N)r  r  r  rM  catalogz*generic status phrase selection failed: %s>   r  waiting	heartbeatlong_runningzstill on itzone sec)r.   r/   r0   )r.  r  r  r  _phrase_err_generic_status_catalog_generic_status_recentr  s        r6   _generic_status_phrasez>GatewayRunner._run_agent_inner.<locals>._generic_status_phraseQ^  s    r++'#13     r r rI;WWW(,0b(b(b}}hqqqqqqqrs    
A"A AAr  >   logr  live_statusr  supports_status_textr  r  interim_assistant_messages)r(  r)  r  r9  voice_mixer_activecleanup_progressdelete_messager"   r  r  r  r  r  r  rY  r  r  r  r  r  r
  r  r  r  rE  rF  r  rs  r1  r  r  rw  r`  rv  ry  rz  r}  r  rV  r  r%   r  r  rl  r  r,  r+  r-  _effective_reply_in_threadr  r  r  r  r}  rI  r	  rc   c                  T  K   dS ddl m}  ddlm} t          dz  }|                    dd            | |dz  d	d
d          }|                     |d                     t          j        dt                               }|
                    t          j                   d|_        |                    |           	 	 	 |                    d                                           nq# j        $ r t#          j        d           d{V  Y nKt&          $ r?}t(                              d|           t#          j        d           d{V  Y d}~nd}~ww xY w# t"          j        $ r Y nw xY w	 	 	 |                    d                                           n# j        $ r Y nt&          $ r Y nw xY wF|                    |           	 |                                 |                                 dS # t&          $ r Y dS w xY w# 	 	 |                    d                                           n# j        $ r Y nt&          $ r Y nw xY wF|                    |           	 |                                 |                                 w # t&          $ r Y w w xY wxY w)uH  Drain log_queue and append tool-call lines to tool_calls.log.

            Only active when ``display.tool_progress`` is ``log``. Uses a
            RotatingFileHandler (5MB × 3 backups) so the audit log can't grow
            unbounded, and the shared RedactingFormatter so secrets never land
            on disk.
            Nr   )RotatingFileHandlerRedactingFormatterr
  Tr  ztool_calls.logi  P r  r  )maxBytesbackupCountr  z%(message)szhermes.tool_calls.Fr
  rV  zwrite_tool_log error: %srk   )logging.handlersr!  r   r#  r;  r  setFormatterr"  r#  r   setLevelINFO	propagate
addHandlerr  r  re  r  r`  r.   r/   r  rf  removeHandlerflushr.
  )r!  r#  r
  file_handlertool_loggerrs  r  rd  s         r6   write_tool_logz6GatewayRunner._run_agent_inner.<locals>.write_tool_logS_  s       <<<<<<777777"V+GMM$M666..**( 	  L %%&8&8&G&GHHH!+,PI,P,PQQK  ...$)K!""<000//#((y/C/C/E/EFFFF ; 1 1 1%mC00000000000$ / / /%?CCC%mA..............// )   #((y/C/C/E/EFFFF ;   $    )),777 &&((( &&(((((    DD#((y/C/C/E/EFFFF ;   $    )),777 &&((( &&((((    Ds   E" (C0 /E" 0$EE" 	E5EE" EE" "E41H 3E44H :(F# #
F;/	F;:F;(G? ?
HHJ'(H<;J'<
IJ'	IJ'IJ'.(JJ'
J$!J'#J$$J')rd  r	  r   r  )StreamingTTSConsumer)_load_tts_config)r  r  
tts_configr   r   z+Could not set up streaming TTS consumer: %sc                     K   t          d          D ]G} d         #d                                          d{V   dS t          j        d           d{V  HdS )z8Wait for the stream consumer to be created, then run it.r   r   Nr
  )r  rq
  r  r`  )r  r  s    r6   _start_stream_consumerz>GatewayRunner._run_agent_inner.<locals>._start_stream_consumer`  s      3ZZ * *)!,80377999999999FFmD))))))))))	* *rB   c                  ^  K    d         "t          j        d           d {V   d         "sd S 6                              s t                              dpd           d S  d                                       j        _        j        r	                    d           d S d S )Nr   r
  uL   Skipping stale agent promotion for %s — generation %s is no longer currentr   r  )
r  r`  r.  r/   r  r  r  r   r  r  )r  r  r  r  s   r6   track_agentz3GatewayRunner._run_agent_inner.<locals>.track_agent"`  s      q/)mD))))))))) q/) 
 )$2N2N^3 3) b%2"  
 :Fq/D,,17~ 8++J777778 8rB   c            	      X  K   sd S 	 t          j        d           d {V  	 
                              } | s4t          | d          r|                               r	d         }|r| j                                      }d }|y|j        pd}t          |dd           pg }
	                    |          r5

                    || |dj        r	dj        ind 	           d {V \  }}n|s|rt          |          }t                              d
           |                    |                                            d         }||                    d           d S nA# t           j        $ r  t&          $ r%}t                              d|           Y d }~nd }~ww xY w)NTg?has_pending_interruptr   r   r  zVoice-interruptrd  r	  r   z3Interrupt detected from adapter, signaling agent...barge-inz,monitor_for_interrupt error (will retry): %s)r  r`  r	  r   r9  r  rT   r   r-   r	  r	  rd  r  r/   r0   r  rt   abortrf  r.   )r~  r   _peek_eventpending_textr	  r  _stts_mon_err_interrupt_detectedr  r  r  r  r^  s           r6   monitor_for_interruptz=GatewayRunner._run_agent_inner.<locals>.monitor_for_interruptC`  sL      8[mC(((((((((6[  $77??H# ! 
 x)@AA ("hFdFdepFqFq (" ,Q  &" +3*D*H*H*U*UK+/L*6/:/?/E2 /6k<QU.V.V.\Z\#'#B#B;#O#O 
!Y<@<c<c(3(0(.(44ETZTd1n+v?O1P1Pjn =d =& =& 7& 7& 7& 7& 7& 7&OL!! *6 !Y+ !Y3KK3X3XL"LL)^___!OOL999/33555$A!$DE$0 %J 7 7 7!E-     [ [ [LL!OQYZZZZZZZZ[o8[s   E) D*E) )F'F""F'r     long_running_notifications)r(  r	  c                    K   d S                                } | sd S d }	 t          j                   d {V  	 }n# t          $ r d }Y nw xY w                    d         |          sd S t          t          j                    z
  dz            }d         }d}t           dd                    }|rt          |d          r	 |	                                }g }|r'|
                    d|d          d	|d
                     |                    d          p|                    d          }	|	r"|
                    t          |	                     |rdd                    |          z   }n# t          $ r Y nw xY wdk    r d          nd| d| }
	 d }|rX	 |                     j        ||
           d {V }n4# t          $ r'}t"                              d|           d }Y d }~nd }~ww xY w|rt'          |dd          s|                     j        |
t+          j                             d {V }t'          |dd          r<t'          |dd           r+t          |j                  }r
                    |           n2# t          $ r%}t"                              d|           Y d }~nd }~ww xY w)NTr   r  r   r	  r	  r	  r	  r;  r  r	  r  r	  r   r  r  u   ⏳ Working — z minzHeartbeat edit failed: %sr  Frc   r  r4  z#Long-running notification error: %s)r	  r  r`  	NameErrorr
  rF  r,   r   r   r	  rs   rT   rU   rD   r.   r'  r  r/   r0   r-   r  r   r_   r4  )_notify_adapter_heartbeat_msg_id	_exec_ref_elapsed_mins
_agent_ref_status_detail_want_iteration_detailr  r  r  _heartbeat_text_notify_res_ee_ne_NOTIFY_INTERVALrF  rE  _executor_taskr  _long_running_mode_notify_startr  r  r  r1  r  r  r  r  s                 r6   _notify_long_runningz<GatewayRunner._run_agent_inner.<locals>._notify_long_running`  s     '"66v>>O"  04LMm$4555555555% .II  % % % $III%BBa)   E #TY[[=%@R$G H H
 *!_
!#)-++#$)	 * *&  '*6L"M"M '<<>>!#1 "MM ZR0@-A Z ZBGWDX Z Z   #%&&"8"8"XBFFCW<X<X" 8"MM#g,,777! I-4tyy7H7H-HN$    *Y66 +*8444OMOO~OO  
M"&K( 	//0?0L0L & 1 /1 1 + + + + + +KK
  ) / / /"LL)DcJJJ*.KKKKKK/ ( KGKE,R,R K,;,@,@"N+%ABYdjds%t%t%t -A - - ' ' ' ' ' '
 #;	5AA Kg'tG G K 14K4J0K0K-0 K 0 7 78I J J J  M M MLL!FLLLLLLLLMWLMsg   A AAB'E9 9
FF#J ("G 
J 
G<G72J 7G<<BJ 
K!KK)	previewed
final_textrW  c                N   | dS t          | dd          rCt          | dd          }t          |          r!	  ||          du rdS n# t          $ r Y nw xY wdS |rJt          | dd          }t          |          r*	 t           ||                    S # t          $ r Y dS w xY wdS )z>Return True only when the actual final reply reached the user.NFfinal_response_sentdelivered_final_matchesThas_delivered_text)r-   r  r.   r   )consumerrX  rW  matcherr\  s        r6    _stream_confirmed_final_deliveryzHGatewayRunner._run_agent_inner.<locals>._stream_confirmed_final_delivery`  s    ux!6>>  "(,EtLLG$$ "7:..%77#(5 8$   t %%,X7KT%R%R".// %%#$6$6z$B$BCCC$ % % %$uu%5s#   A 
AA<B 
B"!B"r  rS  r  i  r  r   c                  0                                    S r;   rm  )_turn_run_generationr  r  s   r6   r   z0GatewayRunner._run_agent_inner.<locals>.<lambda>9a  s    55kCWXX rB   c                      dS r  r,  r,  rB   r6   r   z0GatewayRunner._run_agent_inner.<locals>.<lambda>;a  s    d rB   c                     	                                                rd         nd } | d| _        t                      | _        S S #                                   rd         nd } | d| _        t                      | _        w xY w)Nr   r   )rt   r  	frozensetr  )_finished_agent_turn_worker_doner  r  s    r6    _run_sync_with_timeout_lifecyclezHGatewayRunner._run_agent_inner.<locals>._run_sync_with_timeout_lifecycle>a  s    U#8::%))+++ :F&Ol1oo4O&2HJEIRFF 3 &))+++ :F&Ol1oo4O&2HJEIRFTTTTs   	A
 
>Br#   )	r  r  r  r  r  r  r  r  r  zgateway-turn-watchdog-r   )r  r  r   r  r  r9  r  zVoice-backup-interruptrd  r:  zABackup interrupt detected for session %s (monitor task state: %s)r  r  r;  r  r	  r
  r  rk   u   ⚠️ No activity for zB min. If the agent does not respond soon, it will be timed out in z- min. You can continue waiting or use /reset.r  z!Inactivity warning send error: %sr  ro  r  r  r	  r	  r  zaAgent idle for %.0fs (timeout %.0fs) in session %s | last_activity=%s | iteration=%s/%s | tool=%sr  u   ⏱️ Agent inactive for u(    min — no tool calls or API responses.z!The agent appears stuck on tool `z` (rT  z!s since last activity, iteration r;  z).zLast activity: r	  zs ago, iteration z6). The agent may have been waiting on an API response.zTo increase the limit, set agent.gateway_timeout in config.yaml (value in seconds, 0 = no limit) and restart the gateway.
Try again, or use /reset to start fresh.r   r  )r  r  r  r  r  r  r  r  )_AGGREGATOR_PROVIDERSnormalize_model_for_providerr  g      $@z%streaming TTS wait_complete error: %sz"streaming TTS finalisation timeoutr  "_mark_streaming_tts_completed_turnr  r8  z5Ignoring control interrupt message for session %s: %sr  zVoice-drainz9Processing queued message after agent completion: '%s...'r  pending_steerz0Delivering leftover /steer as next turn: '%s...'rE  uZ   Discarding command '/%s' from pending queue — commands must not be passed as agent inputz=Discarding pending follow-up for session %s during gateway %sz#Processing pending message: '%s...'r  u^   Interrupt recursion depth %d reached for session %s — queueing message instead of recursing.queue_message)r  r  r  rW  r  z5Stream consumer wait before queued message failed: %srR  r  r  zZQueued follow-up for session %s: suppressing intentional silence marker before continuing.zoQueued follow-up for session %s: final stream delivery not confirmed; sending first response before continuing.z7Failed to send first response before queued message: %sz_Queued follow-up for session %s: skipping resend because final streamed delivery was confirmed.r  r  r  uN   Discarding stale goal continuation for session %s — goal is no longer activez:Queued follow-up session-key resolution failed; reusing %sr   r  r  _streaming_tts_completed_turns_streaming_tts_turn_key)r  rV  r  r  r%   r  r  rl  r  r  r  r  final_content_deliveredr[  rS  zSuppressing normal final send for session %s: final delivery already confirmed (streamed=%s previewed=%s content_delivered=%s).r  r  __no_edit__)r  r4  r  r7  r  ziReconciled stale streamed finalize for session %s: edited message %s with the complete response (#71643).zoStale-finalize reconciliation edit failed for session %s (%s); sending complete response via normal final send.r  znStale-finalize reconciliation edit failed for session %s: %s; sending complete response via normal final send.zStale streamed finalize detected for session %s with no editable message; delivering complete response via normal final send (#71643).zPEdited streamed message %s for session %s to include plugin-transformed content.z2Failed to edit streamed message for session %s: %sr  c                  |    dfd} 	 t           |             t          d           d S # t          $ r Y d S w xY w)Nr'   c                  p   K   D ]/} 	                      |            d {V   # t          $ r Y ,w xY wd S r;   )r  r.   )_mid_adapter_snapshot_chat_id_snapshot_ids_snapshots    r6   _delete_allzRGatewayRunner._run_agent_inner.<locals>._cleanup_temp_bubbles.<locals>._delete_alld  s       - ! !!"3"B"B 14# #          ) ! ! ! D!! !s   &
33z$Temp bubble cleanup scheduling errorrw  rX  )r   r/   r.   )rw  rt  ru  rv  _loop_snapshots    r6   _cleanup_temp_bubblesz=GatewayRunner._run_agent_inner.<locals>._cleanup_temp_bubblesd  s    ! ! ! ! ! ! ! !,#~%$J     
 !   DDs    - 
;;z-Post-delivery cleanup registration failed: %sr,  rX  )r  r  r  rs  rd  r   rQ   r=  r_   r  r  r  rT   rR   rS   r2  r1  r  r  rF  r.   r   rq   r  gateway.status_phrasesr  r  rU   rt   r   r  r  r  r	  r-   Queuer1  r|  r{  r   r  r  r  r  r	  r   r  r  r8  r  r%  r  r  r  rX   r  r  rd  r	  r	  r   FEISHUr8  rK  rt  r  r  r  r  r^  r  r  r  r  r  r  r  r  r  rW   r^  gateway.streaming_tts_consumerr1  rr  r2  rg  get_event_loopr  rr  r/   r0   r  ri  r  rY  r,   r  r  snapshot_running_idsr  r  ro  r  rp  r  r  r&
  r  r  r  r9  r  r   r	  r	  r  r  r  r  r<  r	  r  r  r  r   r  rs   rD   rb  hermes_cli.model_normalizerh  ri  r  rV  r  r  wait_completesuppress_whole_filer  r  r  rV   r   rC   r>  rF  r  r  r  r  _MAX_INTERRUPT_DEPTHr   r?  rl  r  rf  r  r  r
  r  r0  r  r  r/  isawaitabler  r$  r  r  r  r  r=  r  rc  r8  r-  r  r4  r'  r  r  r  )r  r  rV  r  r  r%   r  r  rl  r  r  r,  r+  r-  r  rs  r  r  r  agent_cfg_localr  display_configr  _tplr   _ftl_resolved_tp_env_tp_display_cfg_platforms_cfg_platform_cfg_legacy_tp_overrides_tool_progress_configuredr  rY  r  r  r  r  r  r  rw  interim_assistant_messages_moder`  _thinking_moder  rv  r  r  r  r  r
  ry  rz  _va_vtc_gid_tcr}  _cleanup_adapter_cleanup_deleter  r  turn_ctxturn_runner_progress_reply_in_thread_slack_adapter_for_progress_mode_fn_progress_thread_id_relay_prospective_thread_idr8  rK  r0  rt  r  r  r  r  r  r  r  _is_voice_inputr1  r2  _tts_cfgrg  _stts_consumer	_stts_errprogress_tasklog_taskr  r5  r7  tracking_taskrB  interrupt_monitor_NOTIFY_INTERVAL_RAWrV  _notify_taskr_  _agent_timeout_raw_agent_timeout_agent_warning_raw_agent_warning_warning_firedr  _turn_task_id_turn_process_baseline_turn_timeout_fired_turn_cleanup_lock_turn_is_currentrg  _inactivity_timeout_POLL_INTERVALr  r  r  _backup_adapter_backup_agent	_bp_event_bp_text_bp_media_urlsr?  rK  
_idle_secs_act_warn_adapter_elapsed_warn_remaining_mins	_warn_err_timed_out_agent	_activity
_last_desc	_secs_ago	_cur_tool_iter_n	_iter_max_timeout_mins_diag_linesr  _result_for_fb_run_failed
_cfg_modelrh  ri  _agent_providerr  r  _stts_done_err
_mark_turnr  r  r8  rr  r	  _leftover_steer_pending_parts_pending_cmd_word_rc_pending_has_stream_consumer_stts_finallyr   was_interruptedr  rs  _delivery_result
_previewedfirst_response_already_streamedr  r  _bg_cb
_bg_resultupdated_historynext_sourcenext_messagenext_message_idnext_channel_promptnext_session_keynext_message_type_clear_adapter_completed_turns
_prior_key_pk_followup_adapterr  _final_is_empty_sentinel_content_delivered_stale_finalized_matcher_transformed	_streamed
_sc_msg_id_sc_adapter_reconcile_res	_edit_errry  _rperR  rt  ru  rF  rE  rS  r  r  r  rv  rA  rT  rx  rU  r  ra  rf  r  r  r  r  rd  r1  r  r  r^  r  s   `   ` ``                                                                                                                                                                                               @@@@@@@@@@@@@@@@@@@@@@@@@@@r6   r  zGatewayRunner._run_agent_inner]  sC     <    
	22-%'-!1 3 	 	 	 	 	 	 	 	 	 	&%%%%%	MD 	M 	M 	M 	M 	M 	M 	M 	M
 +,,+FO<<??????!"5"5k<"P"PQQ%//'228b+//0CDDL$B77.$// 	 N
 	CBBBBB	>>>>>>**;F[]^__D$$$%=SYYYA>>>> 	 	 	D		>>>>>>**;F\^bccD$$T$ZZ0000 	 	 	D	 /.{L/ZZ)788)3ND)I)IQ~~r%))+66<"&**<88>B+//0IJJPb|+ =$// 5#}4 /66 9 $88 	" 484GG2'2U 	 43KOghhxlx^^^^^^^^,."?"?\"Z"Z
 "=A"'	3 	3 	3	3 	3 ,/s8d?		3
  	3 	3 	3 	3 	3 	3 	3 	3 	3 	30 JNeiw{ 	r 	r 	r 	rC$J 	rX[^bXb 	rqt 	r  AD 	r 	r 	r 	r 	r 	r 	r 	r 	,+++++ -^ C k[c[kHk 43}f
 
  $77??+-CUKK 	(#' %%#'  )E1YfoIY6Y;K*U+%+---QU	 +@*?(+3+>*?+
 +
 +
' Ox// 9/58 	+ /.+3+>*?
 
 

 +e34I8I +?HDF	!Fs $)' "715?h...-##H$455C 3 6==D$%% '#7K*L*L !%  ID#3xx3v~#6#6663;Q;QRV;W;W6.2(+!244 !##K?QRR
 
 @QZ433F;;;VZ VfUq'$'7"8"8:JDQQQw{'#"5"DDD !&#&( !&w!% *
 *
 *
6*
11*
 "6!5*
 0/	*

 0/*
 (-*
 0/*
 #8"7*
 *>*
  i*
 0/*
  i*
 %<$;*
 &*
 "6!5*
  $:#9!*
" 0/#*
$ .-%*
& G'*
( G)*
* %<$;+*
, $-*
. .-/*
0 0/1*
2 .-3*
4 0R/Q5*
6 "6!57*
8 .-9*
: .-;*
< ,O=*
> G?*
@ *>A*
B *>C*
D "zE*
F $G*
H *>I*
J .-K*
L .-M*
N "zO*
P "6!5Q*
R $:#9S*
V !x00 &1%B"&1&D#$ %)!?hn,,*.*B*B6*J*J'*65  '34   H
  )) 484D4D11487>DHH 14 5 51
 ! 5 5 504---59OV-/?5
 
 
 ("222 >FF 3 7>> 3 $ 3  7>>???
  	%$ !
+"f&666 ,,V5EFFF11#!&+t<<$4 2    '+ 	 %*F% #89I!J9:LW]Wfggg HOX5H#III$ J$ J ,	 J   	5	 5	 5	 5	 5	 5	t '9#&8#!,!C v ,v"&
 04f%!. ,*@'1N. !133Z
 #1('2'F$
 )4(H% 226:: .?ho--&2B-GW- 1'7A A## %
'/&&*::: 009IJJJ55ON'%fk4@@(8 6    +/ $ '.3O.
 *+;+' $3 #2 +B()4)J& 0088$ UGL'<@@AAGGIIWT 	
 % &77GG &WOOOOOO;;;;;;++-- $ 2 Ng6L6N6N!5!5)"N'&4" " " "( +7E1!4"((***  W W WJIVVVVVVVVW '  	J#/0F0F0H0HIIM  	=*>>+;+;<<H 	* 	* 	* 	* 	* )*@*@*B*BCC	8 	8 	8 	8 	8 	8 	8 	8.  +KKMM:: &moo<	[ <	[ <	[ <	[ <	[ <	[ <	[ <	[ <	[ <	[| $/0E0E0G0GHH  **H#NN3G!3K3K//QU22(
 
 

 &&#	X	M X	M X	M X	M X	M X	M X	M X	M X	M X	M X	M X	M X	M X	M X	M X	M X	M X	M X	Mt *+?+?+A+ABB $	"	 "	 "	"	 	"	
 "	 "	 "	 "	Hc	 ",,BD!I!I3E3I3I//tN!+,JC!P!P3E3I3I//tN"N @?????&,"M%5%J%J=%Y%Y"'4H$(>H% ) 1 1"+/"3"3!*!1!1 $2  (3 YXXXXXX"l U U U U U U U* ) 9(4#0,B#1'8)<(:),,<
 
 G-2DFF   %'''$2223STT N #( N%  )8$+L'(.% % %      GD!  #1#8#8#:#: /5577  8K  8*.*B*B6*J*J(4Q+ 8 8$+O=T$U$U8$3$I$I+$V$V8 )8(I(M(Mk(Z(ZI9B'Ly~~H(418LRV1W1W1][]#'#B#B9#M#M 
!S8<8_8_(1(7(.(0B4LTZTd1n+v?O1P1Pjn 9` 9& 9& 3& 3& 3& 3& 3& 3&KHaa *2 !Sn !S/G	/R/RH"KK!; +*;*@*@*B*B Q		   *33H===/33555$A!$DE$0 %J 7 7 7S)8 R  _8$+L'(.% % %      GD!  	 $2#8#8#:#:*1133 .2+!-aJ!$J! !gj:P&Q&Q !!#-#B#B#D#DD)-2JC)P)PJJ( ! ! ! D! + ]~/I *n < <)-(,(@(@(H(H( ],/"0D,E,E,JM.1>N3RWY2Y.Z.Z._^_O
]&3&8&8$*N%Om %O %O7F%O %O %O .E '9 '" '" !" !" !" !" !" !" !" !" $- ] ] ] &-PR[ \ \ \ \ \ \ \ \]!^33.2+!(#B0<+84J/@1D0B4D$ $ "Mcrc8J!L!L#'    %'''.5577  8K  8*.*B*B6*J*J(4Q+ 8 8$+O=T$U$U8$3$I$I+$V$V8 )8(I(M(Mk(Z(ZI9B'Ly~~H(418LRV1W1W1][]#'#B#B9#M#M 
!S8<8_8_(1(7(.(0B4LTZTd1n+v?O1P1Pjn 9` 9& 9& 3& 3& 3& 3& 3& 3&KHaa *2 !Sn !S/G	/R/RH"KK!; +*;*@*@*B*B Q		   *33H===/33555$A!$DE$0 %J 7 7 7_8B # =#/? 	# 0@BX(Y(Y $4$I$I$K$K		$    ']]+?KK
%MM*BAFF	%MM.99	#--(8!<<%MM*:A>>	E~{'   $ X*+;=VWWW #Nb$8 9 9 >Q) ) ) )  &&=I = =%B= =%,= =/8= = =     &&N* N N	N N N%,N N/8N N N  
 ""?   '+ii&<&<HUVWHX `a 0 4 4Z D D D^`!()!_2&'" " "!_F*1-N:HS.,,X666eK!gfg&>&>!{!355
	        '.fj"&E&E&KO& _?BW+W+W%A%A*o%^%^
    D<:--d6W6WXcekeq6r6r- ,,[999 #1%F..v66G 2!4E Z--d-;;;;;;;;;;  Z Z ZLL!H.YYYYYYYYZz ; KK DEEE--c-:::::::::, @1D!(2VX\!]!]J
++ @"
;??? !MG *p' *pk *p 6w L L !% : :;Q^ _ _::m,, !p] !pvzzReGfGf !p(.

3F(G(G%45FGG 4S'.3-    #4" p %2$6$<"M")-t"L"L"RPRK66}EE [+/+R+R)#")(5HNHX%bk63C%D%D^b ,S , , & & & & & &
  ' N&>}&M&MG"/"Z3KM3Z3Z p%`bijmkmjmbnooo  cg cm c"(**_"="=" c-GLL!SU\]`^`]`Uabbb  7==??55c:: !(!6!6tQ!?!?ES$[N1$5abb$9$?$?$A$A$AY[!$ VVVVVV&;'899 +"KK!M 1  
 -1M&*G$    ~ = G S&3--//  
 !% VY VYBGCRCLQQQ
  Bww0BCC B BXcgngXX,[9??AAA $t'@@@NNA(+  
 #66v>>G D= D3G4M{\ijjjj  DWWo%F%F D--k7CCC(+`(X_/`/``F  '$$&&& "!!!$$&&&!!!  ! + >.q1= % , !&&((()))))))))"1   !%.{CHHHHHHHHHHH#0'2HI ! ! !#**,,,!"---------&5 ! ! ! D!	! :!<M(1C(##I...'55c5BBBBBBBBBB    D   """  11 2    ~ 8++J777 '2C]T`a   "







"1   } #)**]";";& V% 13C 
e{ 
e	e")"2;"L"L"LLLLLLLLL ' 4g6LM % % %'..000%&1 1 1 1 1 1 1 1 1#*#9 % % % $%( e e e"LL)`bcdddddddde 4>h3M3M'axxTZT`^`$!%&6&:&:;O&P&P!Q!QJ%5%9%9:JB%O%ON(H(H&",) ) )%5``````/R/R,n0 0,, % 5 5 5/4,,,5+ x'.3    ( 0A i"KK !R + 2s   #*,, & .)@ #/ # #        
  ) i i i"NN+dfghhhhhhhhi' }'.3   tG}}.JDQQ]!(!C!C''5 "D " " $F++ %%-3VXX
#*#6z#B#B !5*4$4$4$4$4$4$4$4#, % % % $%% ! %WW6P%Q%Q %!(!A!E!EkSW!X!X#F++ %%-3VXX
#*#6z#B#B !5*4$4$4$4$4$4$4$4#, % % % $% #)**Z"A"A$&"&&*##.  %)! ,")-4"H"H"RFK77FF &tOrOrs}O~O~ &l'.3    &h  '$$&&& "!!!$$&&&!!!  ! + >.q1= % , !&&((()))))))))"1   !%.{CHHHHHHHHHHH#0'2HI ! ! !#**,,,!"---------&5 ! ! ! D!	! :!<M(1C(##I...'55c5BBBBBBBBBB    D   """  11 2    ~ 8++J777 '2C]T`a   "







"1   W+/+G+G+T+T(($   X'.3%) %      *.)Z)Z+* /$4	 *[ * * $ $ $ $ $ $L $+%~  '$$&&& "!!!$$&&&!!!  ! + >.q1= % , !&&((()))))))))"1   !%.{CHHHHHHHHHHH#0'2HI ! ! !#**,,,!"---------&5 ! ! ! D!	! :!<M(1C(##I...'55c5BBBBBBBBBB    D   """  11 2    ~ 8++J777 '2C]T`a   "







"1   w '+&B&B=&Q&QO*1-AQSW*X*X'(/~t(T(T%
 "&!9!9&!A!A!-+-.B\'.~?_ae'f'f$'3%,^=VX\%]%]
#J// >",*[."I"IC" > 0 8 8 = = =
 %)$<$<V$D$D!$ /;;"N%< <           %   " ==k:VVVVVVVVV(,(#1+&) 0#1%5%9%4#6!2 )8 ) ) # # # # # # @XX  '$$&&& "!!!$$&&&!!!  ! + >.q1= % , !&&((()))))))))"1   !%.{CHHHHHHHHHHH#0'2HI ! ! !#**,,,!"---------&5 ! ! ! D!	! :!<M(1C(##I...'55c5BBBBBBBBBB    D   """  11 2    ~ 8++J777 '2C]T`a   "







"1   mVYr  '$$&&& "!!!$$&&&!!!  ! + >.q1= % , !&&((()))))))))"1   !%.{CHHHHHHHHHHH#0'2HI ! ! !#**,,,!"---------&5 ! ! ! D!	! :!<M(1C(##I...'55c5BBBBBBBBBB    D   """  11 2    ~ 8++J777 '2C]T`a   "







"1   {  '$$&&& "!!!$$&&&!!!  ! + >.q1= % , !&&((()))))))))"1   !%.{CHHHHHHHHHHH#0'2HI ! ! !#**,,,!"---------&5 ! ! ! D!	! :!<M(1C(##I...'55c5BBBBBBBBBB    D   """  11 2    ~ 8++J777 '2C]T`a   "







"1   ( %Q'h%% t	hll8.D.D t	\\"2339rF%+!Bv/B
 hll+?@@AAJ!%F%>FF" "  %! /*< /"3(A4HHH%% 11+38F+;+;u+D(($ 1 1 1+0(((1# /).&  -C D DEEL 98$  I
 & El E	 EM_ E V&3&   ,0((' < <AQ <VYVe !^
%c9d;; *"="=+BY/:/G/G$*N'1$*%)	 0H 0 0 * * * * * * #>9dCC 7;H^4"KK !L + 2sJ   
 #NN !R + 2s ' F F  
 %    M'.3	        KK a#*s    ( L S_ !^
 !k66$*N'1$,-=$>%)	 7          480n&(:s    %   P'.3	        '	T ,  - - 8T** - LL**	 -
 (*KLL - !!122M & 0$577N        $T @@)- A    
  T T TLdSSSSSSSST su  0E 
EE,F 
FF9A%Y Y.-Y.6A%f 
g&gg$MBY
 -*z BY
 
z%"BY
 $z%%ABY
 7*|" !BY
 "
},}BY
 }G%BY
 D7AE EBY
 E
AEEBY
 EAEEF7BY
 L-AL? L>BY
 L?
AMM	BY
 MAMMA9BY
 OAO# O"BY
 O#
APO-APPBY
 PAPPJBY
 Z0A[ [BY
 [
A[[BY
 [A[[D3BY
 b Ab	b	AbbAbbAb<b</Adc,Ac5c4Adc5AddAddAddAddAdd7Aee
Ae!e Ae!f9AggAggAgg$BY
 g>Ah hBY
 h/AjiAiiAjiAi&i#Aji%Ai&i&Aji)BY
 i+	Aji4AjjBY
 jAjjA$BY
 k>Al lBY
 lAl lBY
 lAl l 'BY
 mA An	 nBY
 n	
An8nAn3n.BY
 n3An8n8A&BY
 p'Aq qBY
 q
AqqBY
 qAqqA BY
 r'Ar= r<BY
 r=
As
sBY
 s	As
s
BBY
 wAwwAw#w"Aw#w'Axx/Ayx4Ax=x<Ayx=AyyAyyAyyAyyAyy?Azz
Az)z(Az)|A|
|
A||A||"A|8 |7BY
 |8)A}$}!BY
 }#A}$}$&BY
 @B@@B@@B@@"B@?@?/BBA/BA8A7BBA8BB
BBBB	BB
B
BBBBBB:BCC
BC$C#BC$D<BEEBEEBEEB?BY
 H"BH? H>BY
 H?
BII	BY
 IBIIABY
 LBL&L&BL8L7BL8L<BMM/BN*N	BNNBN*NBN$N!BN*N#BN$N$BN*N)BN*OBO1O1
BO>O=BO>QBQQBQ1Q0BQ1S0BS9 S9BTT
BTTBT, T,/BU=UBU%U$BU=U%BU7U4BU=U6BU7U7BU=U<BU=V'BW W
BWWBWX)BX2X2BYYBYY
A9B`[B[[B`[B[[B`[B[[B`[#B\ [?B`\ /B]\0B\9\8B]\9B]	]B]]
B]	]B]]B`]B]])B`];B^^B`^
B^%^"B`^$B^%^%AB`_=B``B``B`	`B``B`	`B`cBc+ c+Bc:c9Bc:fBBh h
BihBiiBii7ABk
 k

Bk<kBk7k7Bk<m7Bn n
Bn?nBn:n:Bn?r;   rX  )r"   r  )r	  r   rU  )r   r$  r'   N)r  )r  )r  r:  r  )r  r[  r\  )NNNF)	NNr   NNNNNN(  r   rx  ry  rz  r  rU   __annotations__r  rH  r  rG  rG  r  r  r   rF  r  r   r  r  r  r  r   r  r  r%  r  r  r  r  r  r
   r  r  r   r  r3  r  r	  r
  r  r4  _turn_lease_tokensr  rk  rl  rm  rn  rp  rq  rs  r  r  r  r  r  r  r  r  r  r  r   ra  r#  r%  r&  r'  r(  r)  r*  r+  r  r  r  rR  r  r;  r  r  r  r  r  r  r  r   r  r  r  r  r  r  r  propertyr  r	  r  r  r  r  rd  r  r   r  r$  r'  r)  r+  r.  r2  r  r;  r?  rS   rX  rc  r  rg  r  rm  rj  ro  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  staticmethodr  r  r  r  r	  r	  r	  r	  r  r	  r	  rU  rV  r!	  rW  rX  r+	  rZ  r1	  r\  r7	  rY  rZ  r\  r]  r^  r_  rM	  r`  r  ra  rn  rm  r`	  rd	  rh	  rn	  ru	  r|	  rw	  r	  r:  r	  r	  r	  r	  r	  r
  r
  r
  r(
  Futurer"
  r
  r'
  r;
  r5
  rt   r8
  r>
  r@
  rg
  r~
  r
  r
  r
  r
  r
  r
  r
  r
  r
  r
  r
  r
  AbstractEventLoopr
  r
  rr  r  r  rc  ri  r  rd  r  r  r  r  re  r{  r  rh  r  r  r  rq  rZ  r\  ra  ro  r  r  r	   rz  r  ry  r  rQ  rZ  r[  r`  rN  rW  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  r  r  r  r  r  r  r  r-  r=  rB  r8  rO  rX  r9  ri  r:  r;  r  r  r  r  r  r  r  r  r   r  r  r  rP  r  r  rJ  r  r  r  r  r  r  r2  r   r  r>  r<  r	  r	  rR  r=  _APPROVAL_TIMEOUT_SECONDSr  r  WHATSAPPr  r  EMAILSMSDINGTALKr|  WECOMWECOM_CALLBACKr  r  r  r<  _UPDATE_ALLOWED_PLATFORMSr`  rY  r_  ra  rb  r&  r  r/  r&
  r  r  r  r  rF  re  rg  rh  r	  r  r  r  r	  r  r3  objectr  r  r  r  rj  r)  r  r   r%  r"  classmethodr'  r8  re  rd  rG  rH  rP  r=  rV  r
  r  r'  r  r_  r  r  r.  r,  r   r8  r+  r  r*  r  r  r  rk  r  r  rq  ru  r  r  rb  r  r-  r  r  r  r,  rB   r6   r  r    sX=          (c'''&OS&&&$IEIII)SSSS $J$$$It#(D((($$$$"'4'''#t###!&$&&&-2$d2227;Xm4;;;)-J&---,0M8GL)000SWxS$x7M2N-N(OPWWW'+x}+++). $... +*+<==O--.BCC112JKK''77L4466223LMM334NOO';';*( ($ $8#78V#W#W &:&:)' '# 0/0FGG))*:;;N"6"67T"U"U,,-@AA-A-A0. .* 212JKK++,>??--.BCC112JKKtC$78    # .    )s )x7O ) ) ) )Bs Bt B B B B

d5k 
 
 
 
 6:(>2999.2hsm222-1Xc]111!$$$$;?X&78???-2$d2228<Xn5<<<~8 ~8x6 ~8 ~8 ~8 ~8B   >-
 -
 -
 -
f$     $&??-8 -c -c - - - -4S>    4@ @ @ @,s ,d ,W[ , , , ,+c +D +UY + + + +$* * * *X"327	   :   < >B2 2 2-5c]2	2 2 2 2h8% 8 8 8 86 6u 6 6 6 6$ :?$
 $
 $
26$
	$
 $
 $
 $
L<PT < < < <  "T " " " X" '$ ' ' ' X' !Xc] ! ! ! X! 8C=    X
m 
 
 
 
 
<= T    2 #,)RI"6"67M 7d 7 7 7 7	m 	 	 	 	 	 +/'= T    (
C 
 
 
 

# 
 
 
 

 
8C= 
 
 
 


 
	
 
 
 
&
  
   444 
#4 4 4 4l@@ 
@ @ @ @> +/%)&*f% f% f% 'f% c]	f%
 d^f% 
sDy	f% f% f% f%P-s -3 -X\ -ae - - - -^.Y .YS .YT .Y .Y .Y .Y`OS#X O4 O O O O #9L #QU # # # #8!"*!"	!" !" !" !"F`>Q `VZ ` ` ` `D## #$ # # # #
)c ) ) ) )
C 
 
 
 
    (s    (    8/U / / / /,E , , , ,."
4 "
 "
 "
 "
H,Z ,Z ,Z ,Z\
 
 
 
 
5 5 5 5"1 1 17U 7UU 7Ud 7U 7U 7U 7UrDc D D D DLs L L L LWT W W W W"5 5N 5UX 5]a 5 5 5 5   /	
 
.	!   > @D          U3 U4 U U U \US 3 SV    6	 	 	 	 	 	
 
HSM 
W_`cWd 
pt 
 
 
 
   @0 0 0 0(/ / / /0* *U *T * * * *H )-$('+   !	
 SM  } 
   0 AC $
 $
 $
# $
t $
 $
 $
 $
L4    4 Dc3h$8    \B 
U3 
U 
U 
U \
U" '+#'#'#
 #
 #
#
 #

 d^#
 C=#
 C=#
 
#
 #
 #
 #
T $(#'E E EE E
 C=E C=E 
E E E E8 4 4c 44$; 4 4 4 \4  F Fc4i8H F F F \F8 +/%)2 2 2 '2 c]	2
 2 
2 2 2 2:

 #4.
 
	
 
 
 
" %)) ) c]) 
#	) ) ) )@ 	
 

 	

 

 
 
 
* d
    \$ 
$ 
 
 
 \
 
3 
 
 
 \
 A# A A A \A.     \$ e    \,     \6 	D 	 	 	 \	 $+    \$-$ -$ -$ -$ -$^ !$c !$$+ !$$ !$ !$ !$ \!$F
$sCx. 
 
 
 
hsm    H H# H H H H  
sHSM!	"	   : #3 #4 # # # \#J4C 4D 4 4 4 4l Q Q Q Q \Q !%83 %8| %8X\ %8 %8 %8 %8N#/L #/S #/ #/ #/ #/Jx| xZ] xbf x x x xt9#% 9#E$sCx.RVBV<W 9# 9# 9# 9#vQ Q Q Q Q QE E E ENFT#s(^ FPT F F F FPc]   }	
 
   @ $.$. $.
 $. 
$. $. $. $.N -/& & &&&)&	& & & &P9c 9d 9 9 9 9v 0S T    6/c / / / /b     *y y y yv]S ]S ]S ]S~F F F F FP 38U ' ' '4 'd 'W[ ' ' ' '\ %9FFF ?$? ? 	?
 
? ? ? ?<, 4     C    48` 8` 8` 8`t    \ic i i i iVJ J# J J J JX
t 
 
 
 
 26'+ -. 8$ 
	   4^0I ^d ^ ^ ^ ^,Y Y Y Y$DT D D D DL  !  #?CaZ^ \ \ \ \ \|0* 0*u 0*t 0* 0* 0* 0*dK>$sCx. K>T K> K> K> K>Zp' p'c p' p' p' p'd? ? ? ? ?  *>s >x~ > > > >"v5 vS v v v vp' 'U ' ' ' '0c    
 
 
 
0Q' Q' Q' Q'f   @         !& %C C C C 	C
 C 
C C C CJ* * * *V V V V Vp@@/5@@DUCZ@P@	@ @ @ @D7$7 7 	7
 
7 7 7 7,`<`<+3`<	`< `< `< `<D99+39>Q9	9 9 9 92+3	&'48	9   

 
 %	

 

 
 
 
F#    8  $ $ $ ''%('	%' ' ' \' B( BS BXe_ B B B \B* .X .X# .X .X .X \.X`AA A 
%	&	A A A AL '+$ $$ sm$ 
3x}5t;	<	$ $ $ $V(Gc (Gd (G (G (G (GTT#T T 
,		T T T TH Q,I	) )tCH~   G
!G
7:G
 G
 G
 G
R|     $ $ $ $ $ $
9l 9s 9 9 9 97\ 7c 7 7 7 7&&=| &= &= &= &= &=P/F| /F /F /F /F /Fb{l {s { { { {&BB< BBHSM BB BB BB BBH,> c d    $UC UD U U U U* &*V V V V 	V
 d38n%V c]V 
#V V V V| &*
 
 
 
 	

 d38n%
 c]
 
#
 
 
 
0
# 
 
 
 
s tCy         * %6    Xc    }9# }9_b }9 }9 }9 }9~=+ +3 + + + +(v c v  v  v  v v(D#(D47(D	#(D (D (D (D`%} %s %t % % % %TO, O4 O O O Or6| 6 6 6 6 6<!Q\ !Q !Q !Q !QLS    *W W W W0S 3 4    &)S )SV )[_ ) ) ) )VMG MG 	MG
 MG 
MG MG MG MGb \ hsm    \7Xl 7Xs 7X 7X 7X 7Xr%| % % % % %.MS MT M M M M's 'S 'VY '^b ' ' ' 'RM,M,&)M,7:M, M, M, M,h #J JJ J 	J
 J 
J J J JXHd H H H HG\ G G G G G GRkIkI kI
 
kI kI kI kIh +/*.+/    	
 #3- T#Y' d3i( 
   @ +/*.+/L LL  L 	L
 #3-L T#Y'L d3i(L 
L L L Lh
] 
t 
 
 
 
8'U- 'UD 'U 'U 'U 'URU] Ut U U U U$	C 	C 	 	 	 	
= 
T 
 
 
 

] 
t 
 
 
 
4#4	%S/	"4 4 4 4lC C    & 15Xl XlXl Xl 	Xl
 U38_-Xl 
Xl Xl Xl Xlt2626 26 	26
 
26 26 26 26hSdSd Sd 	Sd
 
Sd Sd Sd Sdj= T    .#6#6 #6 	#6
 
#6 #6 #6 #6J ,1(M d    &
3 
 
 
 
,"
- "
TW "
 "
 "
 "
J,  , RU ,  ,  ,  , \4< 4Y\ 4ad 4 4 4 4xi;| i; i; i; i; i;zn
 n
 	n

 n
 n
 
s$d*	+n
 n
 n
 n
`B B 	B
 B B 
#B B B BH4S>      .2  &c] 
$sCx.	!	   4 $(-1!%" " "8$" #" C=	" C=" &c]" #" 
$sCx.	!" " " "H  $(!%  8$# C=
 C= # 
   \> .| . . . . \. !$ !*	8>8+<h&7)@(/S[Sgiqiw  zB  zH	+ ! !X X X X  #!$	tK tKtK tK 	tK
 
tK tK tK tKlu u u u unM0(5c8TW=AX;Y2Z M0 M0 M0 M0d GKQ Q Q s5c8C=)@#ABCQ 
U3Xc]*+	,	Q Q Q Qf#
 #
4 #
 #
 #
 #
J# #$ # # # #
	
 	
 	
z1D    &* * * *, +/%)&*"&#G G G 'G c]	G
 d^G 3-G }G 
G G G GRCC #YC 
	C C C CJJ1J1 #YJ1 
sDI~		J1 J1 J1 J1X49     $(5 5 C=5 
sTz49$	%	5 5 5 5J ''V 'V 'V
 #Y'V 'V 
'V 'V 'V 'Vb + + +
 + + 
sDI~	+ + + +ZL
t L
 L
 L
 L
\oo$(o	$o o o ob 4 HU3VCS=T4U    \(33 33 3 3 3 3j@^@^$(@^	$@^ @^ @^ @^D3D 3T 3 3 3 3*0* 0* 0* 0* 0* 0* 0*d|>$ |>4 |> |> |> |>| )   0" PRU3d
?%;T#s(^%K LQQQE4S> E E E [E <T#s(^ < < < [<: (t ( ( ( ( [(T  #'""&#(G> G>G>G> G> 	G>
 4KG> tG> 4ZG> !G> 
G> G> G> \G>R<
S <
T <
 <
 <
 <
|%%'*%<@%	% % % %<
C 
D 
 
 
 
.3 .$ .SW . . . .M M# MRV M M M M )-	7 7 77 !	7
 
7 7 7 7rs C D    :03EH	   :3
S 3
S 3
T 3
 3
 3
 3
j*# *$ * * * *X) ) ) ) ) ) UW 
 
 
c 
c 
[^ 
 
 
 
/3 /C /D / / / /  $J	
 
   . '+R2 R2 R2R2 R2
 R2 !R2  $R2 
R2 R2 R2 R2hII,4SMI	I I I IVR3 RtCy RUY R R R R@s @tCy @ @ @ @0 0UX 0]efi]j 0 0 0 0<#'6>sm	   2 LK4 LKC LK LK LK \LK\Es Et E E E EN "3 " " " " " \"65Oc 5O 5O 5O 5O 5O 5On	0s 	0 	0 	0 	0 	0 	0) ) ) ) ) ):P P P PdV3 V V V Vx     C<C< C< 	C< C< 
4C< C< C< C<X  (,*.Y
 Y
Y
 Y
 d38n%	Y

  Y
 Y
 Y
 !Y
 #3-Y
 
c3hY
 Y
 Y
 Y
H	  (, !*.(,%).226&*/ // / d38n%	/
 / / / !/ / #3-/ !/ TN/ 'sm/ !)/ sm/  
c3h!/ / / /b.} .# . . . .`6%} 6% 6% 6% 6% 6%~  (, !*.(,%).226&*a aa a d38n%	a
 a a a !a a #3-a !a TNa 'sma !)a sma  
c3h!a a a a a arB   r  r  )r  
stop_eventc                   ddl m}m}  |            }|                                 s	 |                                rZt          |dd          sIt          |dd          r8 |            s|                     |           k|                    |d           dS n2# t          $ r%}t          
                    d|           Y d}~nd}~ww xY w|                     |           |                                 dS dS )u  Poll for the planned-stop marker and trigger graceful shutdown.

    On Windows, ``asyncio.add_signal_handler`` raises NotImplementedError
    for SIGTERM/SIGINT, so the standard signal-driven shutdown path
    never runs when ``hermes gateway stop`` signals the gateway. The
    consequence is that the drain loop is skipped — in-flight agent
    sessions are killed mid-turn and ``resume_pending`` is never set,
    so the next gateway boot has no idea those sessions need to be
    auto-resumed (issue #33778, v0.13.0 session-resume feature broken
    on native Windows).

    This watcher runs on every platform (cheap, defensive) and bridges
    the gap on Windows by translating a filesystem marker into the
    same shutdown-handler invocation a real SIGTERM would have produced
    on POSIX. The CLI's ``hermes_cli.gateway_windows.stop()`` writes
    the marker via ``write_planned_stop_marker(pid)`` and then waits
    for the gateway PID to exit; this watcher is what makes that
    exit happen cleanly.

    On POSIX this is a no-op safety net — the signal handler always
    races us to consuming the marker file because it fires synchronously
    from the kernel's signal delivery.

    Args:
        stop_event: cleared by start_gateway() during normal shutdown
            to tell the watcher to exit.
        runner: the GatewayRunner instance; we check ``_running`` and
            ``_draining`` to avoid triggering shutdown if the gateway
            is already in one of those states.
        loop: the asyncio event loop the shutdown handler must run on.
        shutdown_handler: same callable that's wired to SIGTERM —
            tolerates a ``None`` signal argument (planned stop case)
            and consumes the marker via
            ``consume_planned_stop_marker_for_self()``.
        poll_interval: seconds between marker checks. 0.5s gives a
            responsive shutdown without burning CPU.
    r   )_get_planned_stop_marker_path planned_stop_marker_targets_selfr  Frf  Nz#Planned-stop watcher tick error: %s)r 	  r  r  r  rw   r-   r  call_soon_threadsafer.   r/   r0   )	r  r  r   shutdown_handlerr  r  r  r   r  s	            r6   _run_planned_stop_watcherr  d  s^   Z        0/11K!! $'"	D""$$U;; FJ66, 8799 OOM222
 ))*:DAAA 	D 	D 	DLL>CCCCCCCC	D&&&I !! $' $' $' $' $'s   AB >B 
C!CCr  r  c           	         ddl m}m}m}m}m} ddlm}	 d}
d}d}d}d}d}d|fd|fd	|fd
|fd|ff}t          	                    d|           d}| 
                                s|dz  }||z  dk    rw|ru	 ddlm} |9t           ||          |t          d          }||                    d           n2# t          $ r%}t                              d|           Y d}~nd}~ww xY w||
z  dk    rf|D ]c\  }}	  |d          }|rt          	                    d||           1# t          $ r&}t                              d||           Y d}~\d}~ww xY w||z  dk    r_	  |	            \  }}|rt          	                    d||           n2# t          $ r%}t                              d|           Y d}~nd}~ww xY w||z  dk    r	 ddlm}  |t'          d          d            n2# t          $ r%}t                              d|           Y d}~nd}~ww xY w	 ddlm}  |             n2# t          $ r%}t                              d |           Y d}~nd}~ww xY w	 dd!lm}  |             n2# t          $ r%}t                              d"|           Y d}~nd}~ww xY w||z  dk    r	 dd#lm} dd$lm}  |                                d%          pi }|                    d&d'          r |            } 	 |                     t'          |                    d(d)                    t;          |                    d*d                    +           |                                  n# |                                  w xY wn2# t          $ r%}t                              d,|           Y d}~nd}~ww xY w||z  dk    rY	 dd-lm }!  |!d./           nE# t          $ r8}"t                              d0tC          |"          j"        |"           Y d}"~"nd}"~"ww xY w| #                    |           | 
                                t          	                    d1           dS )2u  Background thread for gateway-only periodic chores (NOT cron).

    Split out of the historical ``_start_cron_ticker`` so the cron *trigger*
    can live behind the ``CronScheduler`` provider (built-in or external) while
    these gateway-specific chores keep running independently of which provider
    fires cron. An external scale-to-zero provider has no 60s loop at all, but
    this housekeeping still wants its hourly cadence — so it owns its own loop.

    Refreshes the channel directory every 5 minutes and prunes the
    image/audio/video/document/screenshot caches + expired ``hermes debug
    share`` pastes once per hour, and polls the curator hourly (its inner
    gate enforces the real weekly cadence).
    r   )cleanup_audio_cachecleanup_document_cachecleanup_image_cachecleanup_screenshot_cachecleanup_video_cache)_sweep_expired_pastesr  r{  rk   ImageDocumentAudioVideo
Screenshotz+Gateway housekeeping started (interval=%ds)r  Nz*Channel directory refresh scheduling errorrw  r  r  z#Channel directory refresh error: %sr  )max_age_hoursz*%s cache cleanup: removed %d stale file(s)z%s cache cleanup error: %sz4Paste sweep: deleted %d expired paste(s), %d pendingzPaste sweep error: %s)maybe_run_curatorr	  c                 8    t                               d|           S )Nzcurator: %sr  )r|  s    r6   r   z-_start_gateway_housekeeping.<locals>.<lambda>ce  s    6;;}c+J+J rB   )idle_for_seconds
on_summaryzCurator tick error: %s)maybe_pull_skillszSync pull tick error: %s)maybe_pull_org_skillszOrg sync pull tick error: %sr7  )r>  rb  r?  Fr@  r  rA  rB  zAuto-archive tick error: %s)trim_memoryzmessaging gateway housekeepingr6  z/gateway housekeeping memory trim failed: %s: %szGateway housekeeping stopped)$r  r  r  r  r  r  hermes_cli.debugr  r/   r  r  r]  r   r   r  r.   r0   agent.curatorr  rG  tools.skills_sync_clientr  r  rg  r8  r  r>  rT   r  rF  r.
  hermes_cli.mem_trimr  r   r   r  )#r  r{  r   r  r  r  r  r  r  r  IMAGE_CACHE_EVERYCHANNEL_DIR_EVERYPASTE_SWEEP_EVERYCURATOR_EVERYAUTO_ARCHIVE_EVERYMEMORY_TRIM_EVERYMEDIA_CACHE_CLEANUPS
tick_countr   r  rs  
cache_name
cleanup_fnr  deleted	remainingr  r  r  r  r>  r  _adbr  r5   s#                                      r6   _start_gateway_housekeepingr1  e  s                 766666M
 
%&	+,	%&	%&	/0 KK=xHHHJ!! r*a
))Q..8.GMMMMMM#
 3//994%$P  C
 

2
... G G GBAFFFFFFFFG ))Q..*> N N&
JN(jr:::G g$PR\^efff  N N NLL!=z1MMMMMMMMN ))Q..9%:%:%<%<" KKN    9 9 94a888888889 %**:;;;;;;!!%*5\\JJ      : : :5q99999999:<FFFFFF!!#### < < <7;;;;;;;;<
@JJJJJJ%%'''' @ @ @;Q????????@ **a//?NNNNNN222222..0044Z@@FB	==77 %$9;;D%//&+IMM:Mq,Q,Q&R&R/29==AUWY3Z3Z/[/[ 0   
 



 ? ? ?:A>>>>>>>>? ))Q..;;;;;;#CDDDDD 	 	 	
 EII&       	 	)))e !! r*f KK./////s   5AB7 7
C&C!!C&:*D%%
E/EE"+F 
F=F88F=
!G, ,
H6HHH0 0
I:II#I4 4
J#>JJ#1AN =AM+ N +NN 
N4N//N4O 
P.PPc                 T    ddl m}  |                                | |||           dS )u  DEPRECATED shim — preserved for backward compatibility.

    The cron trigger now lives behind the ``CronScheduler`` provider
    (``cron.scheduler_provider``); the gateway resolves a provider and runs its
    ``start()`` directly (see ``start_gateway``). This shim runs ONLY the
    built-in in-process tick loop, exactly as before, for any external caller
    or test that still references this symbol (e.g. hermes_cli/debug.py). It no
    longer runs gateway housekeeping — that moved to
    ``_start_gateway_housekeeping``.
    r   )InProcessCronScheduler)r{  r   r  N)cron.scheduler_providerr3  rr  )r  r{  r   r  r3  s        r6   _start_cron_tickerr5  e  sC     ?>>>>>"":tV^"_____rB   g     @P@g     A@r	  r  pollc                   K   | dS t          j                                                    t          d|          z   }|                                 rt          j                                                    |k     rWt          j        |           d{V  |                                 r)t          j                                                    |k     W|                                  S )u  Wait for a daemon thread to exit WITHOUT blocking the event loop.

    A synchronous ``thread.join()`` here would freeze the event loop — fatal
    for the cron ticker, whose in-flight delivery is a coroutine scheduled onto
    *this* loop via ``safe_schedule_threadsafe``. Blocking the loop deadlocks
    that delivery (the loop can never run it), so ``join(timeout=5)`` always
    times out and the message is silently dropped on restart (#58818).

    Polling ``is_alive()`` with ``await asyncio.sleep`` keeps the loop running
    so the pending delivery completes, then the ticker sees ``stop_event`` and
    exits. Returns True if the thread exited within ``timeout``.
    NTr  )r  r	  r,   r  r
  r`  )r  r  r6  r	  s       r6   _await_thread_exitr8  e  s       ~t'))..003sG3D3DDH
//

 " 8 : : ? ? A AH L LmD!!!!!!!!! //

 " 8 : : ? ? A AH L L    rB   r  c                     t          | dd          }|dS d| _        	 |                                 dS # t          $ r  t                              dd           Y dS w xY w)z9Idempotently drain and detach Gateway Health OTLP export.rD  Nz*gateway health OTLP export shutdown failedTr   )r-   rD  r  r.   r/   r0   )r  r  s     r6   rH  rH  e  s    f>EEG,0F)R R R RADQQQQQQRs   4 &AArJ  	verbosityc                 h  @AK   ddl m}  |             ddlm}m}m}m}m}m}	  |            }
|
P|
t          j
                    k    r8|r ||
          }t                              d|
           	 ddlm}  ||
           n2# t          $ r%}t                              d|           Y d}~nd}~ww xY w	 ddlm}  ||
          }n# t          $ r g }Y nw xY w	  |	|
d	
           n`# t"          $ r Y nTt$          t&          f$ rA t                              d|
           	 ddlm}  |             n# t          $ r Y nw xY wY d	S w xY wddlm} d	}t/          d          D ]%} ||
          sd} nt1          j        d           &t                              d|
           	  |	|
d
           n$# t"          $ r d}Y nt$          t&          f$ r Y nw xY w|s5t/          d          D ]%} ||
          sd} nt1          j        d           &|s?t                              d|
           	 ddlm}  |             n# t          $ r Y nw xY wd	S 	 ddlm}  |||
           n-# t          $ r  t                              d|
d           Y nw xY w |             	 t9                      dz                      d           n# t          $ r Y nw xY w	 ddlm}  |             n# t          $ r Y nw xY w	 ddlm}  ||
|          }|rt                              d|           n\# t          $ r Y nPw xY wt?          t9                                }t                              d|
|           tA          d|
 d           d	S 	 dd l!m"}  |d!           n# t          $ r Y nw xY wdd"l#m$}m%}  |tL          d#$           	 dd%l'm(} d}	 dd&l)m*}  |            }n# t          $ r d}Y nw xY w |tL          |'           n2# t          $ r%}t                              d(|           Y d}~nd}~ww xY w|dd)l+m,} tZ          j.        tZ          j/        d*0                    |tZ          j1                  } t[          j2         |                      }!|!3                    |            |!4                     |d+                     t[          j5                    6                    |!           | t[          j5                    j7        k     r&t[          j5                    3                    |            tq          |           Ats          |          A_:        d	@dX@Afd,	}"Afd-}#tw          j<                    }$|$=                    t|                     t          j@                    t          jA                    u rt          jC        t          jD        fD ]*}%	 |$E                    |%|"|%           # t          $ r Y 'w xY wt          t          d.          r2	 |$E                    t          jH        |#           n+# t          $ r Y nw xY wnt                              d/           t          jI                    }&t          jJ        t          |&A|$|"fdd01          }'|'L                                 ddlM}(dd2lmN})m}m}  |            }*|*4|*t          j
                    k    rt                              d3|*           d	S  |            st                              d4           d	S 	  |)             n5# t          $ r(  |             t                              d5           Y d	S w xY w|(P                    |           |(P                    |           	 dd6lQmR}+  |+             n2# t          $ r%},t                              d7|,           Y d},~,nd},~,ww xY w	 dd8lSmT}-  |-             n2# t          $ r%}.t                              d9|.           Y d}.~.nd}.~.ww xY wt                       	 dd:lVmW}/ tw          j<                    }0|0X                    d|/           d{V  n2# t          $ r%}t                              d;|           Y d}~nd}~ww xY w	 AL                                 d{V }1n# t          $ r t          A            w xY w|1st          A           d	S 	 dd<l[m\}2  |2            }3|3rt                              d=|3           n# t          $ r Y nw xY wAj]        rSt          A           Aj^        r t                              d>Aj^                   Aj_        t          Aj_                  dS Aja        s	 Ab                                 d{V  Ajc        r9Aj^        r t                              d?Aj^                   	 t          A           d	S 	 dd@lVmd}4  |4             n# t          $ r Y nw xY wAj_        t          Aj_                  	 t          A           dS # t          A           w xY wddAlemf}5mg}6 t          jI                    }7 |6            }8Ajh        tw          j<                    dB}9t          |8|5          rt          Ajk        dCd	          r	 ddDllmm}: t           |:dE                    };|;r8|;|9dF<   t                              dGt          |;          dH |;D                        n2# t          $ r%}.t                              dI|.           Y d}.~.nd}.~.ww xY wt          |8|5          rAfdJ|9dK<   t          jJ        |8jL        |7f|9ddLM          }<|<L                                 t          jJ        t          |7fAjh        tw          j<                    dBddNM          }=|=L                                 t          AdOd          }>t          |>          r
 |>             Ab                                 d{V  	 ddPlSmr}?  |?             n# t          $ r Y nw xY wAjc        r)Aj^        r t                              d?Aj^                   d	S |7s                                 	 |8t                                 n2# t          $ r%}t                              dQ|           Y d}~nd}~ww xY wt          |<t          R           d{V s t                              dSt                     t          |=t          R           d{V  |&s                                 |'x                    dTR           	 dd@lVmd}4  |4             n# t          $ r Y nw xY wAj_        t          Aj_                  @r#Ajy        st                              dU           d	S Ajz        r)t                              dV           t          dW          dS )Ya7  
    Start the gateway and run until interrupted.
    
    This is the main entry point for running the gateway.
    Returns True if the gateway ran successfully, False if it failed to start.
    A False return causes a non-zero exit code so systemd can auto-restart.
    
    Args:
        config: Optional gateway configuration override.
        replace: If True, kill any existing gateway instance before starting.
                 Useful for systemd services to avoid restart-loop deadlocks
                 when the previous process hasn't fully exited yet.
    r   )record_boot_fingerprint)acquire_gateway_runtime_lockget_running_pidget_process_start_timer@  r?  terminate_pidNz<Replacing existing gateway instance (PID %d) with --replace.)write_takeover_markerz#Could not write takeover marker: %s)_snapshot_gateway_childrenFr   z1Permission denied killing PID %d. Cannot replace.)clear_takeover_marker)_pid_existsrI  Tr  zAOld gateway (PID %d) did not exit after SIGTERM, sending SIGKILL.g      ?zjOld gateway (PID %d) still appears alive after SIGKILL; aborting replacement to avoid a duplicate gateway.)reap_gateway_children)
parent_pidz-Child reap for replaced gateway PID %d failedr   zgateway.pidrB  )release_all_scoped_locks)	owner_pidowner_start_timez2Released %d stale scoped lock(s) from old gateway.zAnother gateway instance is already running (PID %d, HERMES_HOME=%s). Use 'hermes gateway restart' to replace it, or 'hermes gateway stop' first.u"   
❌ Gateway already running (PID z).
   Use 'hermes gateway restart' to replace it,
   or 'hermes gateway stop' to kill it first.
   Or use 'hermes gateway run --replace' to auto-replace.
)sync_skills)quiet)setup_logging_safe_stderrr1   )rO  r:  )log_startup_security_warnings)rH  )rO  rX   z-Startup security audit failed (non-fatal): %sr"  )r   rk   z#%(levelname)s %(name)s: %(message)sc                    d}	 ddl m}  |            }n2# t          $ r%}t                              d|           Y d }~nd }~ww xY wd}| t
          j        k    rd}nF|sD	 ddl m}  |            }n2# t          $ r%}t                              d|           Y d }~nd }~ww xY w	 ddlm	}m
}m}  ||           }	n4# t          $ r'}
d }	t                              d	|
           Y d }
~
nd }
~
ww xY w|r&t                              d
|	r|	d         nd           nV|r&t                              d|	r|	d         nd           n.dd_        t                              d|	r|	d         nd           |		 t                              d ||	                     n2# t          $ r%}
t                              d|
           Y d }
~
nd }
~
ww xY w	 t          dz  dz  } |||	d         d           n2# t          $ r%}
t                              d|
           Y d }
~
nd }
~
ww xY wt!          j                                                   d S )NFr   ) consume_takeover_marker_for_selfz Takeover marker check failed: %sT)$consume_planned_stop_marker_for_selfz$Planned stop marker check failed: %s)format_context_for_logsnapshot_shutdown_contextspawn_async_diagnosticz$snapshot_shutdown_context failed: %su?   Received %s as a planned --replace takeover — exiting cleanlyrA  SIGTERMu9   Received %s as a planned gateway stop — exiting cleanlyzSIGTERM/SIGINTu#   Received %s — initiating shutdownzShutdown context: %sz!format_context_for_log failed: %sr
  zgateway-shutdown-diag.logr#   )r  z!spawn_async_diagnostic failed: %s)r 	  rP  r.   r/   r0   rA  SIGINTrQ  rB  rR  rS  rT  r  rl  r   r;  r  ri  rq  )received_signalplanned_takeoverrP  rs  planned_stoprQ  rR  rS  rT  _shutdown_ctxr  	_diag_logrl  r  s               r6   shutdown_signal_handlerz.start_gateway.<locals>.shutdown_signal_handlerf  s    !	@GGGGGG??AA 	@ 	@ 	@LL;Q????????	@ fm++LL! 	HHOOOOOOCCEE H H HCQGGGGGGGGH		E         
 65oFFMM 	E 	E 	E MLL?DDDDDDDD	E  	KKQ+8Gh''i     	KKK+8Nh''>N   
 *.& 15F-KK5+8Nh''>N   $F*,B,B=,Q,Q     F F F@"EEEEEEEEFF(614OO	&&}X6      F F F@"EEEEEEEEFFKKMM*****st    
AA  A A1 1
B ;BB $B: :
C+C&&C+/$F 
GF>>G!G) )
H3HHc                  6                          dd           d S )NFTr
  )r
  r  s   r6   restart_signal_handlerz-start_gateway.<locals>.restart_signal_handler>g  s"    4@@@@@rB   SIGUSR1z6Skipping signal handlers (not running in main thread).zplanned-stop-watcherr  )write_pid_filer?  r>  z^Another gateway instance (PID %d) started during our startup. Exiting to avoid double-running.zBGateway runtime lock is already held by another instance. Exiting.z8PID file race lost to another gateway instance. Exiting.)record_startupz*Lifecycle ledger startup record failed: %s)start_nous_auth_keepalivez%Nous auth keepalive did not start: %s)r!  zMCP tool discovery failed: %s)recover_pending_to_dbz3Recovered %d pending message(s) from shutdown flushzGateway exiting cleanly: %sz Gateway exiting with failure: %s)r   )r3  resolve_cron_scheduler)r{  r   r  )r\  r]  profile_homesz:Cron scheduler will tick %d profile(s) under multiplex: %sc                 L    g | ]!}t          |t                    r|d          n|"S )r   )rR   ra  r  s     r6   r  z!start_gateway.<locals>.<listcomp>h  s/    PPPQZ5118QqTTqPPPrB   z6Could not resolve profile homes for multiplex cron: %sc                  "     j         p j         S r;   )r  r  r^  s   r6   r   zstart_gateway.<locals>.<lambda>h  s    = =5
 rB   can_dispatchzcron-scheduler)r  r  r  r  r   zgateway-housekeepingr  )stop_nous_auth_keepalivezCron provider stop() error: %sr  ub   Cron ticker did not exit within %.0fs of shutdown — an in-flight delivery may have been dropped.r  z}Exiting with code 1 (signal-initiated shutdown without restart request) so systemd Restart=on-failure can revive the gateway.z_Exiting with code 75 (service-restart requested) so the service manager relaunches the gateway.K   r;   ){gateway.code_skewr<  r 	  r=  r>  r?  r@  r?  r@  rq   rT
  r/   r  rA  r.   r0   rB  ProcessLookupErrorPermissionErrorru   r  rC  rD  r  r,   r`  r   rE  rG  rD  rG  rU   printtools.skills_syncrJ  hermes_loggingrL  rM  r;  !hermes_cli.security_audit_startuprN  rg  rH  r   r#  r"  WARNINGr)  rT   DEBUGStreamHandlerr(  r'  r#  r+  levelr  r   r*  r  r	  set_exception_handlerr   ro  current_threadmain_threadrA  rV  rU  add_signal_handlerNotImplementedErrorr   r`  r  rp  r  rr  atexitra  FileExistsErrorr  gateway.lifecycle_ledgerrb  hermes_cli.nous_auth_keepaliverc  r   r&  r!  r  r  rH  r
  rd  r  r  r  
SystemExitrf  rZ  r	  r   r4  r3  re  r{  rR   r-   rX   r  r\  r  r   r1  r  rj  rt   rq  r8  _CRON_SHUTDOWN_DRAIN_TIMEOUT$_HOUSEKEEPING_SHUTDOWN_DRAIN_TIMEOUTrD   r  r   )BrX   rJ  r:  r<  r=  r>  r?  r@  r?  r@  existing_pidexisting_start_timerA  rs  rB  _old_gateway_childrenrC  rD  old_gateway_exitedr  rE  rG  	_releasedrO  rJ  rL  rM  rN  
_audit_cfgrH  
_audit_excr#  _stderr_level_stderr_handlerr\  r_  r   sig_planned_stop_watcher_stop_planned_stop_watcher_threadr|  ra  _current_pid_lifecycle_record_startup_lc_excrc  r5   r!  _loopr  rd  r:  r   r3  re  	cron_stopcron_providercron_start_kwargsr\  rf  cron_threadhousekeeping_threadstart_watchdogrj  rl  r  sB                                                                   @@r6   start_gatewayr  e  s     $ :99999                #?$$LLBIKK$?$? Q	"8"8"F"FKKN  G@@@@@@%%l3333 G G GBAFFFFFFFFG+EEEEEE(B(B<(P(P%% + + +(*%%%+l%88888%   #W-   G   DDDDDD))++++    Duu  322222!&2YY (! (!"{<00 )-&E
3 W   !M,d;;;;;) . . .)-&&&'1   D * )"2YY ) )*{<88 "15.!E
4(((() !LLM$  
HHHHHH--////$    5

@@@@@@%%)l        C !       O ""]2::d:KKKK   @@@@@@%%''''   
	CCCCCC44*%8  	  aKK TV_```    o//00KLL^k  
 Ol O O O   5111111$    ;:::::::Ml;;;;RSSSSSS
	999999(**JJ 	 	 	JJJ	%%,zRRRRR R R RDjQQQQQQQQR 333333#O==AA)W][[!/??  ///$$%7%78]%^%^___&&7777,..444((7776""F /37mmF+ "']+ ]+ ]+ ]+ ]+ ]+ ]+~A A A A A #%%D 	>???!!Y%:%<%<<<M6>2 	 	C''-DcJJJJ&   69%% 	''8NOOOO&   	 	LMMM "+!2!2#,#3((&$8OP#	$ $ $  !&&((( MMMOOOOOOOOOO"?$$LLBIKK$?$?/0<	
 	
 	
 u'')) P	
 	
 	
 u   $$&&&F	
 	
 	
 uu OOO$$$
OO0111LXXXXXX!!#### L L LA7KKKKKKKKLCLLLLLL!!#### C C C<cBBBBBBBBC )***9555555(**##D*<========== 9 9 94a888888889&&&&&&   '///  '///u@@@@@@))++	 	KKEy      ! '/// 	LLL68JKKK 'V-...t? 4	4**,,,,,,,,,. % YLL!CVEWXXX ,F33333??????$$&&&&   + !1222+F33333+F3333 WVVVVVVV!!I**,,M5;_gNfNhNh(i(i 	="899FM#7??	====== !2!2T!B!B!BCCM 5B!/2P&&PP-PPP  
  	 	 	NNH       	 -!788 
-
 -
 -
 -
.) ""\   K 
 $**\"OW5M5O5OPP#   
 V%>EEN  
"
"
$
$$$$$$$$KKKKKK  """"    &  	QLL;V=OPPPu MMOOO: : : :5q99999999:#K9UVVVVVVVVV 
./K	
 	
 	
 %I         
 ""$$$ %%a%000777777    #)*** " &*C M	
 	
 	
 u " .	
 	
 	
 nn4sH  4B 
B5B00B59C CCC, ,
E	8+E	$D54E	5
E?E	EE	E	%F3 3GGG,H= =
I
	I
I$ $'JJ%K 
KKK$ $
K10K150L& &
L32L3N 
N#"N#P  
O P  O*'P  )O**P   
P/
P**P/W
W,+W, X& &
X32X3
\ .]
]9^
 

^9^44^9=_ 
_=_88_=5a 
a4a//a48b b.-c3 3
d ?d %Ah  g h 
gh gh h	Ak# #
l-ll1p 
ppq, ,
r6rr!t2 2
t?>t?c                     	 ddl m}   |              n# t          $ r Y nw xY wddl}|                    d          }|                    ddd	           |                    d
ddd           |                                }d}|j        r]ddl}t          |j        d          5 }|
                    |          pi }t          j        |          }ddd           n# 1 swxY w Y   	 t          j        t          |                    }|rdnd}	nE# t           $ r8}
|
j        d}	n$t%          |
j        t&                    r|
j        }	nd}	Y d}
~
nd}
~
ww xY wt)          |	           dS )z CLI entry point for the gateway.r   )configure_windows_stdioNz)Hermes Gateway - Multi-platform messaging)r   z--configrH
  zPath to gateway config file)r  z	--verboser  
store_truezVerbose output)r
  r  r  rJ  rk   )hermes_cli.stdior  r.   argparseArgumentParseradd_argument
parse_argsrX   rL  ra  rM  r  rU  r  rq
  r  r  r  rR   rF  _exit_after_graceful_shutdown)r  r  parserr  rX   rL  rP  r  r  r  rs  s              r6   r|  r|  h  s   <<<<<<!!!!    OOO$$1\$]]F

D/LMMM
T,EUVVVDF{ 3$+000 	3A>>!$$*D",T22F	3 	3 	3 	3 	3 	3 	3 	3 	3 	3 	3 	3 	3 	3 	3$
+mF3344 'AAa		   6>II$$ 	III "),,,,,s6    
  %,CC!$C!)'D 
E.EEr  c                    t           j        t           j        fD ]'}	 |                                 # t          $ r Y $w xY w	 ddlm}m}  |              |             n# t          $ r Y nw xY w	 ddlm	}  || d           n# t          $ r Y nw xY w	 ddl
m}  |d           n# t          $ r Y nw xY wt          j        |            d	S )
u  Flush stdio, release the PID file + runtime lock, then hard-exit.

    Graceful teardown is already complete by the time this runs, so there is
    nothing left that needs a clean interpreter shutdown. We deliberately use
    ``os._exit`` (not ``sys.exit``): ``sys.exit`` raises ``SystemExit``, which
    triggers ``Py_FinalizeEx`` → ``wait_for_thread_shutdown`` and joins every
    non-daemon thread — exactly the hang (#53107) a wedged tool-worker causes.

    ``os._exit`` bypasses ``atexit`` handlers, so we cannot rely on the
    ``atexit``-registered ``remove_pid_file`` / ``release_gateway_runtime_lock``
    (registered in ``start_gateway``) to run. The full-shutdown path releases
    both explicitly in ``_stop_impl``, but the EARLY exit paths —
    clean-fatal-config (#51228) and startup-aborted-before-running — raise
    ``SystemExit`` right after ``runner.start()`` without going through
    ``_stop_impl``, so on those paths ``atexit`` was the only thing releasing
    them. Now that those paths are routed through this backstop (#53107),
    release both here explicitly. Both calls are idempotent —
    ``remove_pid_file`` only unlinks a PID file that belongs to this process,
    and ``release_gateway_runtime_lock`` no-ops when the lock is already
    released — so this is a no-op on the normal shutdown path and the actual
    cleanup on the early-exit paths.

    Logging IS drained here: the rotating file handlers are driven by an
    async ``QueueListener`` on a dedicated thread (see
    ``hermes_logging._register_queued_handler``), so records emitted right
    before shutdown may still be sitting in the in-memory queue. ``os._exit``
    below bypasses ``atexit``, so the ``atexit``-registered listener drain
    never runs on this path — we drain explicitly (bounded, via
    ``drain_log_queue``) or lose the last log lines (including the shutdown
    reason on the early-exit paths). Stdio is flushed too.
    r   r>  )mark_exitedgraceful_shutdownr6  )drain_log_queuer	  r  N)rm   r  r  r-  r.   r 	  r?  r@  r~  r  rq  r  rq   _exit)r  r  r?  r@  r  r  s         r6   r  r  h  sa   @ :sz*  	LLNNNN 	 	 	D	PPPPPPPP$$&&&&   888888I&9:::::   222222$$$$$   HYsB   1
>>A 
A,+A,0B 
BBB( (
B54B5__main__rX  r;   r  rU  )r   N)rX  r   r'   N)r}  r   )r'   r  )r'   r  )r  r  r'   N)NNr  )r	  )NFr   (  rz  hermes_bootstrapr  r  concurrent.futuresr  r>  r>  r/  r  r"  rq   rd  r<   r'	  rz   rm   rA  ro  r,   collectionsr   contextvarsr   r  r   r   typingr   r	   r
   r   r   r   r   r   r   agent.async_utilsr   r   r  r   r   r   r   r   r   r   r   agent.conversation_loopr   
agent.i18nr   agent.interrupt_compatr   rg  r   r  r   r  r  r  r  r  r  r  compiler@  r  
IGNORECASEDOTALLr  rU   rG  r7   rF   rD   r  r   rZ   rd  rb   rd   _GATEWAY_PROVIDER_ERROR_REr   r   r   r   r   ra   r   r   r  r   r   r   r   r   r   r   r   r   r  r	  r  r  rS   r&  rt   r5  rA  rd  rT  rL  rQ  rW  rY  r`  rg  rs  rz  ra  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  agent.replay_cleanupr  r  r  r  r  r  r  r  r  rF  r  r  r-  r5  r8  r<  r>  r@  rE  rr   rx   ry   rn   rp   r  rG  rH  utilsrI  rJ  r;  dotenvrK  r  rL  	_env_pathro   rV  rW  rU  rq  
contextlibrr  _contextmanagerr  rs  _PORT_BINDING_PLATFORM_VALUESrt  rl  r  rv  r|  r  r  r  r  r  _config_pathrw   r\  r]  r  rR   rh  r_  ri  r.   r  rD  _valrT   _terminal_cfgrV   rW   _terminal_backend_terminal_env_map_cfg_key_env_varr#  r  r	  r  r  _auxiliary_cfg_aux_bridged_keysrH  r  rR  rv   	_task_key	_task_cfg_prov_model	_base_urlrD  r3  _upper
_agent_cfg_sessions_cfgr  _tz_cfg_security_cfg_redact_gateway_cfg_strict_allow_dirs_allow_dirs_strr}   _trust_recent_trust_recent_seconds_bridge_errro  r   r   r  r  dir_network_cfg_bootstrap_excr  r  gateway.cwd_placeholderr  r  _configured_cwdr  rX  _resolved_cwdr$  r  r  r   r  r  r!  r  rP  r"  r#  r$  r%  r&  r'  r(  r)  r*  r+  r,  gateway.deliveryr-  r.  r/  gateway.turn_leaser0  gateway.session_stater1  r4	  r2  r3  r4  gateway.authz_mixinr5  gateway.kanban_watchersr6  gateway.slash_commandsr7  gateway.turn_contextr8  r  r  r9  r:  r;  r<  r=  r>  r?  r@  gateway.shutdown_watchdogrA  rB  rC  rD  rE  rF  gateway.restartrG  rH  rI  rJ  rK  rL  gateway.whatsapp_identityrM  _canonical_whatsapp_identifierrN  _expand_whatsapp_auth_aliasesrO  _normalize_whatsapp_identifierr#  r/   r   r  r  r  r  rc  rj  r  ri  rt  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r!  r$  r   _INTERRUPT_REASON_SSE_DISCONNECTrE  rD  r  r  r  r  r  r  r  r&  r9  r=  rB  rE  rQ   r]  r  rb  ri  rn  ry  r  r  r  weakrefrS  r  rT  r  r  r  r  r  r  r  r  r  r  r  r1  r5  r  r  rp  r8  rH  r  r|  r  r,  rB   r6   <module>r     s-    "	 	 	 	
 	D	                 				  				   



       # # # # # # $ $ $ $ $ $             U U U U U U U U U U U U U U U U U U U U U U T T T T T T T T	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 G F F F F F       9 9 9 9 9 9 % % % % % % 9 9 9 9 9 9  # )- & */ &+. ( &* "&6 #)rz*TUU - &BJ	> MBIA! ! HI# I ISW I I I I,
= 
= 
= 
= 
= 
=, #-"*HH   /1+764=	
     M# # $t    : (i999  
Ls Lt L L L L
 (RZ		 M   )bj
	 M   $]M  
 $>M   BJ788BJ122BJ122BJ344BJ)**BJ/00BJ9:: 3 3 3 3lKc Kc K K K K *.
 
 
 
tCH~&
 
 d38n	
 
 
 
$sCx.) 
   0)] )t ) ) ) )X,
%,04S#X,	, , , ,Dc c    :=, =3 = = = =* !   
    	   :     ( $.2:		 M$ $  ?S ?T ? ? ? ?.s # #    4c s S U]^aUb    <:# : : : :
C 
C 
C$ !   
  c]   @	F 	FC 	FRU 	FZ^ 	F 	F 	F 	F" 59$ $ $$$ $
 $ $ $'s8d?$ 
$ $ $ $N< <s <s < < < <L )0 % /3 +S Xe_    D, , , , ,$BU B B B BBS 5 U    
1
1

1 %
1 	
1
 

1 
1 
1 
1   #'	) ) )) 
%) %	)
 
) ) ) )> B 	B B BSMBB 	B
 	B B B BB- %S/     %	? ?
?? 
c3h? 	?
 
#s(^? ? ? ?D ,M (!a  %O !_(3- _D _ _ _ _	CS 	CSX 	C 	C 	C 	C$ $C $ $ $ $*)c )c ) ) ) )Jc JC JD J J J JXd^     . %)#	f+ f+ f+$sCx.!f+ SMf+ 	f+
 4S#X#./f+ f+ f+ f+RDcN+ 
$sCx.   , PXY\P] be    4d38n1E(F 3    :! ! !           @ !> S T         .  N   M  )-N+ N+4S>"N+N+ "#N+ 49d?	N+ N+ N+ N+b=T#s(^0D = = = = =F1 1 1 1f3 3 3 3 3 3> > > > > >
<t < < < <
2D 2 2 2 29t 9 9 9 9
A A A A !$
       33ttH~~,344 5 5 5 G F F F F F F F 4 4 4 4 4 4 4 4         4 4 4 4 4 46!	  |h9O9O9Q9Q9YZ[9\_e9e f f f f0 0 0 0:#V #V #V #VL     9 8 8 8 8 8           <   P P P P P&: P P P !/ !/ !/ !/H       F: HX ]a    ( $$dee (1:'> $ m+ |
{
 	MLLLLLLL##L11%%z$%% 	D	0000006=6t<<DD 	 	 	D	 **,, 	- 	-JD$z$c5$ 788 -T=S=S#&3t99
4  R00 :	9ZZt<< :	9 #!!),,T
~0N0NTRT! !eggeegg !>!~! -! 1	!
 #$?!  7! %&C! $%A! 5!  !9! !";! /! /! /! -!   !9!!" #$?#!$ #<(G";3%A#=1Y";+M3](G5$?=! ! !@ '8&=&=&?&? 9 9"(},,(2D
  5((SSYY:N-N-N   5((ZZc-B-B(PPPPPP778I4::<<XX <#%7#5#5d#;#;D!z$t55 9/9tz$/?/?
8,,/2s4yy
8, +r22 	Ijj>> 	I !F E EIIIIII88:: 9 9F%))&-88889    
 / I I	*..y"==	!z)T22 IMM*b99::@@BBY]]7B7788>>@@C	j" = =>>DDFF	3y}}Y;;<<BBDD"** GUf__AFBJ=F===> E>DBJ:F:::; KAJBJ=F===> I@HBJ<F<<<= XXgr**
 	**Z66 	j((69c*[:Q6R6R
23 J..58SDU9V5W5W
12(J66=@SLeAf=g=g
9:(J66=@SLeAf=g=g
9:&*44=@S67> >
9: '*44=@SLcAd=e=e
9:0J>>?Bs@A@ @
;< 7*DDEHSFGF F
AB
 R00 	ZZt<< 	M))/2s=3K/L/L
+,=0069c!"237 7
23 xx	2.. 	JJ|T:: 	 L00?Bs<PaCb?c?c
;<<//>Ac,O_B`>a>a
:;!\11@CLQcDd@e@e
<=
 )L88;2:MMFIc !9:G G
BC ((:r** 	<zz'3// 	<,3MMOOBJ()R00:mT** 	K#''(899G"69c'll6H6H6J6J
23xx	2..:lD)) #	"&&x00G""+CC 
9: '**+FGGK L:k3// )&1OOZdE];; )&(joo5W5Wk5W5W5W&W&WOO&(O" L<KBJ89(,,-ABBM((1CCc 
<= %1$4$45Q$R$R!$0BE#F[B\B\
>? +l::
'PRTUU[[]] ; IL !;<I I
DE  
 
 
 	;tK  ); ;-8; ;	
 	
 	
 	

 	L	
 	
 	
 	
 	
 	
 	
 	
 	

(_666666"cceeOODD88BGGLz,%% *,*:*:<*H*H *D)))) _ _ _	E
LN
L
LSVS]^^^^^^^^^_U777777 U U U	E
B.
B
BTTTTTTTTTUU>>>>>>  """" U U U	E
B.
B
BTTTTTTTTTU !
>  !$
  W V V V V V V V*..44 3/-===44&;;bi00&/bi4g'
 '

%'''  c)$)++&&	 	 	M 

~t,,,,%2
>"                                                   
 8 7 7 7 7 7            : 9 9 9 9 9 > > > > > > < < < < < < , , , , , ,
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
                                        
	8	$	$ NVOZ^N6b (3-    J !&(( 2% E   $ 
Dt D D D DN     ,HSM    "-t - - - -`Bs Bs B B B BE E E E E EZ Z Z Z Z ZC D    E E E E E Es    ,s  C TW    6#e # # # # #'c 'hsm ' ' ' 'T4 49L 4 4 4 4 * 3 > #<  %< "$8 ! 6:D D DD 	D
 xD12D 	D D D D^ 6:$ $ $ $
 $ ?$ .$ xD12$ 
$ $ $ $` 59" " " "
 " " ?" ." " xD12" 
" " " "J (i$$&&%%''!''))(..00*0022)//11	 	 58C= 5T 5 5 5 504 0E#*cDj:P4Q 0 0 0 0f=3 =3: = = = =@C: C# C C C C
F F F F Fd    ;d ; ; ; ;|TD[ T    ::d : : : :( 4$; #    &  $#	   } }	
 
#Y   :  $#   
 } } o   :Xd3i0    6C M    4d |    @   >    $0L X\ 0 0 0 	R R RRR 	R
 	R R R Rj>t > > > > >0$ 4    ( 
   @3
 3
 3
 3
p  B B B B B B
e 
 e 
 e 
 e 
 e 
 e 
 e 
 e 
RAbz bz bz bz bz-/IKd bz bz bzVu	 V' V' V'V' 
#V' V' 
V' V' V' V'r]0 ]0IO ]0ad ]0 ]0 ]0 ]0@` `9? `X[ ` ` ` `(  $  (, $ GJ! !Y%&!16!>C!	! ! ! !.	RC 	RD 	R 	R 	R 	RR
 R
 7 R
 R
bjknbo R
x| R
 R
 R
 R
j2- 2- 2-jDS DT D D D DN zDFFFFF s   
 +,{ [/ .{ /[74{ 6[77H{ =0d. -{ .d63{ 5d66V{ |	=||A}4 4~ :~~ $~9 9%?%)> >A@*@A@#@#A@*