
    .cj                    2+   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# ddl$m%Z%m&Z& dd	l'm(Z(m)Z) dd
l*m+Z+m,Z,m-Z-m.Z.m/Z/m0Z0m1Z1m2Z2 ddl3m4Z4 ddl5m6Z6 ddl7m8Z8 ddl9m:Z: dZ;dZ<dZ=dZ>dZ? ej@        d          ZA ej@        dejB        ejC        z            ZDdeEdeEfdZF ej@        dG                    d e+e1e2e0e/e-e.e,fD                       ejB                  ZHdeIfdZJ eKh d          ZLde deIfdZM ej@        dejB                  ZN ej@        d ejB                  ZO ej@        d!ejB                  ZP ej@        d"ejB                  ZQ ej@        d#           ej@        d$           ej@        d%           ej@        d&           ej@        d'           ej@        d(           ej@        d)          fZRdd*ZSde deEfd+ZT	 ddd,d-eeeEe f                  de deeeEe f                  fd.ZUd/eVdeIfd0ZWd1d2d3eeEe f         ddfd4ZXd5eEdeEfd6ZYd7d8deEfd9ZZd:d:d;d<d=eEd>eEd?eEd@eIdAeIdBeIdeEfdCZ[d5eEdeEfdDZ\ ej@        dEejB                  Z]d5eEdeIfdFZ^de d5eEdeEfdGZ_de dHeEdIeEdeeE         fdJZ`deEfdKZadL Zbd:dMde dNe dOe dPeIdeeE         f
dQZcdReddSeEdTeEdeIfdUZed;dddVdReddSeEdTeEdWeIde dXefe          dz  deIfdYZgd5eEde deEfdZZhd[Zid\e deej         fd]Zkdejfd^Zld_eEdWejdejfd`Zmdddad\e dbeej         dceej         deIfddZn	 dd:dfdgeeE         dIeEdheIdeEfdiZodjZpeqeEdkf         erdl<   	 ddmeEdne doeeEe f         dpeIdeeEe f         f
dqZsdrZtdsZudtZvdueeE         deIfdvZwdwe defeE         fdxZxdye defeE         fdzZyd{e deEfd|Zzdye d{e deIfd}Z{dReed         deIfd~Z|dd;dde!eeEe f                  dueeE         deIdeqe!eeEe f                  eeE         f         fdZ}de!eeEe f                  de de!eeEe f                  fdZ~dIe deeE         de fdZdee!eeEe f                           de fdZh dZddlmZmZmZmZmZ dZdZdne deIfdZdne de fdZdZ ej@        dejB                  Z	 	 dde!eeEe f                  dedeef         deqe!eE         eIf         fdZde!eeEe f                  deffdZddZdeEdeEfdZdeEdeEfdZdeIfdZdefdZdeIfdZddZde
j        d<    e             ej                            d eE ee          j        j                             ddlmZmZ ddlmZmZmZmZ  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eIfdZ ej@        d          ZddhZedz  ZeŠ                                r8	 ddlZ eed          5 Z ej        eʦ          pi Zddd           n# 1 swxY w Y   ddl7mZ  ee̦          Z	 ddlmZ  ej        e̦          Zn# e$ r Y nw xY we̠                                D ]1\  ZZ eeeEeejeIf          ree
j        vr eEeԦ          e
j        e<   2e̠                    di           Zeאrr eeed          re eEeנ                    dĦ          pe
j                            dŦ          pde                                                                          Zi ddœddǓddɓdd˓dd͓ddϓddѓddӓddՓddדddٓddۓddݓddߓddddddddddddddddddZe۠                                D ]\  ZZeev ree         Zedk    r eEeԦ          dv r%edk    rJ eeeE          r>ddlmZ  eeeԠ                                          se
j                            eԦ          Z eeeedf          r ej        eԦ          e
j        e<    eEeԦ          e
j        e<   e̠                    di           Zer eeed          rh dZ	 ddlmZ  e            D ]Ze                    ed                    n# e$ r Y nw xY weD ]FZe                    ei           Z eeed          s& eEe                    dde                                                    Z eEe                    dde                                                    Z eEe                    dde                                                    Z eEe                    dde                                                    Ze                                Zeredk    ree
j        de d<   eree
j        de d<   eree
j        de d <   eree
j        de d<   He̠                    di           Zer eeed          rdev r eEed                   e
j        d<   dev r eEed                   e
j        d<   dev r eEed                   e
j        d<   d	ev r eEed	                   e
j        d
<   dev r eEed                   e
j        d<   dev r eEed                   e
j        d<   e̠                    di           ZerL eeed          r@dev r eEed                   e
j        d<   dev r eEed                   e
j        d<   e̠                    di           Zer eeed          rdev r eEed                   e
j        d<   dev r eEed                   e
j        d<   dev r eEed                   e
j        d<   dev r%de
j        vr eEed                   e
j        d<   e̠                    dde          Zer) eeeE          re                                e
j        d<   e̠                    di           Z eeed          r>e                    d           Ze& eEe                                          e
j        d!<   e̠                    d"i           Z eeed          r4e                    d#          Zeerdnd$e
j        d%<   e                    d&          ZerR eeeE          reZn6 eeeeqf          r&e
j        G                    d' eD                       ZndeZeree
j        d(<   e                    d)          Zeerdnd$e
j        d*<   e                    d+          Ze eEe          e
j        d,<   d-ev rIe
j                            d.de                                          s eEed-                   e
j        d.<   nS# e$ rKZ ed/ e e          j         d0e ej        1            ed2ej        1           Y dZ[ndZ[ww xY w	 dd3lmZ d4 e            v reni                     d5i           Z eՐeed          r%e                    d6          r ed:7           n0# e$ r(Z ed8e ej        1           Y dZ[n
dZ[ww xY w	 dd9l7mZ  e             n0# e$ r(Z ed:e ej        1           Y dZ[n
dZ[ww xY w	 dd;l7mZ  e             n0# e$ r(Z ed<e ej        1           Y dZ[n
dZ[ww xY wde
j        d=<   de
j        d><   dd?l	m
Z
mZ e
j                            dde          Zeree
v r eee
j                            dde           e
j        d@           e
j        ddA                                          dBv  eE ej                              C          Zee
j                            dd           nee
j        d<   ddDlmZmZmZmZmZmZmZ ddElmZmZmZmZmZmZmZm Z m!Z!m"Z"m#Z# ddFl$m%Z%m&Z& ddGl'm(Z( ddHl)m*Z* ddIl+m,Z, ddJl-m.Z. ddKl/m0Z0m1Z1m2Z2m3Z3m4Z4m5Z5m6Z6m7Z7 ddLl8m9Z9m:Z:m;Z;m<Z< ddMl=m>Z>m?Z?m@Z@mAZA ddNlBmCZDmEZFmGZH  e	jI        e          ZJejK        dOejL        dPejM        dQejN        dRejO        dSiZPdeeE         fdTZQ eR            ZSdUZTeqerdV<    eR            ZUdedfdWZVdeEdedfdXZWdeeE         fdYZXdeddz  fdZZYd[edeEfd\ZZd[edeIfd]Z[d[edeIfd^Z\d[edeIfd_Z]d[edeIfd`Z^deEfdaZ_dbeEdceEddeEdeEfdeZ`dfejdeEfdgZadheEdeeE         fdiZbdjeEde2dz  fdkZcdlZddmZednZfdoZgdpZhdqZi eKed                                ee                                ef                                eg                                eh                                ei                                h          ZjdIeeE         deIfdrZkdsedeqeEdz  eEdz  f         fdtZldueEdeEdz  fdvZmdddeEfdwZndeIfdxZodefdyZpdedfdzZqdyeddz  dedfd{Zrdedfd|Zsddyeddz  deEfd}Ztddd~d{eEdeeE         deeE         deeE         fdZuddd~dyeded{eEdeeE         deeE         dee         fdZvdeeeE                  fdZwdjeEddfdZxdeddd8fdZyddZzddl{Z|d a}e|j~        erd<   dddeddeEdedeEfdZdeddeIfdZdeddeIfdZdeddeddedfdZddZdZdedefdZ G d de*e,e.          Zdddej        d1ej        dejddfdZddej        defdZddej        defdZdZdZ	 ddeej                 dejdejdeIfdZddyee         deIdee         deIfdZd ZdeddfdZe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Unioncast)fetch_account_usagerender_account_usage_lines)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)cfg_get)get_fallback_chain         @      >@      @i   z'(?<![\w:/])/([A-Za-z0-9][A-Za-z0-9_-]*)uC  (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)templatereturnc                 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     -/home/ice/.hermes/hermes-agent/gateway/run.py	<genexpr>z,_status_template_to_regex.<locals>.<genexpr>   s*      <<d")D//<<<<<<    )r)   splitjoin)r$   partss     r.   _status_template_to_regexr4   x   s6     H]H--E>><<e<<<<<<r0   |c              #   4   K   | ]}t          |          V  d S r(   )r4   )r,   	_templates     r.   r/   r/      s>         	"),,     r0   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lower	Exception)configcompression_cfgs     r.   -_gateway_compression_progress_notices_enabledrI      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rN   s    r.    _gateway_surface_passes_raw_textrS      s    "8,,0KKKr0   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)sysrN   r   __file__resolveparentosenvironrB   appendsetOSErrorrC   rE   addexistspathinsertsite
addsitedirremovepathsepr2   rA   fromkeys)project_root
candidatesseenvenv_dirresolved_venvvenv_keysite_packagesproject_entry
site_entry	insert_at
pythonpaths              r.   $_ensure_windows_gateway_venv_importsry      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 )rC   getattrrD   rE   rR   s    r.   rP   rP   /  s9    wx(339r::@@BBHHJJJr0   rR   metadatac                \    t          |          dk    r| S t          | pi           }d|d<   |S )zEMark Discord lifecycle/status sends without changing other platforms.discordTnon_conversational)rP   rA   )r~   rN   mergeds      r.   _non_conversational_metadatar   4  s=     x((I55(.b!!F#'F Mr0   excc                     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   rZ   TF)rc   idre   type__name__	__cause____context__)r   rp   curdepthtransient_class_namesidentnames          r.   _is_transient_network_errorr   A  s     UUD#&CE   /ebjj3D==
Cyy!(((4m.s /ebjj 5r0   loopzasyncio.AbstractEventLoopcontextc           	      B   |                     d          }|t          |          r|                     d          pd}|                     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messageztransient network errorfuturetaskr|   get_namez9Gateway swallowed transient network error from %s: %s: %sz<unknown task>exc_info)rB   r   hasattrr   reprrF   loggerwarningr   r   __traceback__default_exception_handler)r   r   r   r   r   	task_names         r.   _gateway_loop_exception_handlerr   m  s-    ++k
"
"C
6s;;++i((E,E{{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 )NrZ   r|   z
[REDACTED])	lastindexgroup)ms    r.   <lambda>z5_redact_gateway_user_facing_secrets.<locals>.<lambda>  s     *K!''!***|)[ r0   )rC   agent.redactr   rF   _GATEWAY_SECRET_PATTERNSsub)r   redactedr   patterns       r.   #_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   rC   )r   r   s     r.   _redact_approval_commandr     s6     322222  SYBt<<<<r0   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 .)lenrb   r2   )	r   r   r   r   r   r   cmd_previewheadingchoicess	            r.   _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$:$:$:	;r0   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    r.   _gateway_provider_error_replyr     s}    $$T** 
<	
 	
 #))$// 
S	
 	
 $$T** jii	; r0   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  
   )rC   rD   r   countbool _GATEWAY_PROVIDER_ERROR_SHAPE_REr   )r   bodys     r.   "_looks_like_gateway_provider_errorr     so      ut99??D 4yy3$**T**Q..u077==>>>r0   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|   )rS   rC   rD   
startswithr   r   r   r   )rN   r   r   s      r.    _sanitize_gateway_final_responser     s      '11  4yy##$FGG r23t99==H)(33 7,X666Or0   
event_typer   c                 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)
rC   rD   rS   r   _TELEGRAM_NOISY_STATUS_REr   rI   _COMPRESSION_PROGRESS_STATUS_REr   r   )rN   r   r   r   s       r.   _prepare_gateway_status_messager   .  s     w}"##%%D t'11 .t44D ''--  :;;	/66t<<	 4)$// 3,T222Kr0   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|   )rC   r}   rD   )notices    r.   render_notice_liner   L  s/     wvvr**0b1177999r0   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         r.   _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Br0   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}   rC   rE   )rN   r  r  r   platform_valueplatform_keys         r.   _resolve_progress_thread_idr  h  s     Xw99N~+,,2244L C	 	 $%%-=)>)>>>4(8Bs#$$$dB %#$$$...3C.#$$$4r0   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r@   rA   rB   )r	  r  r
  r  r  platform_cfgs         r.   _has_platform_display_overrider    s    ,6{D,I,ISkooi(((tGgt$$ uK((Ii&& u==..LlD))Eg.EEr0   defaultrN   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  rP   )r,   	candidates     r.   	<setcomp>z0_resolve_gateway_display_bool.<locals>.<setcomp>  s0        	 	**  r0   Fr   resolve_display_setting>   r;   r<   r=   r>   )
rP   rc   r  gateway.display_configr  r@   r   rC   rD   rE   )
r	  r  r
  r  rN   r  current_platformplatform_onlyr  r{   s
             r.   _resolve_gateway_display_boolr    s      /x/G<HH 7@355  M
 	M)).{L'RR 	* u>>>>>>##KwPPE% % C{{}}""$$(BBB}G}};;r0   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 )NrZ   /r   )r   )r#  	sanitizedr"  s     r.   _replacez/_telegramize_command_mentions.<locals>._replace  s<    ++EKKNN;;	"+?9Q?r0   )r}   hermes_cli.commandsr"  r)   MatchrC   _TELEGRAM_COMMAND_MENTION_REr   )r   rN   r  r'  r"  s       @r.   _telegramize_command_mentionsr+    s     Xw99N##;;;;;;@ @# @ @ @ @ @ @ (++Hd;;;r0     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)r@   r   	timestampr   intfloatrC   rD   
ValueErrorfromisoformatreplace)r{   r   numerics      r.   _coerce_gateway_timestampr6    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.sessionr9  r8  s    r.   _auto_continue_freshness_windowr;    s%     ?>>>>>))+++r0   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|   )r`   ra   rB   r1  	TypeErrorr2  )r   r  raws      r.   
_float_envr?    ss     *..

C
{cRiiW~~Szzz"   W~~s   A  A*)A*)nowwindow_secsr@  rA  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)r1  %_AUTO_CONTINUE_FRESHNESS_SECS_DEFAULTr6  time)r{   r@  rA  windowr/  currents         r.   _is_fresh_gateway_interruptionrG  '  sv    " " 	k899 
 {{t)%00It [dikkkcGY&((r0   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         r.   build_resume_recovery_noterS  D  s    0 &&& 	 ''' "!%   
. 	
= 	 
 
D 	
= 	; 	+ 			 	 4C	 	 		 	 	
  '.'B	0r0   )	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   rb  rU  Nr/  )rB   r@   rC   rZ  )	r[  r   r\  r]  entry_sidecar_rkey_rvaltss	            r.   _build_replay_entryrh    s   : &*g>>E ww}%%H%%%x%% 	& 	& swwy))))'m{- 
	! 
	!ECGGENNE+++= !  E%LL $WW[!! 	$!#E+Lr0   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)ri  s    r.   %_uses_telegram_observed_group_contextrl    s     ]#K~#]^^^r0   r>  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  )rC   rD   r+   s     r.   r  z&_csv_or_list_to_set.<locals>.<setcomp>	  s=    GGGdSYY__5F5FGD		!!GGGr0   c                 ^    h | ]*}|                                 |                                 +S r  )rD   r+   s     r.   r  z&_csv_or_list_to_set.<locals>.<setcomp>  s-    BBBTTZZ\\BDJJLLBBBr0   ,)rc   r@   listrC   rD   r1   )r>  ss     r.   _csv_or_list_to_setrs    s{    
{uu#t HGGcGGGGCA uuBBQWWS\\BBBBr0   rG   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}   rB   PlatformSLACKr`   getenvrs  )rG   r  r>  s      r.   +_slack_ignored_channels_from_gateway_configr{    sz     6;3377GGL
ClGR00445GHH
{ i0119Ts###r0   r   c                 \    | sdS t          |                               dd          d         S )zFReturn the parent Slack channel from a possibly thread-scoped chat ID.r|   :rZ   r   )rC   r1   r   s    r.   _slack_parent_channel_idr  %  s0     rw<<c1%%a((r0   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   )rG   r   
channel_idignoreds       r.   _is_slack_ignored_channelr  ,  s=    )'22J9&AAG
Hw G*2GIIIr0   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``.
    Fgatewaymessage_timestampsenabled)r@   rA   rB   r   )r	  gwmts      r.   _message_timestamps_enabledr  3  s     k4(( u		#	#Bb$ u	$	%	%B"d .BFF9e,,---88Or0   ri  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   ra  r/  tzobserved
tool_callstool_call_idtoolc                 "    i | ]\  }}|d v	||S )>   r  r/  r  r,   kvs      r.   
<dictcomp>z0_build_gateway_agent_history.<locals>.<dictcomp>  s)    \\\$!QB[9[9[A9[9[9[r0   mirrormirror_sourcezanother sessionz[Delivered from ] )r]  r@  r   N)hermes_timer  gateway.message_timestampsr  rl  rB   r@   rC   rb   rD   items_strip_auto_continue_noiserh  _strip_interrupted_tool_tails_strip_dangling_tool_call_tail$_strip_stale_dangerous_confirmationsrD  r2   )r  ri  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_srcrc  observed_contexts                      r.   _build_gateway_agent_historyr  G  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  ''' 2-@@M 3=AAM 949;;  M yy!788>>@@HD***r0   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.
    )r@   rq  r   )r  r  s     r.   _select_cached_agent_historyr    sE    " ,%% "#l*;*;cBS>T>T*T*TL!!!r0   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  )r@   rA   r+   s     r.   
<listcomp>z?_wrap_current_message_with_observed_context.<locals>.<listcomp>  s1    VVVdD$!7!7A4:::TVVVr0   r   r   r|   )r   r   )_OBSERVED_GROUP_CONTEXT_HEADER!_CURRENT_ADDRESSED_MESSAGE_HEADERr@   rC   rq  rA   rB   rstrip)r   r  prefixwrappedr-   s        r.   +_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Nr0   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  r/  )reversedr@   rA   rB   )r  r\  r[  rg  s       r.   _last_transcript_timestampr    s      t    #t$$ 	wwv 	t999WW[!!>III tt4r0   >   image_generatetext_to_speechtext_to_speech_tool)is_interrupted_tool_resultstrip_interrupted_tool_tailsstrip_dangling_tool_call_tail#strip_stale_dangerous_confirmationsis_dangerous_confirmationz [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)r@   rC   r   _AUTO_CONTINUE_NOTE_PREFIX_AUTO_CONTINUE_FALLBACK_PREFIX)r   s    r.   _is_auto_continue_noiser    sI     gs## u566 	><==r0   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|   rZ   N)r  rC   findlstrip)r   r   ends      r.   r  r  !  s     #7++ w<<D
!$
'
' (iinn772C!GII%%''	 "$
'
' (
 Kr0   )
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[  rb  r  r   call_idfunctionr   r|   F)r  r  r  r   r  MEDIA:successrZ   ",}[[audio_as_voice]]T)rc   r   rB   rC   _AUTO_APPEND_MEDIA_TOOL_NAMESjsonloadsrF   r@   rA   _JSON_MEDIA_TOOL_PATH_FIELDS_TOOL_MEDIA_RE	fullmatchrb   finditerr   rD   r  )r  r  r  new_messagestool_name_by_call_idr\  callr  fnr   
media_tagshas_voice_directiver   	tool_namepayloadfieldrg   r#  s                     r.   _collect_auto_append_media_tagsr  H  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 ]}|                    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	vrt          |                    d
d          pd          }d|v rot                              |          D ]S}	|	                    d                                                              d          }
|
r|                    |
           Tt          |                    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 tool results.

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

    Missing the JSON-payload shape caused #46627: after a compression
    boundary the auto-append fallback rescans full history, re-discovers an
    earlier ``image_generate`` result whose path was never in the dedup set,
    and re-emits the MEDIA tag every turn.
    r[  rb  r  r   r  r  r   r|   >   r  r  r   r  rZ   r  r  r  Nr  )rc   rB   rC   r  r  r   rD   r  re   r  r  rF   r@   rA   r  )r  pathsr  r\  r  cidr  r   r   r#  pr  r  jps                 r.   _collect_history_media_pathsr    s    E+- : :776??k))--3 : :hhtnn;(;(;XXj))/R266&>>CTXXf-=-=CDD :4 :59(S2  776??"666cggi,,233w'0099 ! !KKNN((**11%88 !IIaLLL#''.))ESWWY-?-?E2FF##C((,<<<*W--   '4(( W[[-C-C 9  E U++B!"c** r 		"Ls   !G66HH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)r`   ra   rB   rg   rf   logging	getLoggerr   r   popsslget_default_verify_pathscafileopenssl_cafilecertifiwhereImportError)configured_certr  r  r  r  s        r.   _ensure_ssl_certsr	    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.schedulerr  upper)r
  r  resolveds      r.   _home_target_env_varr     sN     544444$$]33H !!##2222r0   c                 &    t          |            dS )zDReturn the optional thread/topic env var for a platform home target.
_THREAD_ID)r  )r
  s    r.   _home_thread_env_varr    s    "=11====r0   c                  :    t           dz                                  S )zIReturn True when a /restart completion marker is waiting to be delivered..restart_notify.json)_hermes_homerf   r  r0   r.   _restart_notification_pendingr    s    1199;;;r0   c                      t           dz  S )Nz.restart_pending.json)r  r  r0   r.   "_planned_restart_notification_pathr    s    111r0   c                  B    t                                                      S )zHReturn True when a non-chat planned restart should notify home channels.)r  rf   r  r0   r.   %_planned_restart_notification_pendingr    s    -//66888r0   c                  J    t                                          d           d S )NT
missing_ok)r  unlinkr  r0   r.   #_clear_planned_restart_notificationr!  "  s%    &((//4/@@@@@r0   r;   _HERMES_GATEWAY)get_hermes_homeget_hermes_home_override)atomic_json_writeatomic_yaml_writebase_url_host_matchesis_truthy_value)load_dotenv)load_hermes_dotenv.envrZ   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_activeNrZ   r+  r,  )	agent.secret_scoper1  _bridge_max_turns_from_configr  r*  r   r]   r^   parentsr0  s    r.   /_reload_runtime_env_preserving_config_authorityr5  <  s     766666  	&l333 NN**,,4Q7&@    ",/////r0   homer   c                    | dz  }|                                 sdS 	 ddl}t          |d          5 } |j        |          pi }ddd           n# 1 swxY w Y   ddlm}  ||          }	 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   utf-8encoding_expand_env_varsmanaged_scopeagent	max_turnsHERMES_MAX_ITERATIONSsessionscjk_ftsHERMES_CJK_FTSsearch_slow_msHERMES_SEARCH_SLOW_MS)rf   yamlopen	safe_loadhermes_cli.configr=  
hermes_clir?  apply_managed_overlayrF   rB   r@   rA   rC   r`   ra   )	r6  config_path_yamlfcfgr=  r?  	agent_cfgsessions_cfgs	            r.   r3  r3  Y  s   &K +000 	+A!%/!$$*C	+ 	+ 	+ 	+ 	+ 	+ 	+ 	+ 	+ 	+ 	+ 	+ 	+ 	+ 	+666666s##
	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 ,+sX   B AB AB AB .B B 
BB BB 
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.rB  90Z   )r5  r0  r`   rz  r=  r2  r  r0   r.   _current_max_iterationsrW  }  sU    3555294d;;<<<z"   rr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  r0   r.   r\  r\    s           r0   r\  c                       e Zd ZdZdS )SecondaryPortBindingConfigErrorzEA secondary profile conflicts with the multiplexer's shared listener.Nr]  r  r0   r.   rb  rb    s        OOOOr0   rb  profile_homec              #     K   ddl m}m} ddlm}m}m}  |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_scopeN)	hermes_constantsre  rf  r2  rg  rh  ri  rC   r   )rc  re  rf  rg  rh  ri  
home_tokensecret_tokens           r.   _profile_runtime_scoperm    s      & VUUUUUUU          *)#l*;*;<<J##$>$>tL?Q?Q$R$RSSL/<((("":..... 	<((("":....s   A+ +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}   r#  rF   rm  r   r   debug)rQ  r6  s     r.   load_gateway_config_for_runnerrs    s,   " 

C3,e44 
     


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


sE   2 A AB	 !A</B	 <B  B	 B B	 	(B43B4rx  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.configrw  r}   r@   rC   rD   )rN   rt  rw  rx  ry  s        r.   _platform_has_bot_credentialr{    s     877777///tOWd339rE% %++-- toy$77=2G'3 GMMOO t5r0   z=^(?P<host>.+):(?P<container>/[^:]+?)(?::(?P<options>[^:]+))?$z/outputz/outputsr8  r9  r:  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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container_diskTERMINAL_CONTAINER_DISKTERMINAL_CONTAINER_PERSISTENTTERMINAL_DOCKER_VOLUMESTERMINAL_DOCKER_ENVTERMINAL_DOCKER_EXTRA_ARGS&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_persistentdocker_volumes
docker_envdocker_extra_args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_urlry  r  
AUXILIARY_	_PROVIDER_MODEL	_BASE_URL_API_KEYr@  rA  rB  gateway_timeoutHERMES_AGENT_TIMEOUTgateway_timeout_warningHERMES_AGENT_TIMEOUT_WARNINGgateway_notify_intervalHERMES_AGENT_NOTIFY_INTERVALrestart_drain_timeoutHERMES_RESTART_DRAIN_TIMEOUTgateway_auto_continue_freshnessHERMES_AUTO_CONTINUE_FRESHNESSrC  rD  rE  rF  rG  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_SECRETSr  strict0HERMES_MEDIA_DELIVERY_STRICTmedia_delivery_allow_dirsc              #   8   K   | ]}|t          |          V  d S r(   rC   r,   r  s     r.   r/   r/     s.      5W5WUV5Wc!ff5W5W5W5W5W5Wr0   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>   r;   r=   r>   )configured_cwdterminal_backendmessaging_cwdr  home_fallback)ChannelOverriderx  _BUILTIN_PLATFORM_VALUESrn  HomeChannelru  rq  )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)SessionTurnLeaseRegistry)GatewayAuthorizationMixin)GatewayKanbanWatchersMixin)GatewaySlashCommandsMixin)BasePlatformAdapterEphemeralReplyMessageEventMessageType_prefix_within_utf16_limit_reply_anchor_for_eventmerge_pending_message_event	utf16_len)DEFAULT_HEARTBEAT_INTERVAL_Sarm_shutdown_watchdogloop_heartbeat_foreverresolve_shutdown_watchdog_delay)%DEFAULT_GATEWAY_RESTART_DRAIN_TIMEOUTGATEWAY_FATAL_CONFIG_EXIT_CODE!GATEWAY_SERVICE_RESTART_EXIT_CODE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                 L   t          | di                                           D ]~\  }}t          |dd          st                              |          }|s5|\  }}}t          |dd          pi }t	          |                    d          p|rt          j        |d          nd                                                                          }t	          |                    d          p|rt          j        |d          nd                                                                          }	|d	k    r|	d	k    rt          j        d
d                                          dv }
|
p*|o(t          j        |d                                          dv }|rt|j	         dc S dS )zFReturn a startup-abort reason when open policy lacks allow-all opt-in.r  r  Fru  N	dm_policypairinggroup_policyrI  GATEWAY_ALLOW_ALL_USERSr|   >   r;   r=   r>   z&: open policy without allow-all opt-in)
r}   r  _OWN_POLICY_OPEN_ENVrB   rC   r`   rz  rD   rE   r{   )rG   rN   rt  open_envdm_env	group_envallow_all_envru  r1  r3  gateway_allow_allplatform_opted_ins               r.   "_own_policy_open_startup_violationr<  o  s   %,V["%E%E%K%K%M%M I I!/	599 	'++H55 	+3(	=$77=2IIk"" G06E	&),,,I
 
 %''%%'' 	 IIn%% M3<K	)Y///)
 
 %''%%'' 	 <6#9#9I%r
 

%'')* . 
 M	-,,22448LL 	  	.HHHHHH4r0   )_session_model_overrides _pending_one_turn_model_restores_session_reasoning_overrides_session_service_tier_overrides_pending_model_notes_last_resolved_model_queued_events_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_tokensry  r  r  requested_providerapi_moder   argscredential_pool	ry  r  r  rO  rP  r   rQ  rR  rM  )hermes_cli.runtime_providerrG  rH  rI  hermes_cli.authrJ  rK  r   r   _try_resolve_fallback_providerRuntimeErrorrF   r`   ra   rB   r0  r2  r=  r@   rA   rq  )rG  rH  rI  rJ  rK  runtimeauth_exc	fb_configr   	model_cfgrM  _env_mtr  _runtime_mots                 r.   _resolve_runtime_agent_kwargsr^    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   )rG  rH  )	requestedNry  r  r  rO  rP  r   rQ  rR  )ry  r  r  rO  rP  r   rQ  rR  )rT  rG  rH  rF   rW  rB   rq  )r  rG  rH  rX  r   s        r.   *_resolve_runtime_agent_kwargs_for_providerra  	  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``).NrR  z1Failed to resolve credential pool for provider=%sTr   )rC   rD   ra  rB   rF   r   rr  )r  s    r.   _credential_pool_for_providerrc  	  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}  	 ddl}t          dz  }|                                sdS t          |d          5 }|                    |          pi }ddd           n# 1 swxY w Y   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   )rG  Nr8  r9  r:  )resolve_entry_api_keyr  r  )r`  explicit_base_urlexplicit_api_keyz'Fallback provider resolved: %s model=%sr  ry  rO  rP  r   rQ  rR  )	ry  r  r  rO  rP  r   rQ  rR  r  zFallback entry %s failed: %s)rT  rG  rH  r  rf   rI  rJ  r   hermes_cli.fallback_configre  rB   r   inforq  rF   rr  )
rG  _ycfg_path_frQ  fb_listrc  re  rX  fb_excs
             r.   rV  rV  *	  s   DDDDDD+-/   	4(W--- 	),,r""(bC	) 	) 	) 	) 	) 	) 	) 	) 	) 	) 	) 	) 	) 	) 	)$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[[[;	@    4sj   "H/ H/ A!H/ !A%%H/ (A%)H/ ?H/ EG'$H/ '
H+1/H& H/ &H++H/ /
H<;H<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   )eventro  rq  s      r.   _event_media_type_atrs  \	  s<     %55;K!&[)9)9!9!9;urAr0   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)rs  r   r}   r  PHOTOrr  ro  mtypes      r.   _event_media_is_imagerz  f	  sI     !..E *)))5.$//;3DDDr0   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/rv  N)rs  r   r}   r  VOICEAUDIOrx  s      r.   _event_media_is_audior  u	  sO     ..E *)))5.$//K4E{GX3YYYr0   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.rv  NFr|  )r}   r  r~  DOCUMENTr}  rs  r   )rr  ro  rv  s      r.   _event_media_is_stt_inputr  }	  s_    5.$77L);+?@@@u)) 	Cu--88BBr0   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/rv  N)rs  r   r}   r  VIDEOrx  s      r.   _event_media_is_videor  	  sG     ..E *)))5.$//;3DDDr0   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}   	enumeraterz  rb   r  r  r2   )rr  r3   r  iurls        r.   _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r0   display_name
agent_pathry  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  ry  s      r.   _build_document_context_noter  	  si        
8 8 8*48 8 8	
	6| 	6 	6
 	6 	6 	6r0   secondsc                     t          t          |                     }|dk     rd}t          |d          \  }}t          |d          \  }}|r| d|dd|dS | d|dS )Nr   r,  <   r}  02d)r0  rounddivmod)r  totalhoursremminutessecss         r.   _format_durationr  	  s    gEqyyt$$JE33OOMGT 322'2222222""""""r0   rg   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.rZ   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   rbrZ   )waverI  
getnframesgetframerater1  )r  wfframesraterg   s       r.   _wav_durationz,_probe_audio_duration.<locals>._wav_duration	  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  r1  ri  length)r  rg   s    r.   _ogg_durationz,_probe_audio_duration.<locals>._ogg_duration	  s1    333333WWT]]/6777r0   ffprobe-verrorz-show_entrieszformat=durationz-ofz"default=noprint_wrappers=1:nokey=1)stdoutstderrr#   r  r   )r`   rg   splitextrE   r1  asyncio	to_threadr  rF   create_subprocess_exec
subprocessPIPEwait_forcommunicate
returncodedecoderD   )rg   extr  r  r  procr  _s   `       r.   _probe_audio_durationr  	  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     r.   _dequeue_pending_eventr  	  s     &&{333r0   zStop requestedzSession reset requestedz Execution timed out (inactivity)zSSE client disconnectedzGateway shutting downzGateway restartingc                     | sdS d                     t          |                                                                                                                     }|t
          v S )z?Return True when an interrupt message is internal control flow.FrN  )r2   rC   rD   r1   rE   _CONTROL_INTERRUPT_MESSAGES)r   
normalizeds     r.   _is_control_interrupt_messager  
  sV     u#g,,,,..446677==??J444r0   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.
    r9  r4  )r;  errorsNNu   ﻿z---z
---   r   Nzname:r}  rZ      r   >   "'rN  -r  z
[^a-z0-9-]r|   z-{2,})	read_textrF   r  r   r  
splitlinesrD   r1   r   rE   r4  r)   r   )r  r   r  declared_nameliner>  slug_res           r.   _skill_slug_from_frontmatterr  
  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)rE   r4  tools.skills_toolr  agent.skill_utilsr  r  rf   rglobr  rj  r  r   r]   r^   r_   relative_torq  r3   r2   rF   )r  r  r  r  r  disabled
skills_dirr  r  r  r  	repo_rootoptional_dir	_declaredrelr3   install_paths                    r.   _check_unavailable_skillr  N
  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)rx  LOCALr{   rR   s    r.   _platform_config_keyr  
  s    ..55HNBr0   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)r?   r   r@   rq  )rG   r  s     r.   _teams_pipeline_plugin_enabledr  
  sP    !##FfiB???Ggt$$ uw&E*:g*EEr0   c                  N    t                      } | rt          |           S t          S )z<Return the Hermes home that gateway config reads should use.)r$  r   r  )overrides    r.   _gateway_config_homer  
  s'    '))H H~~r0   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.
    r8  Fr   )get_config_pathread_raw_configTNrr9  r:  z%Could not load gateway config from %sr>  )_normalize_root_model_keys)r  rK  r  r  rF   rf   rH  rI  rJ  r   rr  rL  r?  rM  r@   rA   r  )
config_homerN  r>  used_canonicalr  r  rH  rP  r?  r  s
             r.   r?   r?   
  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)r@   rA   rB   r   rK  r  )rG   cp_cfgr  defaultss       r.   _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); <(
 (
  r0   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<  )r?   r@   rA   rK  r=  )rQ  r=  expandeds      r.   _load_gateway_runtime_configr  
  sh     
 
 Cc4    	222222$$H!(D11988r9r0   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|   )r?   rB   r@   rC   rA   )rG   rQ  r[  s      r.   _resolve_gateway_modelr    s     &&&,@,B,BC$$I)S!! H	It	$	$ H}}Y''G9==+A+AGRG2r0   	thread_id	parent_idr  r  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).
    )rc   rC   re   rb   )r   r  r  keysrp   r  sks          r.   _channel_override_lookup_keysr  #  so     DUUDI.   	XX::BKr0   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  Nr  )r}   rB   channel_overridesr  )
rG   rN   r   r  r  r  rt  	overridesr  ovs
             r.   _get_channel_overrider  ;  s     T22I tmmH--O /"C t1I,9	     ]]3>III 4r0   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hermesrL  z-mzhermes_cli.main)shutilwhichimportlib.utilutil	find_specr\   
executablerF   )r  
hermes_bin	importlibs      r.   _resolve_hermes_binr'  X  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@  rZ   mainr  r  r   )rN   	chat_typer   >   dmthreadr  N)r1   r   )r  r3   results      r.   _parse_session_keyr/  s  s     c""E
5zzQ58w..58v3E3EaqQx
 

 u::>>eAh*:::"'(F;4r0   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   
completion
session_id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)rB   tools.process_registryr;  )	r0  evt_type_sid_cmd_pat_out_supr   r;  s	            r.   $_format_gateway_process_notificationrC    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///4r0   
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   r2  >   r6  r5  r:  )empty
get_nowaitrF   rB   rb   put)completion_queuewatch_eventsrequeuer0  r=  s        r.   _drain_gateway_watch_eventsrL    s      "LG$$&& 	 	"--//CC 	 	 	E	776<00888$$$$+++NN3 $$&& 	   " "S!!!!s   / 
<<c                      d S r(   r  r  r0   r.   r   r     s    D r0   _gateway_runner_refhistory_lenagent_resultresponserP  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     r.   r/   z2_normalize_empty_agent_response.<locals>.<genexpr>  s;       !
 !
 N!
 !
 !
 !
 !
 !
r0   )r   rx  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.)rB   rC   rE   anyr0  ,_is_gateway_hidden_reasoning_incomplete_turn)rQ  rR  rP  error_detailis_context_failurer^  errrW  s          @r.   _normalize_empty_agent_responserg    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	
 	

 Or0   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.
    FrT  r_  r`  r  r|   zremained incomplete afterfinal_response)r@   rA   rB   rC   rD   rE   )rQ  
error_textri  s      r.   rc  rc  %  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=:!==r0   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_  rT  r`  r  	completedTr  )rQ  s    r.   '_should_clear_resume_pending_after_turnrm  =  s     lD)) u&& u!! \%5%5i%@%@ LDTDTU\D]D] u$$--u4r0   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  )r@   rA   rB   r0  )rn  ro  current_offsetfollowup_offsetr   s        r.   (_preserve_queued_followup_history_offsetrs  Q  s     ot,, nd++ #''(899N%))*:;;Onc** /3'' O~,M,M/""F-FMr0   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   )
disconnectrF   r   rr  r}   r   r   r   s    r.   _dispose_unused_adapterrx  q  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  rZ   )min_RECONNECT_BACKOFF_CAP)ry  s    r.   _reconnect_backoffr~    s!    rQ7Q;'(*@AAAr0   c                   %   e Zd ZU dZi Zeeef         ed<   dZ	eed<   d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<   i Z"eeeeef         f         ed<   i Z#eeeee!f         f         ed<   i Z$eeeee!f         f         ed<   i Z%eeee         f         ed<   i Z&eee'e         f         ed<   i Z(eee)f         ed<   i Z*eeef         ed<   d	Z+eed<   dZ,ed         ed<   d Z-eed!<   dZ.ed"         ed#<   d	Z/eed$<   dd%ee0         fd&Z1dd(Z2dd)Z3d'efd*Z4e5d+z  Z6d,ed-ed'efd.Z7d'eeef         fd/Z8dd0Z9d-ed1ed'dfd2Z:d-ed3ed'dfd4Z;dd5Z<d6e=e!         d7ed'efd8Z>dd9Z?dd:d;ee         d'dfd<Z@d'efd=ZAd'efd>ZBd	d?d@ed'efdAZCd'efdBZDeEd'efdC            ZFeEd'efdD            ZGeEd'ee         fdE            ZHeEd'ee         fdF            ZIdGed'efdHZJdGed'efdIZK eLdJdKh          ZMdGed'efdLZNdGed'efdMZOdNZPdGed'efdOZQd'efdPZRd'efdQZSdGed'ee         fdRZTdGed'dfdSZUdGedTed'dfdUZVdGed'ee         fdVZWdGed'efdWZXddddXdGee         dYee         dZeeY         d'e)eeYf         fd[ZZd\ed]ed^eYd'eYfd_Z[d`edae!d'dfdbZ\dceee!f         d'dfddZ]dee^d'dfdfZ_dee^d'dfdgZ`dee^d'dfdhZadTed'dfdiZbd'efdjZcd'efdkZdd'efdlZed'efdmZfd'efdnZgd'efdoZhd'e)fdpZid'efdqZjddrZkd'efdsZlddtZmdu Znddved'dfdwZod'efdxZpd'efdyZqd'efdzZrdYed{d|dee!d'dfd}ZsdYedee!d~ed|         d'ed|         fdZtdddYedee!d'efdZuevde!d'efd            ZwdYedee!d'efdZxd`ed'efdZyddee         dee         d'dfdZzddZ{ddZ|ddZ}ddved'dfdZ~ddddd,edee         dee         dee         d'df
dZdJddTed'dfdZd'efdZevd'e'eee!f                  fd            Zevd'efd            Zddddd,ed-edZeeY         dee         dee         d'efdZdddd,ed-edee         dee         d'ef
dZevdd]ed'eYdz  fd            Zevded'e)eef         fd            ZdddJddGee         dYee         d]ed'eYdz  fdZdYedeeY         d'dfdZ	 	 ddYee         d'ee         fdZ	 ddYeded'dfdZevd'edz  fd            Zevd'efd            Zevd'efd            Zevd'efd            Zevd'efd            Zevd'efd            Zevd'eYfd            Zevd'edz  fd            Zd'edz  fdZevdae!dedz  d'dfd            Zd'eee!f         fdZd'ee         fdZdYed'ee         fdZdYedGed'e)e!ee         f         fdZevde!d'efd            ZdYed'efdZevdYefd            ZdZdYeded'dfdZdedYed'efdZd7ed'e)eee!f         ef         fdZdTed'dfdZddZdeee!f         d'dfdÄZdYee         dae!dee!         d'efdńZdNZdej        dae!ded'dfdȄZdJdɜdae!ded'dfdʄZdae!d'dfd˄ZdZdZded'dfdτZd'efdЄZdYed'dfdфZdd҄ZddӄZd	d	dԜdeded'efdׄZ eLh dأ          Zdee^dedYed'dfdلZded'dfdڄZd'efdۄZdd܄Zd'efd݄Zdd'efdބZd'efd߄Z	 	 ddeee^         d,ee         d'efdZd'efdZdZdZddddZddved'dfdZdeee!f         d'dfdZÐddvefdZd'efdZŐddZƐddZd'efdZȐddZd	d	d	ddededed'dfdZʐddZd'efdZdedddee)ef         d'efdZdee^ded,ed'dfdZded,ed'dfdZded,edee^d'dfd Zded,ed'ee^ge=d         f         fdZded,edee^d'dfdZdefdZevdee!d'ee         fd            Zd,ed%e!d'ee^         fdZ	 dd,edee         d'eeee         ee         gef         fdZאded'dfdZؐd	eِd
ed'ee         fdZded'ee         fdZdd|ded'dfdZdYed'dfdZdddedGede'eee!f                  dYee         d'ee         f
dZdddedGede'eee!f                  dYee         d'ee         f
dZdYed'e'e         fdZdYed'dfdZeEd'efd            ZdYefdZdedefdZdGed'efdZd'efdZdGeded'ee         fdZdGeded'efd Zded'efd!Zded'efd"Zdefd#Zd'efd$Zdߐd%ZdGe!d&ed'dfd'ZdGe!d&ed'dfd(Zd	e!dGe!d)ed'dfd*Zevded'ee         fd+            Zded'efd,Zded'efd-Zd-ed'dfd.Zd/ed0ed1ed'efd2Zd/ed0ed1efd3Z	 dded4ed5ed6ed'ef
d7Zd'efd8Zded9ed'dfd:Zd4eded'dfd;Z	 	 	 dd<edGd=d>ed?ee         d@ee'e                  dAee'e                  d'dfdBZ	 	 	 dd<edGd=d>ed?ee         d@ee'e                  dAee'e                  d'dfdCZdGed'eYfdDZdGed'dfdEZdGed'dfdFZ dGed'efdHZdGed'efdIZdGed'efdJZdGed`edGed'dfdKZdGed`edGed'dfdLZdGed`edGed'dfdMZdGed'efdNZdGed`edGed'dfdOZdPZ	dGed'efdQZ
d'efdRZdGed'efdSZdGed'efdTZdedUed'efdVZded'efdWZdedXedGedYed'eedZdf         f
d[ZdedXedGed&ed'ee         f
d\Zd'eee!f         fd]Z	 d֐d^ee         d'eeee!f                  fd_Zdddd`d,ee         d-ee         dee         daee         d^ee         deee!         d'eeee!f                  fdbZevdddcd,ee         d-ee         dee         daee         deee!         d'efdd            Zevded'ee         fde            ZdZ eLej        ej        ej        ej        ej        ej        ej        ej         ej!        ej"        ej#        ej$        ej%        ej&        ej'        h          Z(dאdfZ)	 	 	 ddiedjed7ed'dfdkZ*d'efdlZ+d'ee)eeee         f                  fdmZ,ddndoeee)eeee         f                           d'ee)eeee         f                  fdpZ-dǐe.d'efdqZ/dred'dfdsZ0dt Z1d'e2j3        j4        fduZ5dאdvZ6ddddddwdGee         dYee         dZeeY         dxee         d]ee         d'efdyZ7dzed{e'e         d'efd|Z8dzed}e'e         d'e)ee'e         f         fd~Z9d'e'e         fdZ:	 d֐dzee         d'e)edz  e'e         f         fdZ;dddde'e         ded'dfdZ<e=dd9eded'e)ee'e         f         fdZ>deYfdZ?dedeYd'ee         fdZ@evdeYd'ee)eeeAf                  fd            ZBded'efdZCdedeYd'ee         fdZDdeYd'dfdZEddved'dfdZFdeYd'dfdZGd̐ZHdZIe)ed<   dZJi ZKeYe)eedz  f         eYee!f         f         ed<   eLd'eYee!f         fd            ZMeLd'eYee!f         fd            ZNeLdZeYdz  d'eYfd            ZOev	 	 	 dd]edeYdededeYdz  d0edz  dedz  d'efd            ZPdYed'dfdZQdYed]ed^eYd'e)fdZRdYed'eYfdZSdYedeYd'dfdZTdYeded'efdZUdddYedee         d'efdZVdYeded'efdZWdYededed'efdZXdYedTed'dfdZYdYed'dfdZZdYed'efdZ[dJddYedTed'efdZ\dYeded'efdZ]dee!dYededz  d'dfdZ^dddYedGedededed'dfdZ_dYed`ee         d'dfdZ`dYede'e         d'dfdZadYed'e'e         fdZbdGedYed'ee         fdZcdedYee         d'efdZdevded'efd            ZedYed'dfdZfevdae!ded'dfdÄ            Zgdae!ded'dfdńZhdae!ded'dfdƄZidae!d'dfdǄZjdאdȄZkd'efdɄZld'ee         fdʄZm	 	 	 dd&edede'eee!f                  dGd=d`edYedee         d?ee         d'eee!f         fd̄Zn	 	 	 	 	 	 	 	 dd&edede'eee!f                  dGed`edYedee         ded?ee         dee         deeY         dee!         dee         d'eee!f         fd҄ZodGed'ee         fdӄZpdGed'dfdԄZq	 	 	 	 	 	 	 	 dd&edede'eee!f                  dGed`edYedee         ded?ee         dee         deeY         dee!         dee         d'eee!f         fdՄZrdS (  GatewayRunnerz
    Main gateway controller.

    Manages the lifecycle of all platform adapters and routes
    messages to/from the agent.
    _running_agents_ts	interrupt_busy_input_mode_busy_text_mode_restart_drain_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_watchdogr=  r>  r?  r@  rD  _session_ephemeral_pin_session_vc_last_startup_restore_in_progresszasyncio.Task_loop_heartbeat_task        _gateway_started_atzthreading.Event_shutdown_watchdog_done _platform_lock_takeover_on_startrG   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 tM          | j        j'        | j        fd          | _(        tS          | j(                  | _*        tW          | j                  | _,        d| _-        d | _.        t_          j0                    | _1        d| _2        d| _3        d | _4        d | _5        d| _6        i | _7        d | _8        d| _9        d| _:        d| _;        d| _<        d| _=        d| _>        d| _?        d | _@        t          jA                    | _B        d| _C        d | _D        d | _E        t          jG                    | _H        d | _I        d| _J        i | _K        i | _L        i | _M        t                      | _O        i | _P        i | _Q        i | _R        i | _S        i | _T        i | _U        i | _V        d| _W        d| _X        g | _Y        g | _Z        t                      | _\        d| _]        t          jG                    | _^        t                      | _`        t                      | _a        d| _b        dd lF}t                      | _c        |G                                | _d        i | _e        i | _f        i | _g        i | _h        i | _i        i | _j        i | _k        | l                                | _m        d | _n        d | _o        i | _p        i | _q        t                      | _r        i | _s        dd lt}|u                    d          | _v        	 ddlwmx}  |d           n# t          $ r Y nw xY w	 ddlymz}  |            }t          t          |ddd          pd          }                                ~                                }	t	          t          |ddd                    }
t          |ddd           }|	dk    r|
s|st                              d           n,# t          $ r t                              dd           Y nw xY wd | _        	 ddlm}m}  | |                      | _        n2# t          $ r%}t                              d|           Y d }~nd }~ww xY w| j        	 ddlymz}  |                                d           pi }|                    d!d          r| j        j                            t          |                    d"d#                    t          |                    d$d
                    t	          |                    d%d                    | j        j'        &           n2# t          $ r%}t                              d'|           Y d }~nd }~ww xY w	 ddlymz}  |                                d(          pi }|                    d!d          rdd)lm}  |t          |                    d"d*                    t          |                    d$d
                    t	          |                    d+d                    t          |                    d,d-                    .           n2# t          $ r%}t                              d/|           Y d }~nd }~ww xY wdd0lm}  |            | _        i | _        dd1lm}  |            | _        |                                 | _        i | _        t                      | _        t          jA                    | _        d | _        t          jA                    | _        d2| _        d S )3Nr   )set_multiplex_activerp  Fz#could not set multiplex-active flagTr   process_registrybg_process_max_age_hours   r,  c                 2                         |           S )N)max_active_age)has_active_for_session)r  _bg_max_age_secondsr  s    r.   r   z(GatewayRunner.__init__.<locals>.<lambda>  s$    0@0W0W$7 1X 1 1 r0   )has_active_processes_fn   i   rZ   )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: %srC  
auto_pruneretention_daysrV  min_interval_hoursvacuum_after_prune)r  r  vacuumsessions_dirz%state.db auto-maintenance skipped: %sr   )maybe_auto_prune_checkpoints   delete_orphansr    )r  r  r  r  z'checkpoint auto-maintenance skipped: %sPairingStore)HookRegistryr  )rs  rG   r2  r  r   r}   rF   r   rr  adapters_profile_adapters'_warn_if_docker_media_delivery_is_risky_weakrefrefrN  _load_prefill_messages_prefill_messages_load_ephemeral_system_prompt_ephemeral_system_prompt_load_reasoning_config_reasoning_config_load_service_tier_service_tier_load_show_reasoning_show_reasoning_load_busy_input_moder  _load_busy_text_moder  _load_restart_drain_timeoutr  _load_provider_routing_provider_routing_load_fallback_model_fallback_modelr<  r  default_reset_policyr  r  session_storer  _async_session_storer
  delivery_router_running_gateway_loopr  Event_shutdown_event_exit_cleanly_exit_with_failure_exit_reasonr  r  r  r  r  r  _signal_initiated_shutdownr  r  r  r  r  rD  _startup_time_booted_from_restartr  r  	threadingLock_executor_lock	_executor_executor_closing_running_agentsr  _active_session_leasesr  _turn_leases_turn_lease_tokens_pending_messagesrB  rC  &_pending_native_image_paths_by_session_busy_ack_ts_session_run_generationr  r  _startup_restore_queue_startup_restore_tasksr   _session_sources_session_sources_max_completion_delivery_lockrc   _completion_deliveries_inflight _completion_deliveries_delivered_completion_delivery_retention_agent_cache_agent_cache_lockr=  r>  r?  r@  rD  r  r  _active_profile_name_kanban_notifier_profile_teams_pipeline_runtime_teams_pipeline_runtime_error_pending_approvals_failed_platforms_fatal_handler_tasks_update_prompt_pending	itertoolsr   _slash_confirm_countertools.tirith_securityr  rK  r  rC   r   rD   rE   r   _session_dbhermes_stater  r  rB   _dbmaybe_auto_prune_and_vacuumr0  tools.checkpoint_managerr  gateway.pairingr  pairing_storepairing_storesgateway.hooksr  hooks_load_voice_modes_voice_mode_recent_voice_transcripts_background_tasksr  r  _last_inbound_at_scale_to_zero_cooldown_until)selfrG   r  _bg_max_age_hours
_threading
_itertoolsr  _load_full_config	_appr_cfg
_appr_mode
_tirith_on_aux_approvalr  r  e	_sess_cfgr   	_ckpt_cfgr  r  r  r  r  s                        @@r.   __init__zGatewayRunner.__init__  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#!%!<!<!>!>#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 "' 024668# 566 5713 57! >@LN3.079$
 -2) 16-:<#:<# DO==$'! *3)9)9&MPUU,^i^k^k-.2+ 	'&&&7B}}!+!2!2 DF%KM- HJ) JL,
 BD( 9;# 13(,(A(A(C(C%'+$<@* >@ BD *-! 8:# 	'&&&&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	==u55 $(DD'*9==9I2+N+N'O'O+.y}}=QSU/V/V+W+W#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#'	6F(M(M#N#N&))--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;S 
SSB-V &V65V6 W" "
X,XXC[+ +
\5\\C_6 6
`% `  `%r%   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)rx  MSGRAPH_WEBHOOKr  r  r   rr  plugins.teams_pipeline.runtimer"  rF   r   ri  r  )r  r"  r   bounds       r.   _wire_teams_pipeline_runtimez*GatewayRunner._wire_teams_pipeline_runtimeW  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  )rx  r  
API_SERVERWEBHOOKr  s     r.   r  zIGatewayRunner._warn_if_docker_media_delivery_is_risky.<locals>.<listcomp>  s3    xxxQqQYQdfnfv@w7w7wq7w7w7wr0   r  c                 V    g | ]&}t          |t                    t          |          'S r  )r@   rC   r,   r  s     r.   r  zIGatewayRunner._warn_if_docker_media_delivery_is_risky.<locals>.<listcomp>  s-    LLL!As9K9KLs1vvLLLr0   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/...'.)r`   rz  rD   rE   rG   get_connected_platformsr  r  r@   rq  rF   r   rr  _DOCKER_VOLUME_SPEC_REr#  r   $_DOCKER_MEDIA_OUTPUT_CONTAINER_PATHSr   )
r  	connectedmessaging_platformsraw_volumesvolumesparsedhas_explicit_output_mountspecr#  container_paths
             r.   r  z5GatewayRunner._warn_if_docker_media_delivery_is_riskyv  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;  rF   )r  r;  s     r.   _has_setup_skillzGatewayRunner._has_setup_skill  sQ    	<<<<<<;344D@@ 	 	 	55	s    
##zgateway_voice_mode.jsonrN   r   c                     |j          d| S )z6Return a platform-namespaced key for voice mode state.r}  r{   )r  rN   r   s      r.   
_voice_keyzGatewayRunner._voice_key  s    .,,7,,,r0   c                    	 t          j        | j                                                  }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 )N>   alloff
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JSONDecodeErrorrd   r@   rA   r  rC   r   r   )r  datavalid_modesr.  r   r  r  s          r.   r  zGatewayRunner._load_voice_modes  s    	:d3==??@@DD!4#7A 	 	 	III	 $%% 	I222!ZZ\\ 	 	MGT;&&g,,C#~~U  
 F3KKs   +. AAc                    	 | j         j                            dd           | j                             t	          j        | j        d                     d S # t          $ r&}t          	                    d|           Y d }~d S d }~ww xY w)NTr4  exist_okr  indentzFailed to save voice modes: %s)
rE  r_   mkdir
write_textr  dumpsr  rd   r   r   )r  r  s     r.   _save_voice_modeszGatewayRunner._save_voice_modes  s    	@!(..td.KKK!,,
4+A666      	@ 	@ 	@NN;Q?????????	@s   AA 
B"BBr  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}   r@   rc   re   discard)r  r   r   r  disabled_chatsenabled_chatss         r.   _set_adapter_auto_tts_disabledz,GatewayRunner._set_adapter_auto_tts_disabled  s     *DdKK.#.. 	F 	,w'''#G-FMMM--- /%%g...../ / ""7+++++r0   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.
        rU  NrT  rV  )r  r   r   r  rY  rX  s         r.   _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 !!'*****r0   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``
        rN   NrT  rU  r   r  voiceauto_ttsF_auto_tts_defaultr}  c              3      K   | ]9\  }}|d k    |                                |t                    d         V  :dS )rC  Nr   r   r,   r  r  r  s      r.   r/   zBGatewayRunner._sync_voice_mode_state_to_adapter.<locals>.<genexpr>  sX       " "&/c45==S^^F%;%;= CKKLL! ===" "r0   c              3   ~   K   | ]7\  }}|d v 	|                               |t                    d         V  8dS )>   rB  rD  Nrb  rc  s      r.   r/   zBGatewayRunner._sync_voice_mode_state_to_adapter.<locals>.<genexpr>#  s_       ! !&/c4000S^^F5K5K0 CKKLL!0000! !r0   )r}   r@   rx  rc   rK  r  r   rB   rF   r   r`  r{   clearupdater  r  )	r  r   rN   rX  rY  r  	_full_cfgr`  r  s	           @r.   !_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_futurewaitCancelledErrorcanceladd_done_callbackr   )r  ri  r  r   done_pendings         r.   #_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_secsrr  rv  r   r   r{   rF   rr  )r  r   rN   r  rl  r  s         r.   _safe_adapter_disconnectz&GatewayRunner._safe_adapter_disconnectE  s      7799	"FF""$$g       I  _&.&:HNN	       	 	 	LLI"*"6I        	s   AA1 1
B+;%B&&B+profilerw  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: )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)rt  rD  	monotonicrr  cancel_background_tasksr   r   r{   rF   rr  rv  ri  r  )
r  r   rN   rw  r  suffix
started_at	cancelledr  disconnecteds
             r.   _bounded_adapter_teardownz'GatewayRunner._bounded_adapter_teardownb  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)	r`   rz  rD   r1  maxr2  r   r   (_ADAPTER_DISCONNECT_TIMEOUT_SECS_DEFAULTr  r>  r  s      r.   rt  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          S )zBReturn the per-platform connect timeout used during startup/retry.r  r|   r  z;Ignoring invalid HERMES_GATEWAY_PLATFORM_CONNECT_TIMEOUT=%r)	r`   rz  rD   r1  r  r2  r   r   &_PLATFORM_CONNECT_TIMEOUT_SECS_DEFAULTr  s      r.   _platform_connect_timeout_secsz,GatewayRunner._platform_connect_timeout_secs  s    iA2FFLLNN 		))** 3(((    Q     65r  is_reconnectr  c                :  K   |                                  }|dk    r|                    |           d{V S 	 t          j        |                    |          |           d{V S # t          j        $ r!}t	          |j         d|dd          |d}~ww xY w)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 grr  )r  connectr  r  TimeoutErrorr{   )r  r   rN   r  r  r   s         r.   _connect_adapter_with_timeoutz+GatewayRunner._connect_adapter_with_timeout  s       5577a<< lCCCCCCCCC	 )\::G          # 	 	 	>HHGHHHH 	s   /A* *B9BB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   rN   s      r.   %_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(   )r  r  s    r.   should_exit_cleanlyz!GatewayRunner.should_exit_cleanly  s    !!r0   c                     | j         S r(   )r  r  s    r.   should_exit_with_failurez&GatewayRunner.should_exit_with_failure  s    &&r0   c                     | j         S r(   )r  r  s    r.   exit_reasonzGatewayRunner.exit_reason  s      r0   c                     | j         S r(   )r  r  s    r.   	exit_codezGatewayRunner.exit_code  s
    r0   sourcec           	         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.r  NrG   rp  Fr   get_active_profile_namer  group_sessions_per_userTthread_sessions_per_user)r  r  rw  )r   r  _generate_session_keyr@   rC   rF   r}   rw  hermes_cli.profilesr  r  )r  r  r  rG   _profiler  s         r.   _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   user_idz(Failed to read Telegram topic mode stateTr   )rN   rx  TELEGRAMr+  r}   is_telegram_topic_mode_enabledrC   r   r  rF   r   rr  )r  r  
session_dbr>  s       r.   _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|   r;   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|   rN   rx  r  r+  r  rC   r  _TELEGRAM_GENERAL_TOPIC_IDSr  r  tids      r.   _is_telegram_topic_root_lobbyz+GatewayRunner._is_telegram_topic_root_lobby$  sb    ?h///63Ct3K3K50088 	5&"(b))d666r0   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      r.   _is_telegram_topic_lanez%GatewayRunner._is_telegram_topic_lane-  ss    ?h///63Ct3K3K50088 	5&"(b)) 	cT===5tr0   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  rC   r   rD  rz  rB   #_TELEGRAM_LOBBY_REMINDER_COOLDOWN_Sr  r  r   _timer@  lasts         r.   $_should_send_telegram_lobby_reminderz2GatewayRunner._should_send_telegram_lobby_reminder:  s     t:;; 	2/1D,fn*++ 	4oo/33GSAA:@@@547(1tr0   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    r.   "_telegram_topic_root_lobby_messagez0GatewayRunner._telegram_topic_root_lobby_messageN  s    *	
 	
r0   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    r.    _telegram_topic_root_new_messagez.GatewayRunner._telegram_topic_root_new_messageW  s    W	
 	
r0   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     r.   _telegram_topic_new_headerz(GatewayRunner._telegram_topic_new_header`  s,    ++F33 	49	
 	
r0   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   r  r  r  r3  )r}   r   r  bind_telegram_topicrC   r  r  r3  )r  r  session_entryr  s       r.   _record_telegram_topic_bindingz,GatewayRunner._record_telegram_topic_bindingj  s     T=$77
V^6;KFZ
;;
&&''&*++,"--%1$/ 	' 	
 	
 	
 	
 	
r0   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  r  rF   r   rr  )r  r  r  rJ  s       r.   _sync_telegram_topic_bindingz*GatewayRunner._sync_telegram_topic_binding}  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  r  )rN   rx  r  r+  r   r  r  rC   r  r  r}   %list_telegram_topic_bindings_for_chatrF   r   rr  rB   )	r  r  inboundis_lobbyr  bindingsr  b	recovereds	            r.   !_recover_telegram_topic_thread_idz/GatewayRunner._recover_telegram_topic_thread_id  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r  )r  rF   dataclassesr4  )r  r  r  s      r.   !_normalize_source_for_session_keyz/GatewayRunner._normalize_source_for_session_key  sa    (	>>vFFII 	 	 	MMM	M"6Y????s    ''r  r  r	  r  r	  c          	      F   |}|s+|)	 |                      |          }n# t          $ r d}Y nw xY wt          |          }|r|                     |           |r| 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||           nTt                              d|pd|| j        r.t          | j        
                                          dd         n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        r5t/          |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t          | dd          }|_|sO|                    |pd          p|                    d          }|r t                              d|pd|           |}n|r|r|||<   ||d<   ||	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  ry  r  rP  rM  rR  )r  ry  r  rP  rM  rR  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=%sr)  z[]z;Runtime provider supplied explicit model override: %s -> %srG   r  parent_chat_idr  r   )get_default_model_for_provideru8   No model configured — defaulting to %s for provider %srB  r  u{   Empty model resolved for session=%s — recovering last-known-good model %s (config read likely returned empty; see #35314))r  rF   r  !_rehydrate_session_model_overrider=  rB   rc  r   rr  rq  r  r^  r   ri  r}   r   rC   r  r  r  rN   r  r  ra  _apply_session_model_overridehermes_cli.modelsr  r   )r  r  r  r	  resolved_session_keyr  r  override_modeloverride_runtimeruntime_kwargsruntime_modelrQ  r   r  r  chch_runtime_modelr  
_last_good
_recovereds                       r.   _resolve_session_agent_runtimez,GatewayRunner._resolve_session_agent_runtime  s3     +# 	,(:,'+'C'CF'K'K$$ , , ,'+$$$, '{33 	I223GHHHNbl40445IJJJhl  	%\\'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$*EBFB_iT27799::2A2>>ei   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       T#94@@
! ('^^,@,FBGG^:>>Z]K^K^
 'NN- -2J	   'E (' =7<J34"'
3n$$s    --!;N 
N*)N*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_overridesry  r  r  rO  rP  r   rQ  rR  rM  rS  )r  rX  	signaturer  Nrequest_overridesr  )r  r  rB   rq  tupler}   rF   )	r  r  r  r  r  rX  routeservice_tierr  s	            r.   _resolve_turn_agent_configz(GatewayRunner._resolve_turn_agent_config}  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r3  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  rP  _fallback_activatedF)r  r  rP  fallback_activec                 "    i | ]\  }}|d v	||S ))Nr|   r  r  s      r.   r  z@GatewayRunner._sync_session_model_from_agent.<locals>.<dictcomp>  s(    KKKDAqq
7J7J1a7J7J7Jr0   model_configgateway_runtimec              3   P   K   | ] \  }}                     |          |k    V  !d S r(   rB   )r,   r  r  r  s      r.   r/   z?GatewayRunner._sync_session_model_from_agent.<locals>.<genexpr>  sK       . .041##A&&!+. . . . . .r0   )r  z-Failed to sync gateway session model metadataTr   )r  r}   r   r  r  get_sessionrB   r  r  rF   r@   rA   rB  update_session_metarQ  r   rr  )r  r3  r@  r  rX  dbrowcurrent_model
raw_configrG   r  s             @r.   _sync_session_model_from_agentz,GatewayRunner._sync_session_model_from_agent  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ctxc                    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   )rC   rB   r  emitrF   r   rr  )r  r  r  s      r.   _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}   rc   r  r  create_task$_handle_adapter_fatal_error_detachedre   ro  rW  shield)r  r   tasksr   s       r.   _handle_adapter_fatal_errorz)GatewayRunner._handle_adapter_fatal_error  s       4d;;=035ED-"4#L#LW#U#UVV		$u}--- nT"""""""""""r0   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 unexpectedlyr  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_implrF   r   r   rN   r{   r}   fatal_error_retryabler  is_setr  r  r  stop)r  r   rN   shutdown_eventstrandeds        r.   r  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                  }|rW|j        | j        vrI|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t1          | j                             d S d S d S )NzDIgnoring stale fatal error from a superseded %s adapter instance: %sr4  zFatal %s adapter error (%s): %srU  relay_disabledr  retryingfatalplatform_state
error_codeerror_messager   rG   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  rB   rN   r   rr  r{   fatal_error_coder  fatal_error_messager  _update_platform_runtime_statusr   r  ru  rG   r  r  rD  rz  ri  r  r  r  r   r   )r  r   existingr  rt  s        r.   r  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 ( 	"k3778HIIO 	7#34;Q#Q#Q- !"&."2"2< <&w'78
 ;$*  
 } 	T%; 	 ' ; d?dD, h*.'rssssfggg))++ 	4#9 	 NN' D*++	    	 	 	 	r0   c                 T    d| _         || _        | j                                         d S NT)r  r  r  rc   )r  rJ  s     r.   _request_clean_exitz!GatewayRunner._request_clean_exit  s-    !"  """""r0   c                 *    t          | j                  S r(   )r   r  r  s    r.   _running_agent_countz"GatewayRunner._running_agent_count  s    4'(((r0   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    r.   _active_work_countz GatewayRunner._active_work_count  s@     %%''))++,((**+	
r0   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)r  r*  r   rF   )r  r*  s     r.   r&  z$GatewayRunner._active_cron_job_count  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}   rB   rx  r*  r   r  r0  rF   )r  r   helpers      r.   r'  z#GatewayRunner._active_api_run_count  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(   )rp  )r,   r   s     r.   r/   zHGatewayRunner._scale_to_zero_has_live_background_work.<locals>.<genexpr>  s,      <<61688|<<<<<<r0   Tr   )active_countz+scale-to-zero async-delegation check failedr   r  z"scale-to-zero bg-work check failedF)rb  r  tools.async_delegationr0  rF   r   rr  r<  r  has_any_activepending_watchers)r  r0  r  s      r.   '_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_secondsr  scale_to_zeroidle_timeout_minutes)gateway.scale_to_zeror6  r?   r@   rA   rB   rF   )r  r6  r>  user_cfgr  stzs         r.   #_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_guardr  Nr?  max_restartswindow_seconds)
r  r?  DEFAULT_MAX_RESTARTSDEFAULT_WINDOW_SECONDSr?   r@   rA   rB   r0  rF   )r  _rlgr@  rA  r:  r  rlgs          r.   _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  Fr}   r,   r  pcs      r.   r  z;GatewayRunner._scale_to_zero_should_arm.<locals>.<listcomp>  s.    ___uq"YX]A^A^____r0   N)r  relay_only_or_absentwake_url)
gateway.relayrI  r9  rJ  rK  rL  rG   r  r  rF   )r  rI  rJ  rK  rL  r  rR  s          r.   _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   rH  )rJ  rK  Nc                 X    g | ]'\  }}t          |d d          t          |d|          (S )r  Fr{   rN  rO  s      r.   r  zEGatewayRunner._log_scale_to_zero_not_armed_reason.<locals>.<listcomp>:  sJ       !Ar"2y%887A..  r0   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.nonerc   MISSINGz.scale-to-zero: not-armed reason logging failedTr   )rS  rI  r9  rJ  rK  rG   r  r  rF   r   ri  rr  )r  rI  rJ  rK  r  active
relay_onlyrR  s           r.   #_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)r9  r]  r$  rD  r  r<  r4  )r  r]  s     r.   _scale_to_zero_is_idlez$GatewayRunner._scale_to_zero_is_idleT  sk    111111w $ 9 9 ; ;'+y{{T5J'J!%!I!I!K!K%)%Q%Q%S%S	
 
 
 	
r0   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)rD  r  r}   _update_runtime_statusrF   r   rr  r  r  s    r.    _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   rx  N)gateway.platforms.baserx  rF   r  rB   RELAY)r  rx  s     r.   _relay_adapter_for_dormancyz)GatewayRunner._relay_adapter_for_dormancyo  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  sleepr|  r  rD  r  rb  rk  r}   r   r   ri  r<  re  rF   rr  iscoroutiner  rm  )r  rl  r   rn  r.  s        r.   _scale_to_zero_watcherz$GatewayRunner._scale_to_zero_watcherw  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    r.   _status_action_labelz"GatewayRunner._status_action_label  s     3CyyCr0   c                     | j         rdndS )N
restartingshutting downrv  r  s    r.   _status_action_gerundz#GatewayRunner._status_action_gerund  s    #6K||OKr0   c                 "    | j         o| j        dv S )N>   queuesteer)r  r  r  s    r.   _queue_during_drain_enabledz)GatewayRunner._queue_during_drain_enabled  s     &V4+@DV+VVr0   queued_eventr  c                     |dS t          |dd          }|dS t          | dd          }|	i }|| _        ||v r+|                    |g                               |           dS |||<   dS )z6Append a /queue event to the FIFO chain for a session.Nr  rC  )r}   rC  
setdefaultrb   )r  r  r  r   pending_slotqueued_eventss         r.   _enqueue_fifozGatewayRunner._enqueue_fifo  s    ?Fw(;TBBF&6== M"/D,&&$$["55<<\JJJJJ(4L%%%r0   pending_eventc                 R   t          | dd          }|s|S |                    |          }|s|S |                    d          }|s|                    |d           ||S |t          |d          r||j        |<   n*|                    |g                               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.
        rC  Nr   r  )r}   rB   r   r   r  r  rh   )r  r  r   r  r  overflownext_queueds          r.   _promote_queued_eventz#GatewayRunner._promote_queued_event  s    "  &6== 	!   $$[11 	!  ll1oo 	1k4000 774G#H#H5@G%k22 $$["55<<QLLLr0   rw  c                    t          | dd          pi }t          |                    |g                     }||t          |di           v r|dz  }|S )u=   Total pending /queue items for a session — slot + overflow.rC  Nr  rZ   )r}   r   rB   )r  r  r   r  r   s        r.   _queue_depthzGatewayRunner._queue_depth  sb    &6==CM%%k26677;''CVXZ2[2[#[#[QJEr0   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}   rC   r   )r  r   s     r.   _is_goal_continuation_eventz)GatewayRunner._is_goal_continuation_event  s5     }fm<<B4yy##$STTTr0   c                    d}|t          |dd          nd}t          |t                    rE|                    |          }|                     |          r|                    |d           |dz  }t          | dd          }t          |t                    rn|                    |          pg }|rUg }|D ]2}	|                     |	          r|dz  }|                    |	           3|r|||<   n|                    |d           |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  rZ   rC  )r}   r@   rA   rB   r  r   rb   )
r  r  r   removedr  r  r  r  keptr  s
             r.   !_clear_goal_pending_continuationsz/GatewayRunner._clear_goal_pending_continuations  s>    FMFYww(;TBBB_clD)) 	(,,[99M//>>   d3331&6==mT** 	9$((55;H 
9$, 2 2L77EE 21L1111 915M+..!%%k4888r0   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   GoalManagerr3  z2goal continuation: active-state recheck failed: %sN)hermes_cli.goalsr  	is_activerF   r   rr  )r  r3  r  r   s       r.   _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(  rF   )r  r  r  r  s       r.   re  z$GatewayRunner._update_runtime_status7  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(  rF   )r  r  s     r.   _persist_active_agentsz$GatewayRunner._persist_active_agentsC  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.ro  )r  r   ri  r(  re  r  s    r.   _enter_external_drainz#GatewayRunner._enter_external_drainc  sc     & 	F&*#M##%%	
 	
 	
 	##J/////r0   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.rd  )r  r  r  r   ri  re  r  s    r.   _exit_external_drainz"GatewayRunner._exit_external_drainw  s     * 	F&+#> 	 	 KK:   F@	
 	
 	
 	##I.....r0         ?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  r  r  r  r  r  rm  rF   r   rr  rp  )r  rl  r  r   s       r.   _drain_control_watcherz$GatewayRunner._drain_control_watcher  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r  r  r  r  c                T    	 ddl m}  |||||           d S # t          $ r Y d S w xY w)Nr   r  )rN   r  r  r  )r  r  rF   )r  rN   r  r  r  r  s         r.   r  z-GatewayRunner._update_platform_runtime_status  sm    		;;;;;;  !-%+	       	 	 	DD	s    
''rJ  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  r  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}   rB   r1  r  r{   rF   r   r   )r  rN   rJ  ri  s       r.   _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  r  r  u,   %s resumed — retrying on next watcher tickT)
r}   rB   r   rD  rz  r  r{   rF   r   ri  )r  rN   ri  s      r.   _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: %sr  r9  r:  Nz3Prefill messages file must contain a JSON array: %sz+Failed to load prefill messages from %s: %s)r`   rz  r  rC   rB   r   r   
expanduseris_absoluter  rf   r   r   rI  r  loadr@   rq  rF   )	file_pathrQ  rg   rP  rH  r  s         r.   r  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@  system_promptr  )r`   rz  r  rC   r   rD   )promptrQ  s     r.   r  z+GatewayRunner._load_ephemeral_system_prompt)  s^     ;R@@ 	M*,,73"EEEKLLRRTTTr0   )r	  r  r  r  r  c                    t          | dd          }|r$t          |||||          }|r|j        r|j        S t          |          S )zFResolve model for this channel: channel_overrides else global default.rG   Nr  )r}   r  r  r  )r  rN   r   r	  r  r  rG   r  s           r.   _resolve_model_for_channelz(GatewayRunner._resolve_model_for_channel6  si     x.. 		&,##  H  &HN &~%%k222r0   r  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.
        rG   Nr  r|   r  )r}   r  r  rD   )r  rN   r   r  r  rG   r  s          r.   _get_system_prompt_for_channelz,GatewayRunner._get_system_prompt_for_channelM  s     x.. 		>,##  H  >H2 > .4";;===t7>>D"Dr0   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)rj  r  r  )r  r  rQ  s      r.   r  z$GatewayRunner._load_reasoning_configi  s4     	>=====*,,''U333r0   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  )	shlexrC   rD   r4  r1   r2  rb   r2   rE   )r  r  r   tokenspersist_globalvalue_tokensrx  s          r.   _parse_reasoning_command_argsz+GatewayRunner._parse_reasoning_command_argsz  s     	8>r""((**225$?? 	9	" U[&&FF 	" 	" 	"ZZ\\FFF	"  	+ 	+E
""!%##E****xx%%++--3355~EEs   A A32A3r  r  r  c                    |}|s+|)	 |                      |          }n# t          $ r d}Y nw xY wt          | di           pi }|r||v r||         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.
        Nr?  )r  rF   r}   r  )r  r  r  r  r  r  s         r.   !_resolve_session_reasoning_configz/GatewayRunner._resolve_session_reasoning_config  s       +# 	,(:,'+'C'CF'K'K$$ , , ,'+$$$, D"@"EEK	 	3$8I$E$E122**5111    --reasoning_configc                     |sdS t          | d          si | _        || j                            |d           dS t          |          | j        |<   dS )z3Set or clear the session-scoped reasoning override.Nr?  )r   r?  r   rA   )r  r  r  s      r.   _set_session_reasoning_overridez-GatewayRunner._set_session_reasoning_override  sm      	Ft;<< 	302D-#-11+tDDDDD=ABR=S=SD-k:::r0   c                     |}|s+|)	 |                      |          }n# t          $ r d}Y nw xY wt          | di           pi }|r||v r||         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.
        Nr@  )r  rF   r}   r  )r  r  r  r  r  s        r.   _resolve_session_service_tierz+GatewayRunner._resolve_session_service_tier  s      +# 	,(:,'+'C'CF'K'K$$ , , ,'+$$$, D"CRHHNB	 	3$8I$E$E122&&(((r  re  c                     |sdS d| j         vri | _        |r| j                            |d           dS || 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).
        Nr@  )__dict__r@  r   )r  r  r  re  s       r.   "_set_session_service_tier_overridez0GatewayRunner._set_session_service_tier_override  sc      	F,DMAA 46D0 	M044[$GGGGG@LD0===r0   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  >   rC  rW  normalr  standardN>   r<   fastpriorityr  z#Unknown service_tier '%s', ignoring)r  rC   r   rD   rE   r   r   )rQ  r>  r{   s      r.   r  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tr0   c                  ^    t                      } t          t          | dd          d          S )z<Load show_reasoning toggle from config.yaml display section.r  show_reasoningFr  )r  r(  r   )rQ  s    r.   r  z"GatewayRunner._load_show_reasoning   s9     +,,C$455
 
 
 	
r0   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  r}  r~  r  )r`   rz  rD   rE   r  rC   r   )r  rQ  s     r.   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{r0   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  r}  )	r`   rz  rD   rE   r  rC   r   r  r  )legacyrQ  
input_modes      r.   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[@r0   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)r`   rz  rD   r  rC   r   r  r  r1  r=  r2  r   r   )r>  rQ  r{   s      r.   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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_notificationsFrC  >   Nr|   rB  >   rB  rC  r  r.  zBUnknown background_process_notifications '%s', defaulting to 'all')	r`   rz  r  r   rC   rD   rE   r   r   )r  rQ  r>  valids       r.   #_load_background_notifications_modez1GatewayRunner._load_background_notifications_modeA  s     y:B?? 	 .00C#y*LMMCe||J&&3xx$$&&,,..111uNNT   5r0   c                     	 ddl } t          dz  }|                                rXt          |d          5 }|                     |          pi }ddd           n# 1 swxY w Y   |                    di           pi S n# t          $ r Y nw xY wi S )z>Load OpenRouter provider routing preferences from config.yaml.r   Nr8  r9  r:  provider_routing)rH  r  rf   rI  rJ  rB   rF   )rj  rk  rl  rQ  s       r.   r  z$GatewayRunner._load_provider_routing]  s    	#m3H   =(W555 1,,r**0bC1 1 1 1 1 1 1 1 1 1 1 1 1 1 1ww1266<"<=  	 	 	D		s4   3A= AA= AA=  A!A= =
B
	B
c                     	 ddl } t          dz  }|                                rSt          |d          5 }|                     |          pi }ddd           n# 1 swxY w Y   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.
        r   Nr8  r9  r:  )rH  r  rf   rI  rJ  r   rF   )rj  rk  rl  rQ  fbs        r.   r  z"GatewayRunner._load_fallback_modelk  s    
	#m3H   (W555 1,,r**0bC1 1 1 1 1 1 1 1 1 1 1 1 1 1 1',, I 	 	 	D	ts4   3A8 AA8 AA8  A!A8 8
BBc                    	 ddl }t          dz  }|                                sd| _        | j        S t	          |d          5 }|                    |          pi }ddd           n# 1 swxY w Y   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   Nr8  r9  r:  zRfallback_providers refresh: config.yaml read failed; keeping last known-good chainTr   )
rH  r  rf   r  rI  rJ  rF   r   rr  r   )r  rj  rk  rl  rQ  s        r.   _refresh_fallback_modelz%GatewayRunner._refresh_fallback_model  s+   	(#m3H??$$ ,'+$++h111 -Rll2&&,"- - - - - - - - - - - - - - - 	( 	( 	(LL0:>     ''''	(  2#66>$##s:   /A3 A3 A'A3 'A++A3 .A+/A3 3-B#"B#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   r  F_fallback_chain_unavailable_fallback_keys)rq  r}   rD  rz  r  r  _fallback_indexre  )r@  r  	new_chainrate_limited_until	old_chainunavailables         r.   _apply_fallback_chain_to_agentz,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 $!!##### "!$ $r0   c                 H    d | j                                         D             S )Nc                 ,    i | ]\  }}|t           u||S r  )_AGENT_PENDING_SENTINEL)r,   r  r@  s      r.   r  z:GatewayRunner._snapshot_running_agents.<locals>.<dictcomp>  s4     
 
 
"U333 333r0   )r  r  r  s    r.   _snapshot_running_agentsz&GatewayRunner._snapshot_running_agents  s2    
 
&*&:&@&@&B&B
 
 
 	
r0   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_sessionsrG   N)hermes_cli.active_sessionsr  r}   rF   )r  r  s     r.   _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 |t          | di           v rdS t          t          | di                     }||k     rdS d| d| dS )zKReturn a user-facing rejection when starting a new session exceeds the cap.Nr  z'Hermes is at the active session limit (r%  z+). Try again when another session finishes.)r  r}   r   )r  r  max_sessionsr0  s       r.   _active_session_limit_messagez+GatewayRunner._active_session_limit_message  s    88::4'$(92>>>>474):B??@@,&&47l 7 7\ 7 7 7	
r0   c                    |t          | di           v 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  r  Nr   )try_acquire_active_sessionr  gateway:rG   r   r|   r  )rN   r   r  )r3  surfacerG   r~   z'Failed to claim active session slot: %s)	r}   r  r  r  rN   r{   rF   r   r   )r  r  r  local_limit_messager  rN   r   s          r.   _claim_active_session_slotz(GatewayRunner._claim_active_session_slot  s)    '$(92>>>>:"@@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)r  r}   r@   rq  r  rc   r   rF   )r  childrenlocks      r.   _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).
        r  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AttributeErrorr=  rF   r   r   get_compression_lock_holderrC   r   )r  r  r  r3  r  raw_dbholders          r.   "_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.Nr3  )_lock_ensure_loaded_locked_entriesrB   r}   )r  r  rc  s      r.   r  z1GatewayRunner._lookup_session_id_under_store_lock\  s       	< 	<//111!*..{;;E	< 	< 	< 	< 	< 	< 	< 	< 	< 	< 	< 	< 	< 	< 	< 6;5FwulD111DPs   /AA
A    rr  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  rv  r  
merge_textrw  uJ   Dropping busy-mode follow-up for session %s — pending queue at cap (%d).)_adapter_for_sourcer  r}   r@   rA   rB   r  rw  rv  r   r  r  TEXTr  _BUSY_QUEUE_MAX_PENDINGr   r   r  )r  r  rr  r   r  r  s         r.   _queue_or_replace_pending_eventz-GatewayRunner._queue_or_replace_pending_eventm  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7r0   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 | j!        "                    |          }| j#        }tA          | dd          }|j$        tJ          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|j        pd                                }|oA|j$        tJ          j&        k    o,|j)         o$|j*         o|d uo|tV          uotY          |d          }|rY	 t[          |.                    |                    }n5# t>          $ r(}t                              d"||           d}Y d }~nd }~ww xY w|sd}n|dk    r|j$        tJ          j&        k    r|j)        s|j*        s||tV          urtA          |d#d          du rtY          |d$          rr	 t[          |/                    |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|tV          ur	 |j        }!tA          |d&d           pg }"| 0                    |          r0| 1                    |||j        |j        pdd'(           d {V \  }!}#n|!s|"rte          |          }!|3                    |!           n# t>          $ r Y nw xY wth          j5        "                    d)d*                                          d*k    }$|$st          6                    d+|           dS d,}%to          j7                    }&| j8        "                    |d
          }'|&|'z
  |%k     rdS d
d-l9m:}( tw          |j        j                  })|rth          j5        "                    d.          }*|*)|*                                                                d/v }+n't[           |(ty                      |)d0d                    }+|+st          6                    d1|           dS |&| j8        |<   g },t[           |(ty                      tw          |j        j                  d2d                    }-|-r|r|tV          ur	 |=                                }.|."                    d3d
          }/|."                    d4d
          }0|."                    d5          }1| j>        "                    |d
          }2|2r3t          |&|2z
  d6z            }3|3d
k    r|,@                    |3 d7           |0r|,@                    d8|/ d|0            |1r|,@                    d9|1            n# t>          $ r Y nw xY w|,rd:d;A                    |,           d<nd}4|rd=|4 d>}n.| rd?|4 d@}n%|r	|rdA|4 dB}n|r	|rdC|4 dB}n|rdD|4 dE}ndF|4 dG}	 d
dHlBmC}5mD}6mE}7mF}8 ty                      }9 |7|9|5          s5|rd}:n|rd}:n| rd$}:nd}:| dI |6|:           } |8t          dJz  |5           n2# t>          $ r%};t          6                    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          6                    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=%sr4  T   ⏳ Gateway 2    — queued for the next turn after it comes back.   ⏳ Gateway is - and is not accepting another turn right now.r,  r   r   reply_tor~   r   has_blocking_approvalr|   >      👍yokr=   okayapproveconfirm>      👎nnodenyrn  reject>   approve alwaysalwaysalways approver<  >   approve sessionsession approvesessionr@  r4  r9  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  r}  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)z'Gateway steer failed for session %s: %s_supports_active_turn_redirectredirectz*Gateway redirect failed for session %s: %sr  zVoice-busy-interruptlog_contextr  r>   z"Busy ack suppressed for session %sr{  r  r  >   r;   r<   r=   r>   r  z(Busy steer ack suppressed for session %sbusy_ack_detailapi_call_countmax_iterationscurrent_toolr  z min elapsed
iteration z	running:  (r   ry  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_gatewayis_seen	mark_seenr   r8  z.Failed to apply busy-input onboarding hint: %szFailed to send busy-ack: %s)H_is_user_authorizedr  r   r   r  	user_namerN   r{   r  r#  r  _thread_metadata_for_sourcer  r&  r{  _send_with_retryr   rx  r  r+  r  
message_idtools.approvalr/  r   rD   rE   _handle_approve_command_handle_deny_commandri  _unwrap_ephemeralrF   r}   r  rB   r  rv  r  r$  r  r  r  rq  r  r   r   r~  rC  _pending_event_audio_paths"_transcribe_and_echo_pending_voicer  r  r`   ra   rr  rD  r  r  r  r  r?   get_activity_summaryr  r0  rb   r2   agent.onboardingrL  rM  rN  rO  r  )=r  rr  r  r   reply_anchorthread_metar   r/  	_raw_text_approve_words_deny_words_approval_handler_normalized_args_verb_synth_reply_adapter_text_eph_ttl_anchorr  effective_moder  demoted_for_subagentsdemoted_for_compressionsteered
redirected
steer_text	can_steerr   is_queue_modeis_steer_modeis_redirect_mode_interrupt_text_media_urlsr  r  _BUSY_ACK_COOLDOWNr@  last_ackr  r  steer_ack_envsteer_ack_enabledstatus_partsbusy_ack_detail_enabledsummary	iterationmax_iterrI  start_tselapsed_minstatus_detailrL  rM  rN  rO  	_user_cfg
_hint_mode_onb_errr  s=                                                                r.   #_handle_active_session_busy_messagez1GatewayRunner._handle_active_session_busy_message  sh      ''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,00==. '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$$**1133J 4&+*::4((4 ))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$((a88>...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),+&
 "&##$&&$U\%:;;!	 #
 #
 # 	} 	Ne9e9e'<<>>#KK(8!<<	";;'7;;&{{>::266{AFF 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<+"S 
T S;;T  ;V 
W&W		WBZ 
Z('Z(Cd! !
d.-d.Ag" "
h,hhBk 
lk>>l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   } j        s(                                 s                                 rt          j                                                    |k     r| |             t          j	        d	           d {V   j        s(                                 s                                 r)t          j                                                    |k     |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  ro  )r  get_running_looprD  r$  r&  r'  re  )
r   r@  r0  
cron_count	api_countlast_active_countlast_api_countlast_cron_countlast_status_atr  s
        r.   _maybe_update_statusz@GatewayRunner._drain_active_agents.<locals>._maybe_update_statusG  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0r0   r   Tr   皙?F)
r  r$  r&  r'  r   r  r  r  rD  rp  )
r  r  snapshotr  deadline	timed_outr  r  r  r  s
   `     @@@@r.   _drain_active_agentsz"GatewayRunner._drain_active_agents@  su     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> $		% ..00		% --//			% (**//11H<<  """-$$$$$$$$$ $		% ..00		% --//			% (**//11H<<
 %&& 2D//11222D..0011 	
 	4((((""r0   c                 8   t          | j                                                  D ]r\  }}|t          u r	 |                    |           t
                              d|           A# t          $ r%}t
                              d|           Y d }~kd }~ww xY wd S )Nz8Interrupted running agent for session %s during shutdownz-Failed interrupting agent during shutdown: %s)rq  r  r  r  r  r   rr  rF   )r  rJ  r  r@  r  s        r.   _interrupt_running_agentsz'GatewayRunner._interrupt_running_agents{  s    "&t';'A'A'C'C"D"D 	Q 	QK///Q'''WYdeeee Q Q QLaPPPPPPPPQ	Q 	Qs   0A((
B2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.
        Nry  rz  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     — r  originz>Failed to load session origin for shutdown notification %s: %srN   r   r  z^Shutdown notification suppressed for active session: %s has gateway_restart_notification=falserT  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=falserw  z>Failed to send shutdown notification to home channel %s:%s: %sz0Sent shutdown notification to home channel %s:%s)"r  r  r  rc   r}   async_session_store_ensure_loadedr  r  rB   rF   r   rr  _get_cached_session_sourcerN   r{   rC   r   r  r/  rx  r  rG   r  gateway_restart_notificationri  _thread_metadata_for_targetr   re   r  r  rq  r  get_home_channel)r  rY  restart_sourceactionhintr\  notifiedr  r  rc  r  platform_strr   r  _parsed	dedup_keyrN   r   r  r  restart_platformrestart_chat_idrestart_thread_idr~   r.  r  r6  s                              r.   #_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           	      j  K   |                                 D ]}	 t          |dd           }t          |dd           }t          |          r_t          |t                    rJ|rHt          |dd           }t          |          r	  ||           n# t
          $ r Y nw xY w ||           n2# t
          $ r%}t                              d|           Y d }~nd }~ww xY w	 ddlm	}  |dt          |dd           d	d
           n# t
          $ r Y nw xY w| 
                    |d           d {V  d S )N_flush_messages_to_session_db_session_messages)_drop_trailing_empty_response_scaffoldingz$Shutdown transcript flush failed: %sr   invoke_hookon_session_finalizer3  r  ru  r3  rN   rJ  zshutdown finalizer   )valuesr}   r   r@   rq  rF   r   rr  hermes_cli.pluginsr  !_cleanup_agent_resources_off_loop)r  r  r@  _flushr  _strip_e_invoke_hooks           r.   _finalize_shutdown_agentsz'GatewayRunner._finalize_shutdown_agentsL  s     "))++ 1	 1	E I (GNN$+E3F$M$M!F## .
3Dd(K(K .Pa .
 %JD F  '' !!"F#45555( ! ! ! D!F,--- I I ICRHHHHHHHHI	JJJJJJ)&ulDAA&%	         882 9          _1	 1	sN   A(B,BB,
BB,BB,,
C6CC$D
DDexecutor_taskc                 ~    |dS ||                                 rdS |r| j                            |          |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)rp  r  rB   )r  r  r@  r  s       r.   &_should_emit_long_running_notificationz4GatewayRunner._should_emit_long_running_notification  sW     =5$););)=)=$5 	4/33K@@MM5tr0   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: %srK  ry  r|   r  )r  r  rm  rF   r   rr  r  )r   r@  r   r   r  s    r.   _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_tasksr%   N)r  r  r}   rc   r  re   ro  rW  )r  r   r@  r   r  r   r  s   ````   r.   &_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}-----r0   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).
        Nru  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)rK  ry  r|   z,Agent resource cleanup%s failed: %s (#53175))r   _end_session_on_closerF   r  r  _run_in_executor_with_context_cleanup_agent_resources_CLEANUP_TIMEOUT_Sr  r   r   )r  r@  r   cleanup_excs       r.   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                    |dS 	 t          |d          rPt          |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_providerr  closer   )cleanup_stale_async_clients)	r   r}   r@   rq  r  rF   r  agent.auxiliary_clientr  )r  r@  session_messagesr  s       r.   r  z&GatewayRunner._cleanup_agent_resources  s*   =F	u899 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	s6   A A' '
A43A48$B 
B*)B*.C   
CCr  z.restart_failure_countsactive_session_keysc                 R   ddl }t          | j        z  }	 |                                r" |j        |                                          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   NrZ   rM  )	r  r  _STUCK_LOOP_FILErf   r  r  rF   rB   r%  )r  r  r  rg   counts
new_countsr  s          r.   !_increment_restart_failure_countsz/GatewayRunner._increment_restart_failure_counts  s     	d33	59[[]]JZTZ 0 0111FF 	 	 	FFF	 
& 	5 	5C$jja0014JsOO	dJt<<<<<< 	 	 	DD	s#   8A AAB 
B&%B&c                     ddl }t           j        z  }|                                sdS 	  |j        |                                          }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   Nc                 0    g | ]\  }}|j         k    |S r  )_STUCK_LOOP_THRESHOLD)r,   r  r  r  s      r.   r  z>GatewayRunner._suspend_stuck_loop_sessions.<locals>.<listcomp>H  s*    VVVDAqa4;U6U6Ua6U6U6Ur0   TrZ   u_   Auto-suspended stuck session %s (active across %d consecutive restarts — likely a stuck loop)r  )r  r  r  rf   r  r  rF   r  r  r  rB   	suspendedr   r   _saver   )r  r  rg   r  r  
stuck_keysr  rc  s   `       r.   _suspend_stuck_loop_sessionsz*GatewayRunner._suspend_stuck_loop_sessions5  s    	d33{{}} 	1	TZ 0 011FF 	 	 	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+1D 
DDD3 3
E ?E c                 *   ddl }t          | j        z  }|                                sdS 	  |j        |                                          }||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   NrM  Tr  )	r  r  r  rf   r  r  r%  r   rF   )r  r  r  rg   r  s        r.   _clear_restart_failure_countz*GatewayRunner._clear_restart_failure_countf  s    
 	d33{{}} 	F		TZ 0 011F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    rdd l}ddlm}m} g |d	d
}	|                    d                                          }
t          j                                        }|                    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}t          j                                        }|                    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#   rU   )&windows_detach_flags_without_breakawaywindows_detach_popen_kwargsr  rt  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(),
                )
                r"  rV   rW   rX   rY   r[   -cr  r  env)r  r  r  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     r.   r/   zAGatewayRunner._launch_detached_restart_command.<locals>.<genexpr>  s,      @@Tu{4((@@@@@@r0   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  r  start_new_session),r  r  r'  r   r  r  r`   getpidr  r1  r}   r\   rN   textwraphermes_cli._subprocess_compatr  r  dedentrD   ra   copyr   r   r]   r^   r_   r$  rB   rf   rC   rb   rl   r2   rA   rm   PopenDEVNULLrd   r  r   rg   basenamer0  r   )r  r  r  
hermes_cmdcurrent_pidrestart_after_sr  r  r  cmd_argvwatcherwatcher_envrn   watcher_pythonrq   rt   rx   watcher_argvr   r  r  error_fieldr   	shell_cmd
setsid_bins                            r.    _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_ ` *//++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*>*> % %(% %% % % 	 joo'')4000\\(++
 	VUI6!)!)"&       	*!)!)"&      s=   $I- -
L8,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          }|j        pd                                S # t          $ r Y dS w xY w)Nshowz--property=MainPIDz--valueTr  )capture_outputr   r  r|   )runr  rD   rF   )scope_flagsoutservice_namer  r  s     r.   
_query_pidzBGatewayRunner._launch_systemd_restart_shortcut.<locals>._query_pid[  s    $.." :[ :& :, :-:/8:'+$ )  C
  J,"33555    22s   >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/shr  T)r  r  r  zALaunched systemd planned-restart helper for %s (pid=%s, scope=%s)ra  r  z3Failed to launch systemd planned-restart helper: %s)r\   rN   r`   ra   rB   r  r  r   hermes_cli.gatewayr  rF   r  rC   r  r  r4  r  r  r   ri  rr  )r  r  systemd_runr  r  r  
system_piduser_pidr  systemctl_scopeservice_argr  	unit_namer  r  r  r  s                 @@@r.    _launch_systemd_restart_shortcutz.GatewayRunner._launch_systemd_restart_shortcut4  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;detachedvia_servicer"  r#  c                      j         rdS d _         _         _        d _         d fd}t	          j         |                       _        dS )NFTr%   c                    K   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rt  detached_restartservice_restart)r	  rF   r   r  r  rp  r  )r  r"  r  r#  s    r.   _run_restartz3GatewayRunner.request_restart.<locals>._run_restart  s       \\??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r  )r  r  r  r  r  r  r  )r  r"  r#  r*  s   ``` r.   request_restartzGatewayRunner.request_restart  s    % 	5"&!)$/!%)"	b 	b 	b 	b 	b 	b 	b 	b* %0@@tr0   >   rL  rM  restart_interruptedc                   K   	 |                     |           d{V  t          |di           }t          |t                    r|                    |          nd}|t          j        |           d{V  | j                            |          t          u r| 	                    |           dS dS # | j                            |          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}   r@   rA   rB   r  r  r  r  _release_running_agent_state)r  r   rr  r  session_tasksr   s         r.   _run_startup_resume_eventz'GatewayRunner._run_startup_resume_event  s     	?((/////////#G-=rBBM5?t5T5T^=$$[111Z^DnT********* #''448OOO11+>>>>> POt#''448OOO11+>>>> Ps   A4B2 29C+c                    t          | dd           }|	g }|| _        |                    |           	 |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)Nr  zJQueued inbound message during gateway startup restore: platform=%s chat=%sr4  )
r}   r  rb   r  r   ri  rN   r{   r   rF   )r  rr  r}  r  s       r.   _queue_startup_restore_eventz*GatewayRunner._queue_startup_restore_event  s    6===E*/D'U	\FKK\)/RFOR%%"(7i    
  	 	 	DD	s   AA6 6
BBc           
        K   d}t          | dd          }|dS |r|                    d          }t          |dd          }|                     |          }|:t                              dt          t          |dd          dd                     y	 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   r  Nr  zCDropping startup-restore queued message: adapter unavailable for %srN   r{   _hermes_startup_restore_replayTrZ   )r}   r   r#  r   rr  setattrrF   r/  )r  drainedr}  rr  r  r   s         r.   _drain_startup_restore_queuez*GatewayRunner._drain_startup_restore_queue  s     6===1 	IIaLLEUHd33F..v66GYGFJ==wMM   ?FFFF   ((/////////qLG#  	$ s   B& &
B32B3c                   K   t          t          | dg           pg           }|rbt          j        |ddi d{V }|D ]H}t	          |t
                    r1t                              dt          |          ||j	        f           Ig | _
        |                                  d{V }d| _        |rt                              d|           dS dS )	zCWait for startup auto-resume, then release and drain inbound queue.r  return_exceptionsTNzstartup auto-resume task failedr   Fz;Drained %d inbound message(s) queued during startup restore)rq  r}   r  gatherr@   rF   r   rr  r   r   r  r9  r  ri  )r  r  resultsr.  r8  s        r.   _finish_startup_restorez%GatewayRunner._finish_startup_restore  s     WT#;R@@FBGG 	#NEJTJJJJJJJJG!  fi00 LL9"&v,,8L!M !    ')#99;;;;;;;;,1) 	`KKUW^_____	` 	`r0   c                   K   	 ddl m}m}m}m}m}  |            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	 |^t!          |dd          rM ||	d                    |dz  }t                              d|	d	         |	d         |	d         |	d                    n0 ||	d         t%          t!          |dd          pd                     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_recoverablec           	      J    h | ] }t          |d t          |                    !S r?  )r}   rC   r  s     r.   r  z?GatewayRunner._redeliver_pending_obligations.<locals>.<setcomp>2  s7       017CFF++  r0   N)deliverable_platformszdelivery ledger sweep failedTr   rN   z"obligation %s: unknown platform %robligation_idr   needs_markerr  r   r   r   r~   z)obligation %s: redelivery send raised: %sr  FrZ   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@  rA  rB  rC  rD  r  r  r  rF   r   rr  rx  rB   r   r   r}   ri  rC   r  clear_resume_pending)r  r@  rA  rB  rC  rD  _deliverableclaimedredeliveredr  rN   r   r   r~   r.  send_errr  s                    r.   _redeliver_pending_obligationsz,GatewayRunner._redeliver_pending_obligations  s4      	              ">## 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%"N3#78881$KKK6JYO,c*o	     K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 &A76A7B?CC$E''
F1$FF#BH44&II: J'KK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         j        v r>|
j        }                     |          }|;t                              d|
j        t/          |j        d|j                             	                      |          s!t                              d	|
j                   n8# t          $ r+}t                              d
|
j        |           Y d}~d}~ww xY wt4           j        |
j        <   t7          j                     j        |
j        <                                     t=          dt>          j         |d          }tC          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(   )resume_pendingr  r  resume_reason_AUTO_RESUME_REASONSrN   )r,   rc  rN   r  s     r.   r  zCGatewayRunner._schedule_resume_pending_sessions.<locals>.<listcomp>  sm       #+ "O 0+t/HHH!)U\-Bh-N-N 
 .O-N-Nr0   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   rv  r  rA  r  Fr  rZ   z;Scheduled auto-resume for %d restart-interrupted session(s))+r;  r  r  r  r  r  rF   r   r   r  r?  rF  check_and_recordrr  r   r@  last_resume_marked_at
updated_attotal_secondsr  r  r  r#  r}   rN   rP  r  rD  r  r  r  r  r$  r  r  r2  r  re   ro  rW  r  rb   ri  )r  rN   rE  ro   r   rD  _max_restarts_windowr@  	scheduledrc  markerr  r   rr  r   r  s   ``               r.   !_schedule_resume_pending_sessionsz/GatewayRunner._schedule_resume_pending_sessions~  sJ   . 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	 F	 F	E0DE4DF!sV|&B&B&D&Dv&M&M  D$888\F..v66GK%FOWfoFF  
 //77 NNH)  
     Q%s    7ND !239=D#E$56'')))
 !(-	  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5G??
H4	!H//H4c                 P    | j         p| j        p| j                                        S r(   )r  r  r  r  r  s    r.   _startup_should_abortz#GatewayRunner._startup_should_abort	  s.    # -~-#**,,	
r0   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{  rF   r   rr  r{   ru  r  r  current_taskr  r  r  r  r  r  )r  r   rN   r  	stop_taskrb  s         r.   $_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.c           
      >+   BK   t                               d           	 t          j                     _        n# t
          $ r
 d _        Y nw xY w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}
m}  |
            } ||          }|r5t                               d|           t                               d           n,# t          $ r t                               dd !           Y nw xY w                                  d{V rd S d"}d#}d$}d$}	 dd%lm} t;          d& |                                D                       }t;          d' |                                D                       }n# t          $ r Y nw xY wt?          d( ||z   D                       }t!          j        d)d*                                          d+v pt?          d, ||z   D                       }|s|st                               d-           tA           j                  }|r|!                    d.d/          d         }d}tD          #                                D ]\  }}|j$        |k    r
|d0         } nt           %                    d1||pd2           	 ddlm}	  |	d3|           n# t          $ r Y nw xY w &                    |           d S 	 dd4l'm(}  |             n,# t          $ r t                               d5d !           Y nw xY w	 dd6l)m*}m+}m,}m-}  |              |            r-t                               d7 |                        |             n,# t          $ r t                               d8d !           Y nw xY w	 dd9l.m/} dd:l0m1}   |  |            d;<           n,# t          $ r t                               d=d !           Y nw xY w j2        3                                 	 dd>l4m5}! |!6                                }"|"rt                               d?|"           n2# t          $ r%}#t                               d@|#           Y d}#~#nd}#~#ww xY wtn          dAz  }$|$8                                r@t                               dB           	 |$9                                 n# t          $ r Y ntw xY w	  j:        ;                                 d{V }%|%rt                               dC|%           n2# t          $ r%}#t                               dD|#           Y d}#~#nd}#~#ww xY w	  <                                }&|&rt                               dE|&           n2# t          $ r%}#t                               dF|#           Y d}#~#nd}#~#ww xY wd  _=        g  _>        g  _?        d}'d}(g })g }*t          t           j        dGd;                    }+g }, j        jB        #                                D ]\  }}-                                  d{V r d S |-jC        s+|+rFt          ||-          s6t                               dH|j$                   |,E                    |           s|(d/z  }( F                    ||-          }.|.sk|j$        }/dI t          jH        I                                D             }0|/|0vrt                               dJ|/           nt                               dK|/           |.J                     jK                   |.L                     jM                   |.N                     jO                   |.P                     jQ                   t          |.dLd          }1t          |1          r |1 jS                   |.T                     jU                   |.V                     W                    |.jX                              jY        |._Y        t                               dM|j$                    Z                    |j$        dNddO           	  [                    |.|           d{V }2                     |.|           d{V r d S |2rd|. j\        |<    ]                    |.           |'d/z  }' Z                    |j$        dPddO           t                               dQ|j$                   n*t                               dR|j$                    ^                    |.|           d{V  |.j_        r Z                    |j$        |.j`        rdSndT|.ja        |.jb        O           |.j`        r|*n|)}3|3E                    |j$         dU|.jb                    |.j`        r"|-d/t          jd                    dVz   dW je        |<   n] Z                    |j$        dSddXO           |*E                    |j$         dY           |-d/t          jd                    dVz   dW je        |<   n# t          $ r}#t           %                    dZ|j$        |#            ^                    |.|           d{V   Z                    |j$        dSdt          |#          O           |*E                    |j$         dU|#            |-d/t          jd                    dVz   dW je        |<   Y d}#~#nd}#~#ww xY w                                  d{V r d S 	  g                                 d{V }4|'|4z  }'n# t          $ r}#t          |#          }t           %                    d[|           	 ddlm}	  |	d3|           n# t          $ r Y nw xY wt           _j         &                    |           d; _=        Y d}#~#d; _k        d S d}#~#wt          $ r'}#t           %                    d\|#d !           Y d}#~#nd}#~#ww xY wd; _k        n# d; _k        w xY w|,D ]VBt?          Bfd] jl        I                                D                       }5|5s t                               d^Bj$                   W|'dk    rA|)rd_m                    |)          }t           %                    d`|           	 ddlm}	  |	d3|           n# t          $ r Y nw xY wt           _j         &                    |           d; _=        d S |(dk    r|*rhd_m                    |*          }t                               dat           je                  |           	 ddlm}	  |	dbd           n# t          $ r Y nw xY wt                               dc|(           n4t                               dd           t                               de                                             d{V rd S  j\         jo        _\         p                                 d  _q         r                    df           	 t           dgd          }6|6|6s                                rt          jt        t          t          t           dhdi          j                     _w        t           dkd          }7|79|7x                     jw                    jw        y                    |7jz                   n,# t          $ r t                               dld !           Y nw xY wt           j2        j{                  }8|8rt                               dm|8            j2        |                    dndodp  j\        }                                D             i           d{V  |'dk    rt                               dq|'           	 ddrl~m}9  |9 j\                   d{V }:t          ds |:                    doi           I                                D                       };t                               dt|;           n2# t          $ r%}#t                               du|#           Y d}#~#nd}#~#ww xY w                                  d{V }<|<s?t?          dv tn          dwz  tn          dxz  fD                       r                                  |'dk    rt          j        dy           d{V  t	                      }=t                      }>|=rd  _                                          d{V  |>rA	                      dz           d{V  t                       n# t                       w xY w                                  d{V                                                                      d{V  	 dd>l4m5}! |!j        }?g |!_        t          |?          D ]\  }@}A                     |Af fd{	d||A                    d}           d;~           t                               d|A                    d}                     |@dz  dk    rt          j        d           d{V  n2# t          $ r%}#t           %                    d|#           Y d}#~#nd}#~#ww xY w                      j        d                                 j        d                                 j        d            je        rPt                               dt           je                  dm                    d  je        D                                                        j        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...Nz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: %srB  rU  zuAgent budget: max_iterations=%d (agent.max_turns from config.yaml, or HERMES_MAX_ITERATIONS from .env, or default 90)r  r>   >   r;   r<   r=   r>   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  )detect_compromisedgateway_log_message%szCRun `hermes doctor` on the gateway host for full remediation steps.z1security advisory check failed at gateway startupTr   )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_USERSr%  WECOM_CALLBACK_ALLOW_ALL_USERSr(  BLUEBUBBLES_ALLOW_ALL_USERSr,  r+  r  platform_registryc              3   2   K   | ]}|j         	|j         V  d S r(   )allowed_users_envr,   r  s     r.   r/   z&GatewayRunner.start.<locals>.<genexpr>  sB       ) )()&)#) ) ) ) ) )r0   c              3   2   K   | ]}|j         	|j         V  d S r(   )r9  r  s     r.   r/   z&GatewayRunner.start.<locals>.<genexpr>  s@       + +$%?++ + + + + +r0   c              3   >   K   | ]}t          j        |          V  d S r(   )r`   rz  r-  s     r.   r/   z&GatewayRunner.start.<locals>.<genexpr>  s;       
 
BIaLL
 
 
 
 
 
r0   r4  r|   >   r;   r=   r>   c              3   h   K   | ]-}t          j        |d                                           dv V  .dS )r|   >   r;   r=   r>   N)r`   rz  rE   r-  s     r.   r/   z&GatewayRunner.start.<locals>.<genexpr>  s\       e
 e
 Ia""$$(<<e
 e
 e
 e
 e
 e
r0   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}  rZ   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 startupr  )register_from_configF)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: %srp  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     r.   r  z&GatewayRunner.start.<locals>.<setcomp>  s    !Q!Q!Qa!'!Q!Q!Qr0   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...
connectingr  r2  u   ✓ %s connectedu   ✗ %s failed to connectr  r  r  r{  r  z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_map_skippeds     r.   r/   z&GatewayRunner.start.<locals>.<genexpr>&   s<       ' '  L(' ' ' ' ' 'r0   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.r  z0Gateway hit a non-retryable startup conflict: %suS   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.rd  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     r.   r  z'GatewayRunner.start.<locals>.<listcomp>   s    @@@a!'@@@r0   z#Gateway running with %s platform(s)build_channel_directoryc              3   4   K   | ]}t          |          V  d S r(   )r   )r,   chss     r.   r/   z&GatewayRunner.start.<locals>.<genexpr>   s(      WW3s88WWWWWWr0   z%Channel directory built: %d target(s)z"Channel directory build failed: %sc              3   >   K   | ]}|                                 V  d S r(   )rf   )r,   rg   s     r.   r/   z&GatewayRunner.start.<locals>.<genexpr>   s>        
  
 KKMM 
  
  
  
  
  
r0   .update_pending.json.update_pending.claimed.jsonr  skip_targetsc                 .                         |           S r(   )_run_process_watcher)wr  s    r.   r   z%GatewayRunner.start.<locals>.<lambda>   s    d&?&?&B&B r0   zprocess_watcher:r3  )rt  z(Resumed watcher for recovered process %sd   c   z!Recovered watcher setup error: %ssession_expiry_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     r.   r/   z&GatewayRunner.start.<locals>.<genexpr>   s$      BBa!'BBBBBBr0   platform_reconnect_watcher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   ri  r  r  r  rW  rG   r  gateway.shutdown_forensicsrf  r  rB   r   rF   rr  r0  r`   rz  rE   r  r  r  r  hermes_cli.security_advisoriesrm  rn  rd  gateway.platform_registryr  r  plugin_entriesrb  r<  r1   r5  r  r{   r  r"  r  r  rS  r  r  r  r  rK  r  agent.shell_hooksr  r  discover_and_loadr<  r  recover_from_checkpointr  rf   r   r  suspend_recently_activer  r  r  r  r   r}   r  r  r{  rb   _create_adapterrx  __members__r  set_message_handler_handle_messageset_fatal_error_handlerr	  set_session_storer  set_busy_session_handlerr  r   r  set_topic_recovery_fnr  set_authorization_check_make_adapter_auth_checkrN   r  r  r  r  rh  ru  has_fatal_errorr  r  r  rD  rz  r  rC   !_start_secondary_profile_adaptersr\  r  r  r  r  r2   r   r  r&  r  re  rp  r  r  r  r  re   ro  rW  loaded_hooksr  r  gateway.channel_directoryr  sum_send_update_notification#_schedule_update_notification_watchrp  r  r  r  _send_restart_notification(_send_home_channel_startup_notificationsr!  rP  r^  r>  r3  r  _spawn_supervised_session_expiry_watcher_kanban_notifier_watcher_kanban_dispatcher_watcher_platform_reconnect_watcher_handoff_watcher_async_delegation_watcherrT  r<  rr  r[  r  )Cr  rf  
_alignmentr  _effective_max_iter_redact_raw
_redact_onr  r  r  rm  rn  	_adv_hits_adv_msg_builtin_allowed_vars_builtin_allow_all_vars_plugin_allowed_vars_plugin_allow_all_varsr  _any_allowlist
_allow_allrJ  r  r9  rN   r6  r  r  r  r  r  r  r  r  r  r  _clean_markerr  stuckconnected_countenabled_platform_countstartup_nonretryable_errorsstartup_retryable_errors_multiplex_on_multiplex_skipped_platformsrt  r   _pval_builtin_names_set_reactionr  target_secondary_connected_served_by_secondary_existing_hb_bg
hook_countr  	directorych_countr  !chat_restart_notification_pending$planned_restart_notification_pendingwatchersr  r  r  sC   `                                                                 @r.   startzGatewayRunner.start*  s\      	0111	&!(!9!;!;D 	& 	& 	&!%D	&)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&N&N"O"OKKE#   
  	 	 	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		        +*,,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>>>>>>  UCCCCC 	 	 	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 P	 P	%Ho>>@@@@@@@@ tt"*   %A(O%\%\ < N	   -33H==="a'"**8_EEG  !Q!Q83G3N3N3P3P!Q!Q!Q..NN[    NN#@%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   T $ J JX! !       BB7HUUUUUUUU  44 ;.5DM(+::7CCC#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. %<<$N9@9V+c::\c'.'?*1*E	 =     '<=44!< 
 '~NN1LNN   #8 *9,-.2n.>.>.C@ @D28< <<$N+5'+*=	 =    177'~BBB  
 '6()*..*:*:R*?< <.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4 4&x000000& >>@@@@@@@@ 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* #>??OQWXXXCCCCCC((7GU[\\\\\    D"@((000491t%))+  "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<>WXXX 	t>@[\\\ ! 	KKMD*++		BB4+ABBBBB  
 	t?A]^^^ 	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*+++tsg  9 AA6A1C( (
D2DD=E 
E&%E&*A#G 
GG3H 
H H $H8 8
II	AJ &KK/AM 
MM"Q6 6
RRR/ /&SSAT* *&UU!U9 9&V"!V"?7W7 7
X&X!!X&"Y7 7
ZZ<[ 
[4[//[481\* *
]4]]!8n-Fn--
q*7B)q%%q*r- ,u: -
u/7*t;"s65t;6
t t;t+t;.u: ;u/u*%u: *u//u: :	vx- -
x:9x:3{ 
{{B/A@5 @5&AAAAAC=A7AE5 E5
AF$E?AFFAF$I&AJ JAJ#K/B.AN N
AON(AOOAOS
A1AT< T<&AU%U$AU%r)  r\  Tr   rt  _attemptc                *    t           dd          t                       _        t          j                    t          j                               } j                            |            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.
        r  Nc                    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 )NrZ   r	  )r  rp  r  r  )backoffcoro_factoryeffective_attemptr   rt  r  s   r.   _respawnz@GatewayRunner._spawn_supervised.<locals>._done.<locals>._respawnv!  su      !-000000000} ..( $+%6%:	 /      r0   )r  rW  r~  r   r   r  r  rD  rz  _SUPERVISED_HEALTHY_SECS_MAX_SUPERVISED_RESTARTSr|  r  r  re   ro  )r   r   ran_forr	  respawn_taskr	  r	  r	  _startedr	  r   rt  r  s        @@r.   _donez.GatewayRunner._spawn_supervised.<locals>._doneV!  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NC!O !O !O !Or0   )	r}   rc   r  rD  rz  r  r  re   ro  )r  r	  r   rt  r	  r   r	  r	  s   `````  @r.   r  zGatewayRunner._spawn_supervised:!  s      4,d33;%(UUD" >## "<<>>22""4(((,	O ,	O ,	O ,	O ,	O ,	O ,	O ,	O ,	O ,	O\ 	u%%%r0          @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  rp  r  r  list_pending_handoffsrB   claim_handoff_process_handoffcomplete_handoffrF   r   r   fail_handoffrC   rm  rr  )r  rl  pendingr  r3  r   s         r.   r  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r  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| j                            |          }	|	st          d| d          | 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t1          |          }|r|sd}d}nd}|r|nd} ||||
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tI          |d(d          s#tI          |d)d*          }t          d'|           dS )+zAExecute one handoff row. Raises on failure (caller marks failed).r   rh  )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 firsttitleN   u   Hermes — z/Handoff: create_handoff_thread raised on %s: %sTr   r-  zsystem:handoffr,  Handoff)rN   r   	chat_namer+  r  rQ  r  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  rA  ub   Handoff: dispatching synthetic turn for CLI session %s → %s (home=%s, thread=%s, session_key=%s)r  rI  zadapter.send failed: r  r  r  )%rz  rx  r:  r  r  ri  r  rB   rD   rE   rW  r2  KeyErrorr  rG   r  r   create_handoff_threadrC   rF   r   rr  r  r  r  r   r  ru  r  get_or_create_sessionswitch_session_evict_cached_agentr0  ri  r  r   r}   )r  r  rx  r  r  r  cli_session_idr
  rN   r   r6  	cli_titlethread_namenew_thread_idr   effective_thread_idhome_chat_idis_telegram_private_chatdest_chat_typedest_user_iddest_sourcer  ru  r  switchedsynthetic_textsynthetic_eventresponse_textsend_metadatar.  rf  s                                  r.   r	  zGatewayRunner._process_handoff!  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 -##H-- 	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#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*.E 
F# FF2M; ;
NNN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 ]e\  }}	 	 ddlm} |                    d          }
t          |
          dk    r|
d         nd} |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   || j                            |          }|r&|t8          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}~_d}~ww xY w|retI          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"}tM          j&                    |z
  |k    r	 tO          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tM          j&                    | _*        n2# t,          $ r%}t"          !                    d&|           Y d}~nd}~ww xY wtW          |          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  r4  r   rZ   r   c              3   *   K   | ]\  }}| d | V  dS )r}  Nr  )r,   r  cs      r.   r/   z8GatewayRunner._session_expiry_watcher.<locals>.<genexpr>"  sA       . .'+q!1

q

. . . . . .r0   z,Session expiry: %d sessions to finalize (%s)r  r|   r  session_expiredr  r  r  r  expiry_finalizedr  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 )rZ   N)rB	  )r,   r  r  s      r.   r/   z8GatewayRunner._session_expiry_watcher.<locals>.<genexpr>"  sB          "a!:L            r0   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  rp  r  r  r  rq  r  r  r  rB	  _is_session_expiredrb   r1   r   rB   r2   sortedr   ri  r  r  r3  rF   r}   r  r@   r  r  r  r  r.	  _clear_conversation_scopeset_expiry_finalizedrr  r   r   r  _sweep_idle_cached_agentsrD  r0  rG   prune_old_entriesrE	  range)r  rl  _finalize_failures_MAX_FINALIZE_RETRIES_expired_entriesr  rc  
_platforms_kr  _parts_plat_plat_summaryr  	_platform_cached_agent_cache_lock_cachedr  failuresr	  _failed_idle_evicted_last_prune_ts_prune_interval_max_age_prunedr  s                               r.   r  z%GatewayRunner._session_expiry_watcherl"  sJ      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!VVVVVV%(YYs^^F58[[1__q		"I(L 5+0+;)2'8	      ) ! ! ! D!
 )-&-d4G&N&N&2!, { {*.*;*?*?*D*D>HRW>X>X0z

ip^z^e^evz{ { { { { { { { { { { { { { {
 )0,0,@,D,DS,I,IM( ]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9LI			LI		CLV 
O#'B1OV O##A*V 1R  ?V  
R/
R*%V *R//0V  A(U	 V 	
U8U3.V 3U88V 
WV>>W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  rF   )r  r  s     r.   r  z"GatewayRunner._active_profile_name#  sO    	CCCCCC**,,9	9 	 	 	99	s    
""c           
        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0||d         k     r=|d         }|d         dz   }t          ||          s)t                              d	|j                   | j        |= t                              d
|j        |           d}	 |                     ||          }|s)t                              d|j                   | j        |= |                    | j                   |                    | j                   |                    | j                   |                    | j                   t1          |dd          }t3          |          r || j                   |                    | j                   |                    |                     |j                             | j         |_         | !                    ||d           d{V }	|	r|| j"        |<   | #                    |           | j"        | j$        _"        | j        |= | %                    |j        ddd           t                              d|j                   	 ddl&m'}
  |
| j"                   d{V  n# tP          $ r Y nw xY w	 | )                    |           n:# tP          $ r& t          *                    d|j        d           Y nw xY w|j+        rs|j,        sl| %                    |j        d|j-        |j.                   t                              d|j        |j.                   t_          |           d{V  | j        |= n| %                    |j        d|j-        |j.        pd           ta          |          }||d<   t          j                    |z   |d<   t                              d|j        |           t_          |           d{V  # tP          $ r}|t_          |           d{V  | %                    |j        ddtc          |                     ta          |          }||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        Yd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.
        
   Nr{  rZ   r  r  rG   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  r2  r  u   ✓ %s reconnected successfullyr   r  rR   z3resume-pending reschedule after %s reconnect failedr   r  zAReconnect %s: non-retryable error (%s), removing from retry queuer  zfailed to reconnectz&Reconnect %s failed, next retry in %dsz)Reconnect %s error: %s, next retry in %ds)2r  rp  r  r  rM	  rD  rz  rq  r  rB   r{  r   r   r{   ri  r  r  r  r  r	  r  r  r  r  r}   r   r  r  r  r  r  rN   r  r  r  rh  r  r  r  r  rF   r^  rr  r  r  r  r  rx  r~  rC   )r  r  r@  rN   ri  rt  ry  r   r  r  r  r	  r  s                r.   r  z)GatewayRunner._platform_reconnect_watcher,#  s      mBm y	') r + +A= - !-**********.""C !7!<!<!>!>?? d d} FF-h7 88H%% l+++"&x.z*Q. 4HoNN NN4   
 .x85NG  
 F"228_MMG" !e$N   !28< //0DEEE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  M?29h/>>wGGG8<,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&&&&&&&&&&s m y	' y	' y	' y	' y	'sj   A RFRL21R2
L?<R>L??RMR,NR
ND
R
T=!BT88T=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  r@   rA   r  rb  r  Taskrp  rb   rn  rt  rl  r   r   r   re  )	r  r"	  rF  r  profile_pendingr   r  r	  
unfinisheds	            r.   )_cancel_secondary_profile_reconnect_tasksz7GatewayRunner._cancel_secondary_profile_reconnect_tasks#  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   	r0   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)r  rG   systemd_watchdog_secondsr  gateway.systemd_notifyrj	  r
	  ready)r  rj	  watchdogs      r.   _start_systemd_watchdogz%GatewayRunner._start_systemd_watchdog$  s    } 	 D I I5!-4::::::"?$777~~ 	5!)/000tr0   c                 b   K   | j         }|dS d| _         |                                 d{V  dS )z;Stop heartbeats before any potentially long shutdown drain.N)r  r  )r  ro	  s     r.   _stop_systemd_watchdogz$GatewayRunner._stop_systemd_watchdog&$  sG      )F!%mmoor0   r'  rt  r(  r)  c                    K   |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.TNr%   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 (ry  r  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   ri  rF   rr  r  rw	  r   r   r2   r1  rx	  tools.terminal_toolry	  tools.browser_toolrz	  )
ru	  r  _killedr  rw	  _interrupted_interrupt_async_async_nry	  rz	  s
             r.   _kill_tool_subprocesseszGGatewayRunner.stop.<locals>._stop_impl.<locals>._kill_tool_subprocesses?$  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  ro  rd  r  active_cron_jobsactive_api_runsr  watchdog_delay_sphase_elapsed_s)rB   r   r  r  r  r$  r&  r'  r  r  rD  rz  )started_stop_started_at_boxr  s    r.   _shutdown_watchdog_snapshotzKGatewayRunner.stop.<locals>._stop_impl.<locals>._shutdown_watchdog_snapshot$  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  r0   PYTEST_CURRENT_TESTrZ   )
done_eventsnapshot_fnr  )rC   r  r  r  rA   r`   ra   rB   r  r  r  rc   )r	  _watchdog_doner	  r	  _stop_impl_bodyr  s      @r.   
_stop_implz&GatewayRunner.stop.<locals>._stop_impl>$  s.     ?Ss ?St ?S ?S ?S ?SN '_..N+9D(57        $ :>>"788 %3D4OPP- ;	   %%o+(        
 ""$$$$$""$$$$s   B) )B?c                    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                    |           !j        )                                 !j6        )                                 t_          !d           r!j7        )                                 !j8        )                                 !j9        )                                 t_          !d!          r!j:        )                                 !j;        <                                  | d"           t                               d# |                       	 dd$l=m>}  |             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	 |?                                 +# t(          $ r%}t                               d*|           Y d }~Ud }~ww xY wt          A                    !           t                               d+ |                       dd,lBmC}mD}  |              |             |s.	 t          d-z  F                                 n*# t(          $ r Y nw xY wt                               d.           |r4!G                    ty          |H                                                     !j        r!jI        	 t          t                      t          j                    t          !jM                  t          !j$                  d/d 0           n2# t(          $ r%}t                               d1|           Y d }~nd }~ww xY w!j        r5!jM        r.!N                                 t          !_P        !jQ        pd2!_Q        d!_        t          !d3d          r=!j        s6t                               d4           !"                    d5!jQ                   n!"                    d6!jQ                   t                               d7 |                       d S )8NzStopping gateway%s...z for restartr|   r   r%   c                  0    t          j                     z
  S r(   )rD  rz  )_stop_started_ats   r.   _phase_elapsedzCGatewayRunner.stop.<locals>._stop_impl_body.<locals>._phase_elapsed$  s    ~''*:::r0   FTrr	  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#   ro  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  r  rv  z3Shutdown phase: all adapters disconnected at +%.2fsr  r  zfinal-cleanupz6Shutdown phase: final-cleanup tool kill done at +%.2fs)shutdown_cached_clientsz!shutdown_cached_clients error: %sr  r  r  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"  rM  z7Failed to write planned restart notification marker: %szGateway restart requestedr  u   Gateway stopped by an unexpected signal — persisting gateway_state=running so container_boot auto-starts on the next boot (issue #42675)rd  stoppedz&Gateway stopped (total teardown %.2fs))Rr   ri  r  rD  rz  r1  r  r  r}   r   rh	  r  r  rq  r  r  r  r  mark_resume_pendingrb   rF   rr  r&  r'  r  r   r$  rK  r   r  !_INTERRUPT_REASON_GATEWAY_RESTART"_INTERRUPT_REASON_GATEWAY_SHUTDOWNr  r  re  rp  r  r	  r  r  r  re  r@   r  r  r  r  r   r  r  r  r  rn  r0  r  r  r  r  r  r  rc   r  r	  r  r  _shutdown_executorr  r	  r	  r  touchr  r  r  r%  r  r   r  r   r  r  r  )"r	  r	  r	  stop_watchdogr  _pre_drain_keys_sk_agentr  _cron_at_start_api_at_start_drain_started_atr  r  _resume_reasoninterrupt_deadliner  rX	  _cache_idle_agents_entryrN   r   _prof_amap_task_session_keyr	  _self_dbr  r	  r	  r	  r  s"                                   @r.   r	  z+GatewayRunner.stop.<locals>._stop_impl_body$  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,???? &&(((#))+++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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:c 
c:c55c:e,,
f6ff:h 
h$#h$Ak 
l(llr  )r  r  r  r  r  r  )r  rt  r(  r)  r	  r	  s   `    @r.   r  zGatewayRunner.stop.$  s        	8&*D#%5D"(7D%?&/!!!!!!!Fl	% l	% l	% l	% l	% l	% l	%\o	T o	T o	T o	T o	T o	Tb "-jjll;;or0   c                 H   K   | j                                          d{V  dS )zWait for shutdown signal.N)r  rl  r  s    r.   wait_for_shutdownzGatewayRunner.wait_for_shutdown &  s3      "'')))))))))))r0   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<   $ |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t'          | j                                                  z   }|D ]!}|r|| j        vr ||          | 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.
        rp  Fr   )profiles_to_server  r  NT	multiplexzDSkipping secondary profile '%s' due to port-binding config error: %sz-Failed to start adapters for profile '%s': %sr   r  r  rv  )served_profilesz could not record served_profiles)r}   rG   r  r	  r  rF   r  r  _adapter_credential_fingerprint_start_one_profile_adaptersrb  r   r   r\  r  r  r  r	  r  rH	  r  r  r  rr  )r  r	  r  rY  r2  rM  rT	  _adfpprofile_namerc  r  r  r  servedr   s                   r.   r  z/GatewayRunner._start_secondary_profile_adapters$&  s      t{$8%@@ 	1	VVVVVVVVV 	 	 	11	 )(**7i	 %'---// 	. 	.JE355c::B~'-$*;*;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
  K K KD(;;;0<T0J0J0JD'-  88888 	L 	L 	LLL;dLKKKKK	L sC   % 
33 B==
D'C((D'?D""D'+A&F &F;:F;r	  rc  r   rM  c                   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\  }}|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                   |                     |          }|f|                    ||f          }|Ft&                              d|||j        |j                   |                     ||           d{V  G||||f<   |                     |||           	 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  # t$          $ rI}t&                              d|j        ||           |                     ||           d{V  Y d}~dd}~ww xY w|
S )z>Create+connect one profile's adapters under its runtime scope.r   rq  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{   ru  )r,   rN   rt  s      r.   r/   z<GatewayRunner._start_one_profile_adapters.<locals>.<genexpr>~&  s^       (
 (
)/&(
 %X^_5JKK	(
N(
 (
 (
 (
 (
 (
r0   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.rp  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 (a single bot token cannot be polled twice). Give each profile its own %s credential.rZ   u   ✓ %s connected (profile: %s)u&   ✗ %s failed to connect (profile: %s)u   ✗ %s error (profile: %s): %s)rz  rq  rm  r<  r\  rH	  r  r  r2   rb  r  r  r  r}   rG   rx  rj  r  rF   r   r  r{   r   r	  rB   ru  _configure_profile_adapterr  ri  )r  r	  rc  rM  rq  profile_cfg	violationport_binding_platformsjoinedprofile_mapr2  rN   rt  r   r  r	  ownerr  s                     r.   r	  z)GatewayRunner._start_one_profile_adaptersm&  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  
  55g>>B~XrN33$LL- |X^X^   77JJJJJJJJJ*62'++G\8LLLG+L99  $($N$N% %      G                K,3K)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$ L/JLJ	LJ	 A.L
M#>MM#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)r	  )r  _make_profile_message_handlerr  !_make_profile_fatal_error_handlerr  r  r  r  r}   r   r  r  r  r  r  r  )r  r   r	  rN   r  s        r.   r	  z(GatewayRunner._configure_profile_adapter&  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r0   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_dirr	  zASecondary %s reconnect skipped: adapter unavailable (profile: %s)Tr  u    ✓ %s reconnected (profile: %s)r  Fr  z3Secondary %s reconnect attempt failed (profile: %s)r   rZ   z1Secondary %s reconnect retry in %ds (profile: %s))!r  rb  r  r  r	  rz  rq  rm  r  rB   r  r  r@   rA   re	  r   r  r   r   r{   r	  r  r  r  rh  ri  ru  r}   rm  rF   rr  r~  rp  )r  r	  rN   r  rb  r   r	  rq  rc  profile_configr"	  rf	  r   r  r	  r	  s                   r.    _run_secondary_profile_reconnectz.GatewayRunner._run_secondary_profile_reconnect&  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  )r  r  r  r@   rA   r  r  r  r	  r{   r}   rc   r  re   ro  rW  )r  r	  rN   r   r"	  rf	  r   background_taskss           r.   %_schedule_secondary_profile_reconnectz3GatewayRunner._schedule_secondary_profile_reconnectK'  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8r0   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   rN   r	  r  s    r.   _handlerzAGatewayRunner._make_profile_fatal_error_handler.<locals>._handlerh'  s8      ::<SZ[[[[[[[[[[[r0   r  )r  r	  rN   r	  s   ``` r.   r	  z/GatewayRunner._make_profile_fatal_error_handlerd'  sM    	\$7 	\D 	\ 	\ 	\ 	\ 	\ 	\ 	\ 	\ r0   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.
        r  zBIgnoring stale fatal error from secondary %s adapter (profile: %s)Nz6Fatal %s adapter error for multiplexed profile %s (%s)r4  )r}   rB   r@   rA   r   rr  r{   r   ru  r  r	  r  r  )r  r	  rN   r   r	  s        r.   r	  z1GatewayRunner._handle_profile_adapter_fatal_errorm'  s      d$7<<@@NN+t,, 	0I0IQX0X0XLLT  
 F$'''++GX>>>>>>>>>} 	F22<7SSSDN$1			
 	
 	
 	
 	
r0   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  rw  rF   rm  r  )rr  rc  r	  r  s    r.   r	  z=GatewayRunner._make_profile_message_handler.<locals>._handler'  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	  rF   )r  r	  r	  r	  rc  s   ``  @r.   r	  z+GatewayRunner._make_profile_message_handler'  s}     	877777	 *?<88LL 	  	  	 LLL	 		5 		5 		5 		5 		5 		5 		5 s    &&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 )
ad  Return a stable, log-safe fingerprint of an adapter's credential.

        Used only to detect two profiles claiming the same bot token. Returns a
        salted hash (never the token 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)rx  	bot_token_token	api_token
_bot_tokenrG   )rx  r	  rx  r   zhermes-mux:r9     )r}   r@   rC   rD   hashlibsha256encode	hexdigest)r   rx  attrvalrQ  rG   r	  s          r.   r	  z-GatewayRunner._adapter_credential_fingerprint'  s|    O 	 	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Wr0   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.
        ru  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   r@   ru  rA   r  rG   r  r}   r  r  is_registeredr{   create_adaptergateway_runnerr   r  rF   rr  rx  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  rN   rG   r  r   r  r	  r	  r	  r	  r	  r	  r	  r	  r	  r	  r	  r	  r	  r	  r	  r	  r	  r	  r	  s                            r.   r  zGatewayRunner._create_adapter'  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   )rN   r   r+  r  rw  )r  rP  )r  r+  r   r  rN   r	  r  s       r.   checkz5GatewayRunner._make_adapter_auth_check.<locals>.checkk(  sT    
  u"!2#.w$  F ++F333r0   r  )rC   r   r   )r  rN   r	  r
  s   ``` r.   r  z&GatewayRunner._make_adapter_auth_checkV(  sm    . (,%)	4 	4	4}	4 c]	4 		4 	4 	4 	4 	4 	4 	4 	4 r0   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.NrG   rN   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 publicr7  Tr   )r#  r}   rx  ry  r  r   ri  r   r
  rN   rR  send_private_noticer   r  rF   rr  r   )r  r  r   r   rG   notice_deliveryr~   r.  s           r.   _deliver_platform_noticez&GatewayRunner._deliver_platform_notice(  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*r  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_reasonr9   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.r4  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   r  rF   rr  rB   get_compression_tipr3  r  advance_compression_sessionr  r-	  ri  )r  r  r
  r  
pinned_rowtarget_session_idfollows_compressiontip_rowroute_owns_lineage	route_row	route_tipprior_session_idr9	  s                r.   !_resolve_async_delegation_sessionz/GatewayRunner._resolve_async_delegation_session(  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c                 `   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                                  |s*	 ddlm}  |d  j                  }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%          |
t0                    rt3          j        |
          j         } n	|	dk    r n|rn|j        >                     |          s't                              d|j        j                   d	S nv                     |          s`t                              d|j        |j        |j        j                   |j        dk    r!                     |j        |j                   d k    r|j        r|j        j        nd} j!        "                    ||j                  rd	S  j!        #                    ||j        |j        pd!          }|rC $                    |          }|r+|%                    |j        d"| d#| d$| d%           d	{V  nX $                    |          }|r!|%                    |j        d&           d	{V   j!        &                    ||j                   d	S  '                    |          }t           d'i           }|                    |          rAj(        pd!)                                }*                                }|d(v rd)}nX|d*v rd+}nQd	}|rF	 dd,l+m,} n# t          $ r d	}Y nw xY w|*	  ||          }|r|j-        nd	}n# t          $ r d	}Y nw xY w|rd!}n|}|rt\          d-z  }t\          d.z  }	 |/                    d/          }|0                    |           |                    |           |1                    d0           n7# td          $ r*}t                              d1|           d2| cY d	}~S d	}~ww xY w|3                    |d	           ti          |          d3k    r|n|d	d3         d4z   }d5| d6S |rt\          d-z  }t\          d.z  }	 |/                    d/          }|0                    d!           |                    |           |1                    d0           t                              d7||           n2# td          $ r%}t                              d8|           Y d	}~nd	}~ww xY w|3                    |d	           d	}	 dd9l5m6} |7                    |d:          }n# t          $ r d	}Y nw xY w||̉j(        pd!)                                }|r|8                    d;          s|9                    ||          }|rt                              d<||j:                    $                    |          }|rH	 |;                    |j                   n,# t          $ r t                              d=d           Y nw xY wd!S dd>l5m<}  | =                    |          }!d}"	 dd?l>m?}#  |#|          }"n# t          $ r d}"Y nw xY w|!r|"s̉j(        pd!)                                }$|$@                    d@          A                                }%*                                }&d	}'|&dAv rdB}'n"|&dCv rdD}'n|&dEv rdF}'n|%dGv rdB}'n|%dHv rdD}'n|%dIv rdF}'|'4| B                    ||!                    dJ          |'           d	{V }|pd!S | C                    |           t          dKdL          }( jE                            |d          })| jF        v rz|)rwt          jG                    |)z
  }* jF                            |          }+t          dM          },d!}-|+rt          |+dN          r	 |+J                                }.|.                    dOt          dM                    },dP|.                    dQd           dR|,dSdT|.                    dUd           d;|.                    dVd           }-n# t          $ r Y nw xY w|(dk    rt          |(dWz  dX          nt          dM          }/|+t          uo|(dk    r|,|(k    p|*|/k    }0|0rKt                              dY||*|,|(|-            M                    |dZ[            N                    |           | jF        v r*                                d\k    r O                               d	{V S dd]l+mP}1m,}2 *                                }3|3r |2|3          nd	}4|3r!|4 Q                    ||4j-                  }5|5|5S |4r(|4j-        d^k    rt                              d_|           d!S |4r&|4j-        d`k    r R                               d	{V S |4rf|4j-        dak    r[ S                    ||t          dbc           d	{V  t                              dd|           t          t          de                    S |4rJ|4j-        dfk    r? S                    ||t          dgc           d	{V   X                               d	{V S *                                dhv r~Y                                )                                }6t          t          did	                    }7|6s|7sdjS  $                    |          }|rt          d7i d|6dk|7rj[        nt          j]        dlj         dmj^        dnj_        dit          t          dig           pg           dot          t          dog           pg           dpja        dqjb        drjc        dsjd        dtje        dujf        dvjg        dwjh        dji        dxjj        }8 k                    ||8|            l                    | $                    |          y          }9|9dzk    rd{S d||9 d}S |4r|4j-        d~k    rY                                )                                }:|:sdS  jF                            |          };|;t          u rV $                    |          }|r=t          |:t          j]        j         j_        jg        jh                  }8|8|jm        |<   dS |;rt          |;d~          r{	 |;n                    |:          }<n8# t          $ r+}=t                              d||=           d|= cY d	}=~=S d	}=~=ww xY w|<r(|:d	d         ti          |:          dk    rdnd!z   }>d|> dS dS  $                    |          }|r=t          |:t          j]        j         j_        jg        jh                  }8|8|jm        |<   dS |4r|4j-        dk    rdS |4r|4j-        dk    rdS |4rJ|4j-        dv rA|4j-        dk    r o                               d	{V S  p                               d	{V S |4r&|4j-        dk    r q                               d	{V S |4r&|4j-        dk    r r                               d	{V S |4r&|4j-        dk    r s                               d	{V S |4r|4j-        dk    rY                                pd!)                                A                                }?|?r|?t                    d	dz          d         nd!}@|? p	|?dv p|@dk    }A|Ar u                               d	{V S dS |4r|4j-        dk    rdS |4r&|4j-        dk    r v                               d	{V S |4r{|4j-        dv rr|4j-        dk    r w                               d	{V S |4j-        dk    r x                               d	{V S |4j-        dk    r y                               d	{V S |4r|4j-        |1v r|4j-        dk    r z                               d	{V S |4j-        dk    r {                               d	{V S |4j-        dk    r |                               d	{V S |4j-        dk    r }                               d	{V S |4j-        dk    r ~                               d	{V S |4rd|4j-         dS j[        t          j        k    rKt                              d|            $                    |          }|rt          |jm        |           d	S t          t          j        dd                    }B jE                            |d          }C|j        t          j        k    rj[        t          j]        k    r|Bdk    r|Crt          jG                    |Cz
  |Bk    rt                              dt          jG                    |Cz
  |            $                    |          }|r< j        dk    r k                    ||           nt          |jm        |d           d	S  jF                            |          };|;t          u r*                                dak    r? N                    |           t                              d|           t          d          S  $                    |          }|rt          |jm        |d           d	S  j        rn                                 r                     |                                            rd                                  dnd                                  dS  j        dk    r3t                              d|                                |           d	S  j        d~k    rj(        pd!)                                }:d}Dj[        t          j]        k    ryj        srj        sk|:rit          |;d~          rY	 t          |;n                    |:                    }Dn5# t          $ r(}=t                              d||=           d}DY d	}=~=nd	}=~=ww xY w|Drt                              d|           d	S t                              d|                                |           d	S                      |;          r3t                              d|                                |           d	S                      |           d	{V r3t                              d|                                |           d	S j[        t          j]        k    rj        sj        st          |;dd          du rt          |;d          r	 |;                    j(        pd!)                                          rt                              d|           d	S n3# t          $ r&}=t                              d||=           Y d	}=~=nd	}=~=ww xY wt                              d|           j(        }Et          did	          pg }F                               r>                      $                    |          |j(        pd!d           d	{V \  }E}Gn|Es|Frt!                    }E|;                    |E           d	S *                                }Hddl+m}Im}Jm,}K |Hr |K|H          nd	}|r|j-        n|H}L|Hre|bt%           j        t&                    r j                            di           pi }Mnt           j        di           pi }Mt%          |Mt&                    r|H|Mv r|M|H         }N|N                    d          dk    r|N                    d¦          pd!)                                }O|Or|O8                    d;          r|Ond;|O }O|O@                    d;          }PY                                )                                }Q|O d$|Q )                                _(        |Pr|Pt                                d         n|P}H|Hr |K|H          nd	}|r|j-        n|H}L|Hr'|Lr% |J|L          r Q                    ||L          }5|5|5S |Hrg |J|L          r[Y                                )                                }R|j        r|j        j        nd!|j        |L|H|R|RdÜ}S	  j                            d|L |S           d	{V }Tn5# t          $ r(}Ut                              d|L|U           g }TY d	}U~Und	}U~Uww xY w|TD ]}Vt%          |Vt&                    st1          |V                    dd!                    )                                A                                }W|Wr|Wdk    ri|Wdk    r8|V                    dȦ          }Xt%          |Xt0                    r|Xr|Xc S d|H dʝc S |Wdk    r2|V                    dȦ          }Xt%          |Xt0                    r|Xr|Xnd	c S |Wdk    rt1          |V                    dd!                    )                                @                    d;          }Y|Ys1t1          |V                    dd!                    )                                }Zd;|Y d$|Z )                                _(        *                                }H|Hr |K|H          nd	}|r|j-        n|H}L n|Ldfk    r[t/          j         j        |           d	{V r                                 S  fd΄}[                     dfdd|[Ѧ           d	{V S |Ldk    r                                d	{V S |Ldk    r z                               d	{V S |Ld^k    rt                              d|           d!S |Ldk    r {                               d	{V S |Ldk    r |                               d	{V S |Ldk    r                                d	{V S |Ld\k    r O                               d	{V S |Ldk    r q                               d	{V S |Ldk    r                                d	{V S |Ld`k    r R                               d	{V S |Ldak    r                                d	{V S |Ldk    r                                d	{V S |Ldk    r                                d	{V S |Ldk    r                                d	{V S |Ldk    rddlm}\ Y                                )                                }]|]rdnd}^	  $                    |          }|rE                     |          }_|%                    t1          |j                  |^|_ܦ           d	{V  n,# t          $ r t                              dd           Y nw xY w	  |\|]          _(        n# t          $ r Y dS w xY w|Ldk    r                                d	{V S |Ldk    r x                               d	{V S |Ldk    r y                               d	{V S |Ldk    r w                               d	{V S |Ldk    r                                d	{V S |Ldk    r                                d	{V S |Ldk    r                                d	{V S |Ldk    r s                               d	{V S |Ldk    r                                d	{V S |Ldk    r                                d	{V }`t          |`dd	          }a|art          |`dd!          pd!}^|^r	  $                    |          }|rE                     |          }_|%                    t1          |j                  |^|_ܦ           d	{V  n,# t          $ r t                              dd           Y nw xY w	 |a_(        n6# t          $ r t          |`dd!          pd	cY S w xY wt          |`dd!          pd	S |Ldk    r                                d	{V S |Ldk    r fd}bdz}cY                                )                                }d|drS	 t          dzt[          |dt                                d                             }cn# t\          t^          f$ r dz}cY nw xY w|cdzk    rdnd|c d}e                     dd|e|bѦ           d	{V S |Ldk    r                                d	{V S |Ldk    r                                d	{V S |Ldk    r                                d	{V S |Ldk    r                                d	{V S |Ldk    r                                d	{V S |Ldk    r                                d	{V S |Ldk    r                                d	{V S |Ldk    r                                d	{V S |Ldk    r o                               d	{V S |Ldk    r p                               d	{V S |Ldk    r }                               d	{V S |Ldk    r ~                               d	{V S |Ldk    r                                d	{V S |Ldk    r                                d	{V S |Ldk    r                                d	{V S |Ldk    r                                d	{V S |Ldk    r                                d	{V S |Ldk    r                                d	{V S |Ldk    r r                               d	{V S |Ldk    rCY                                )                                }f|fsdjS 	 |f_(        n# t          $ r Y nw xY w|Ld~k    rCY                                )                                }g|gsdS 	 |g_(        n# t          $ r Y nw xY w|Ldk    r u                               d	{V S |Ldk    rddlm}hm}i ddlm}j Y                                )                                }k|ks
 |h            S 	  |j            }l |it%          |lt&                    r|l                    d          ni           }mn# t          $ r  |ii           }mY nw xY w|md         }n	 |k_(         j                            |          _        d|nddd d j        |<                        |           d_        n# t          $ r Y dS w xY w|Ldk    r v                               d	{V S |Ldk    r                                d	{V S  j        rd                                  dS |Hrt%           j        t&                    r j                            di           pi }Mnt           j        di           pi }Mt%          |Mt&                    si }M|H|Mv r^ Q                    ||H          }5|5|5S |M|H         }N|N                    d          dk    r9|N                    dd!          }o|or	 ddlm}p  |pt          j                                                  }qt/          j        |ot.          j        j        t.          j        j        |q           d	{V }rt/          j        |r                                d	
           d	{V \  }s}t|sp|t                                )                                }u|urddlm}v  |v|u          }u|ur|undS # t.          j        $ r Y dS t          $ r}d| cY d	}~S d	}~ww xY wd|H dS |N                    d          dk    r|N                    d¦          pd!)                                }O|Or|O8                    d;          r|Ond;|O }O|O@                    d;          }PY                                )                                }Q|O d$|Q )                                _(        |Pr|Pt                                d         n|P}Hnd|H dS d|H dS |Hr	 ddlm}w  |w|H                    dd                    }x|xraY                                )                                }Q |x|Q          }yt/          j        |y          r|y d	{V }y|yrt1          |y          nd	S n3# t          $ r&}t                              d|           Y d	}~nd	}~ww xY w|Hrd}z	 ddlm}{m}|  |||H          }}|}Y                                )                                }~|j        r|j        j        nd	} |{|}|~||          }|rB|\  }}}|_(        d}z|r1t                              d|}d                    |                     n3# t          $ r&}=t                              d|=           Y d	}=~=nd	}=~=ww xY w|Hr"t                                          dd          s	 ddlm}m}m}  |             ||H          }|>|                             dd!          }|j        r|j        j        nd	}|r$|r"ddlm} | ||           v rd!| d"| d#S Y                                )                                }~	 dd$lm}m}  ||~          \  }}n# t          $ r	 d	}g |~}}Y nw xY w|rH|rFddlm}  ||           fd%|D             }|r d!d                    |           d&| d'S |r,|* ||g|||(          }|r|\  }}}|_(        nd)|H d*S  |||~|(          }|r|_(        ngt          |H          }|r|S |H                    dd          |Ivr9t                              d+|H|j        r|j        j        nd,           d-|H d.S n3# t          $ r&}t                              d/|           Y d	}~nd	}~ww xY wt/          j         j        |           d	{V r+                     |          r                                 S d	S  j        r"|s t                              d0|           	 d1S                      ||          \  }}|t                              d2|           |S |"t           d3          si  _        | j        |<   t           jF        |<   t          jG                     jE        |<                                                          |          }	                      |||           d	{V }	 d!}t%          |t&                    r&t1          |                    d4          pd!          }nt%          |t0                    r|}|)                                rU	  j                            |           d	{V }n# t          $ r d	}Y nw xY w|                     |||5           d	{V  n3# t          $ r&}t                              d6|           Y d	}~nd	}~ww xY w|                     |                                |            N                    |                                ||           S #                      |                                |            N                    |                                ||           w xY w(8  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   rA  FrN   NrG   r   z9Dropping Slack message from configured ignored channel %sr  r6  r  pre_gateway_dispatch)rr  r  r  z*pre_gateway_dispatch invocation failed: %sr  skipz8pre_gateway_dispatch skip: reason=%s platform=%s chat=%srJ  r4  rewriter   r   allowz(Ignoring message with no user_id from %sz Unauthorized user: %s (%s) on %sr,  rv  pairr|   z;Hi~ I don't recognize you yet!

Here's your pairing code: `z5`

Ask the bot owner to run:
`hermes pairing approve rN  r   z<Too many pairing requests right now~ Please try again later!r   >   r=   r4  r1  >   r8  r9  r7  resolve_command.update_response.update_prompt.jsonz.tmpr  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: %sclarify_gateway)include_choice_promptsr%  z=Gateway intercepted clarify text response (session=%s, id=%s)z.Failed to resume typing after clarify responseslash_confirmr.  z!/>   r2  r=   r4  r5  once>   r<  rememberr<  >   r8  r9  rn  	nevermindrn  >   approve oncer:
  r4  >   r<  r=  >   r8  rn  r<
  
confirm_idr    r  r[  seconds_since_activityz | last_activity=last_activity_descrK  .0fzs ago) | iteration=rG  rH  rc	  i   zWEvicting stale _running_agents entry for %s (age: %.0fs, idle: %.0fs, timeout: %.0fs)%sstale_running_agent_evictionr  status)ACTIVE_SESSION_BYPASS_COMMANDSr0
  r
	  z3Ignoring /start platform ping for active session %srt  r  stop_command)interrupt_reasoninvalidation_reasonu@   STOP for session %s — agent interrupted, session lock releasedzgateway.stop.stoppednewnew_command>   qr}  r  zUsage: /queue <prompt>rv  r  raw_messagerT  rq  r  reply_to_textreply_to_author_idreply_to_author_namereply_to_is_own_message
auto_skillri  channel_contextr/  rw  rZ   zQueued for the next turn.zQueued for the next turn. (z queued)r~  zUsage: /steer <prompt>)r   rv  r  rT  ri  rR
  u9   Agent still starting — /steer queued for the next turn.zSteer failed for session %s: %su   ⚠️ Steer failed: 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  u=   Agent is running — wait or /stop first, then switch models.zcodex-runtimeu>   Agent is running — wait or /stop first, then change runtime.>   r9  r4  r4  agents
backgroundkanbangoal>   rp  r  re  pauseresumerD
  unwaitrl  ui   Agent is running — use /goal status / pause / clear / wait mid-run, or /stop before setting a new goal.moau8   Agent is running — wait or /stop first, then run /moa.subgoal>   yolofooterverboser\
  r^
  r]
  helpcommandsrw  rf  versionu   ⏳ Agent is running — `/zE` can't run mid-turn. Wait for the current response or `/stop` first.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 interruptr}  r!  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 %sz(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)rB  rC  z PRIORITY redirect for session %sz+PRIORITY redirect failed for session %s: %sz!PRIORITY interrupt for session %szVoice-priority-interruptrD  )GATEWAY_KNOWN_COMMANDSis_gateway_known_commandr0
  quick_commandsr   aliasr  )rN   r  r   raw_commandrQ  r  zcommand:z/command:%s hook dispatch failed (non-fatal): %sdecisionr9  r   z
Command `/z` was blocked by a hook.handledr  r  c                  >   K                                    d {V S r(   )_handle_reset_commandrr  r  s   r.   	_do_resetz0GatewayRunner._handle_message.<locals>._do_reset,  s-      !77>>>>>>>>>r0   z/newzJThis starts a fresh session and discards the current conversation history.)rr  r   r%	  detailexecutetopicz,Ignoring /start platform ping for session %swhoamirT  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.r  personalitysuggestions	blueprint
agent_seedzblueprint ack send failedretryundoc                  >   K                                    d {V S r(   )_handle_undo_commandrl
  s   r.   _do_undoz/GatewayRunner._handle_message.<locals>._do_undov-  s-      !66u=========r0   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bundlesrr  r%	  rX
  rC  branchrollbackzJUsage: /steer <prompt>  (no agent is running; sending as a normal message))	moa_usagenormalize_moa_configr  default_presetzmoa://localzmoa-virtual-providerchat_completions)r  r  r  ry  rP  zFailed to prepare MoA turn.r^  z) and is not accepting new work right now.execr   )_sanitize_subprocess_envr  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)task_idrN   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_namesrR   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     r.   r  z1GatewayRunner._handle_message.<locals>.<listcomp>.  sj     + + + !)~~a4488DDVV 'NN1b1155fbAAVVVr0   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 noticer7  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  ri  )r  r  ri  z!goal continuation hook failed: %sr  )r  gateway.session_contextr)
  rF   r   rr  r   r}   rx  ry  r  ri  r4  rf  r  r  r  r   r@   rA   rB   rN   r{   r   rC   r  r4  r  rP  rQ  r+  _get_unauthorized_dm_behaviorrw  r
  _is_rate_limitedgenerate_coder#  r   _record_rate_limitr  r   rD   get_commandr(  r0
  r   r  with_suffixrP  r   rd   r   r   toolsr6
  get_pending_for_sessionr   !resolve_text_response_for_session
clarify_idresume_typing_for_chatr9
  get_pendingrU  r/  r  rE   r^   clear_if_staler?  r  r  rD  r1  r   r[  r  r  "_invalidate_session_run_generationr0  _handle_status_commandrE
  _check_slash_access_handle_restart_command_interrupt_and_clear_session_INTERRUPT_REASON_STOPr  r   _INTERRUPT_REASON_RESETrk
  get_command_argsr  rv  r  r$  rL
  rT  rq  r  rM
  rN
  rO
  rP
  rQ
  ri  rR
  rA  r/  r  r  r  r~  rV  rW  _handle_agents_command_handle_background_command_handle_kanban_commandr1   _handle_goal_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_commandrw  r  r`   rz  r  r  r  r  r&  r{  r  rq  r  r  rC  rY  rZ  r  r  rc
  rd
  rG   r  emit_collectr  r  r  r   _maybe_confirm_destructive_slash_handle_topic_command_handle_whoami_command_handle_platform_command_handle_stop_command_handle_reasoning_command_handle_memory_command_handle_skills_commandagent.learn_promptru
  rR  _handle_fast_command_handle_model_command_handle_codex_runtime_command_handle_personality_command_handle_suggestions_command_handle_blueprint_command_handle_retry_commandr0  r2  
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_command_handle_debug_command_handle_title_command_handle_resume_command_handle_sessions_command_handle_branch_command_handle_rollback_commandhermes_cli.moa_configr
  r
  rK  r  r=  _moa_restore_overrider.	  _moa_disable_after_turn_handle_voice_commandtools.environments.localr
  ra   r  create_subprocess_shellr  r  r  r  r  r   r   r  r
  rq  agent.skill_bundlesr
  r
  r2   localsagent.skill_commandsr
  r
  r
  r  r
  r
  r
  r  r  r  r  r  r  r  _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  rr  r  r)
  is_internalr  _hook_results	_hook_exc_result_action	_new_textr
  coder   
_quick_key_update_promptsr>  r   r<	  _recognized_cmd_resolve_update_cmd_cmd_defresponse_pathprompt_pathtmpr  label_clarify_mod_pending_clarify_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	_stale_ts
_stale_age_stale_agent_stale_idle_stale_detail_sa	_wall_ttl_should_evict_DEDICATED_HANDLERS_resolve_cmd_inner_evt_cmd_cmd_def_inner_deniedqueued_text	has_mediar  r   rp  r  acceptedr   preview	_goal_arg
_goal_verb_is_control_telegram_followup_grace_started_atrn  ru  rv  r  r   rc
  rd
  _resolve_cmd	canonicalre
  qcmdr  target_command	user_argsr  hook_ctxhook_results	_hook_errhook_resultrh
  r   rJ
  new_argsrm
  ru
  
_learn_req_ack	_ack_meta_blueprint_result_blueprint_seedr~
  _undo_n	_undo_raw_undo_detailqueue_payloadsteer_payloadr
  r
  r  moa_payloadrQ  moa_cfgpresetexec_cmdr
  sanitized_envr  r  r  r8  r   r
  plugin_handlerr.  r
  r
  r
  
bundle_keyuser_instruction_bundle_platbundle_resultr\  _loadedmissingr
  r
  r
  cmd_key_skill_namerT	  _get_plat_disabled_build_stackedr
  
extra_keysstacked_instruction_disabled_extrastacked_result_missing_unavail_msg_active_session_lease_limit_message_run_generation_agent_result_final_textr  	_goal_excr
  r
  s   ``                                                                                                                                                        @@r.   r  zGatewayRunner._handle_messageA)  s-B      	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   	
#JJJJJJ ,* "&"4	! ! !  # # #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 &  4	^# ++F33 GI^___t ))&11 (	NN=v~vO_agapavwww  D((66O"N 7   	  :@ W 5 5i %66}fnUU  4)77!6>63C3Ir   Y"66v>>G %ll"NO:>O O 8EO O HLO O O         #66v>>G %ll"N6         &99-XXX4 11&99
!$(@"EEz** @	6:#**,,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=111KK...&&$&7777 Q Q QNN#H!LLLPQPPPPPPPPQ  ##J555),]););r)A)A}UXVXUXGY\aGaCECCCC  6 ,/A A*-BB'33F;;CNN2&&&KK...&&$&777KKP'"	       NNW       
  ##J555 	$======+CC4  D      	$ 	$ 	$#	$'L,D"'*"2!9!9!;!;
 " *<*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+//
A>>	---)-y0J/33J??L  ,,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*===---  ""h..!88?????????        ((**H=EO//9994N  #N6226>;NOO&"N
  ."5"@"@QS]^^^r A."5"B"B!99%@@@@@@@@@  A."5"?"?77%;(6	 8          ^`jkkk%a(>&?&?@@@  
?."5">">77%<(5	 8          "77>>>>>>>>>   ""n44#4466<<>>
 !d!C!CDD	" 49 433226:: J#/ $ $ $([$;D%ZU%7%7+JZ$  %||$ %*$5$5	$
 $)#3#3$ $(|R(H(H(NB#O#O#O$ %)r)J)J)Pb$Q$Q$Q$ -2,E,E$ ',&9&9$ ,1+C+C$ .3-G-G$ 160M0M$ $)#3#3$ (-';';$ ).(=(=$  "'!$" #(//#$L& &&z<III))*d>V>VW]>^>^)__A::66DUDDDD  )N."5"@"@"3355;;==
! 433 $ 4 8 8 D D $;;;"66v>>G 	M'3!+)4)9#(<','7+0+?,1,A( ( ( AM1*=VV  	=W]G%D%D 	==#0#6#6z#B#B$ = = ='H*VYZZZ<s<<<<<<<<=   e",SbS/c*ooPR>R>RUUXZ"[dZadddd<<226:: 	I#/'%0%5$|#(#3',';(-(=$ $ $L =IG-j9MM  W."5"@"@VV  +."5"H"H* *  >."59L"L"L!&)33!%!=!=e!D!DDDDDDDD!66u=========  @."5"A"A!88?????????  D."5"E"E!<<UCCCCCCCCC  @."5"A"A!88?????????  C."5"?"?"3355;BBDDJJLL	<EMY__T155a882
 "M , $dd,!V+ 
  B!%!:!:5!A!AAAAAAAA C  C R."5">">QQ
  A."5"B"B!99%@@@@@@@@@  D."59V"V"V!&&00!%!:!:5!A!AAAAAAAA!&)33!%!=!=e!D!DDDDDDDD!&(22!%!<!<U!C!CCCCCCCC  
E."59L"L"L!&&00!%!:!:5!A!AAAAAAAA!&*44!%!>!>u!E!EEEEEEEE!&)33!%!=!=e!D!DDDDDDDD!&(22!%!<!<U!C!CCCCCCCC!&)33!%!=!=e!D!DDDDDDDD  Q.2E Q Q Q
 ![%666egqrrr226:: ^/0I:W\]]]t',	BEJJ( ($ 155j!DDK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44Z@@M 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;;;;;;;;;  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 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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=========$$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(
.2.K.O.OPZ.[.[+ %# -5 2= =-j9 ((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? ZYYYYY,D,DRZ__EVEV,W,WM)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 "4#EvNNNNNNNN 	 88@@ A>>@@@4 & 		{ 		KKM  
)  150O0O1
 1
-~ %KKR   "! ,4!9:: 1.0+6KD'
3+BZ(.2ikk
+##%%%<<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 R' 'R65R6<S S"!S"AU 
V#VVV%A1Y 
Z!ZZ"[   [[]4 4&^^ _ _! _! Bg 
ggy$ $
z. zzzU	"AU, U,
AVU6AVVAV[A	A\ \
A]\&A]]A]h"$Ai i
Ai9iAi4i4Ai9zAA{< {<&A|%|$A|%|)A|: |:
A}}A}B?ABD D&BEEBEE	BE EBE1E0BE1G6BH HBH.H-BH.TBT T
BTTBTUBU U
BU!U BU!W?BX XBX%X$BX%X1ABZ Z
BZZBZ_C%Bb( b(Bcb<	BccBcc
BccBcgB
Bi i
Bji!BjjBjjB%Bl5 l5
Bm%l?Bm m Bm%nA:Bu p&Bu p3Bq q
Bu qBqqBu qBqqABu r+-Bu s,Bu tABu u
Bv
u$BvvBv
z3C@ {A(B~ |; B} }B~ }B}+}(B~ }*B}+}+$B~ ~C@ ~
B ~B~;~6C@ ~;B  C@ @ACA3	quick_keyc                     t          |dd          sdS 	 t          |dd          }|| j                            |d           n
|| 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=  r   r.	  rF   )r  rr  rQ  _restores       r.   r
  z#GatewayRunner._restore_moa_one_shot_/  s     u7?? 	F	u&=tDDH-11)TBBBB;C-i8$$Y///// 	 	 	DD	s   AA% %
A32A3c                     |sdS 	 | j                             |d          }|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>  r   _restore_session_model_overriderF   r   rr  r  r  r  s      r.   r
  z6GatewayRunner._restore_pending_one_turn_model_overridet/  s     	F	U<@@dSSH 00hGGGGG 	U 	U 	ULLDtLTTTTTT	Us   = = &A'&A')r  r  c          
      8  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|                    |           |rMt5          j        | j        ||           d{V }|dk    rWt          | dd          }|	i }|| _        t=          |          ||<   t>                               dt!          |                     nt>                               d|t!          |                     d}	 | !                    ||          \  }}tE          |pi           }||d<   n,# tF          $ r t>          $                    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 ]\}	 |-                    |j.        d| d|           d{V  +# tF          $ r%}t>          $                    d|           Y d}~Ud}~ww xY w|rddl/m0} |D ]}tb          j2        3                    |          }|4                    dd           } t!          |           d!k    r| d          n|}!tk          j6        d"d|!          }! ||          }"d#|! d$|" d%}#|# d&| }|rddl/m0} |D ]}$tb          j2        3                    |$          }|4                    dd           } t!          |           d!k    r| d          n|}!tk          j6        d"d|!          }! ||$          }"d'|! d$|" d(}#|# d&| }|j        rnddl7}%ddl/m0}& h d)}'t          |j                  D ]J\  }}t%          ||          s tq          ||          sts          ||          r7|t!          |j                  k     r|j        |         nd}|d*v r]tb          j2        :                    |          d+         ;                                }(|(|'v rd,}n|%<                    |          \  })}*|)r|)}nd-}tb          j2        3                    |          }+|+4                    dd           },t!          |,          d!k    r|,d          n|+}-tk          j6        d"d|-          }- |&|          }.t{          |-|.|          }/|/ d&| }L|Mt          |d.d          t          j>        k    r.t          |d/d          rdd0l?m@}0  |0            rd1|jA         d2| }t          |d3d          r8|jB        r1|jC        dd4         }1t          |d5d          r	d6|1 d7| }nd8|1 d7| }d9|v r0	 dd:lDmE}2 dd;lFmG}3 tb          jH        I                    d<tb          j2        J                    d=                    }4d}5d}6i }7g }8	 t                      }6|6I                    di           }7t          |7tD                    r&|7I                    d>          }9|9t          |9          }5	 dd?lNmO}:  |:|6          }8n'# tF          $ r |6I                    d@          pg }8Y nw xY wn# tF          $ r Y nw xY w| !                    |||6A          \  };}<|<I                    dB          pd}=t          |7tD                    r*|7I                    dC          p|7I                    d          n|7}>|;|>k    rd}5|5zt          |7tD                    re	 ddDlPmQ}?  |?dd|7I                    dB          |=|7I                    dE          |<I                    dE                    rd}5n# tF          $ r d}5Y nw xY w|8r,|=r*	 ddFlNmR}@  |@|;|=|8G          }A|Ar|A}5n# tF          $ r Y nw xY w |3|;|=|<I                    dH          pd|5|<I                    dE          pd|8I           d{V }B |2||4|B|4J           d{V }C|CjS        rT| *                    |          }D|Dr;|D-                    |j.        dKT                    |CjU                  pdL           d{V  dS |CjV        r|CjW        }nN# tF          $ rA}Et>          X                    dM|E           t>          $                    dNd           Y d}E~End}E~Eww xY w|S )Oa  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  rR
  z

[New message]
r  r  r  nativer  zSImage 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-streamrZ   z
text/plainrk  rN   rT  _discord_tools_loadedz[Triggering message id: `uG   ` — use as `message_id` for reply/react/pin via the discord tools.]

rM
  r  rP
  z%[Replying to your previous message: "z"]

z[Replying to: "@)#preprocess_context_references_async)get_model_context_length_asyncr  ~context_lengthget_compatible_custom_providerscustom_providersr  r  r  should_clear_context_pinr  "get_custom_provider_context_lengthr  r  ru  ry  r  ry  config_context_lengthr  ru  )r  rr  allowed_rootr   zContext injection refused.z(@ context reference expansion failed: %sz,@ context reference expansion failure detail)Yr   r}   r   rG   r  #_consume_pending_native_image_pathsr  rQ  r	  rN   rx  ry  r  rR
  r  r  r   rq  rz  rb   rv  r  r~  r  r   r  r  r  _decide_image_input_moder  rq  r   ri  r  rA   rF   rr  r  r]  _enrich_message_with_vision"_enrich_message_with_transcription_should_echo_stt_transcriptsr#  rR  r  r   r   tools.credential_filesr_  r`   rg   r  r1   r)   r   	mimetypesr  r  r  rE   
guess_typer  DISCORDr:  rm  rT  r  rM
  agent.context_referencesro  agent.model_metadatarp  ra   rB   r  r?   r@   r0  rK  rt  hermes_cli.route_identityrw  ry  blockedr2   warningsr  r   r   )Fr  rr  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  rg   ry  	_img_modepending_nativevision_runtime
turn_modelr  r]  _successful_transcripts_echo_adapter
_echo_meta_tx	_echo_exc_to_agent_path_apath	_basenamerS	  _display_agent_path_note_vpath
_mimetypesr_  _TEXT_EXTENSIONS_extguessedr  r  r3   r  r  context_note_disc_tools_loadedreply_snippetro  rp  _msg_cwd_msg_config_ctx_msg_cfg_msg_model_cfg_msg_custom_providers_msg_raw_ctxrt  
_msg_model_msg_runtime_msg_base_url_msg_configured_modelrw  ry  _msg_custom_ctx_msg_ctx_len_ctx_resultrg  r   sF                                                                         r.   _prepare_inbound_message_textz+GatewayRunner._prepare_inbound_message_text/  s_     * -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 ')!# b	"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,,, 4 #*"31! +# # #      	
 ((%,T3[]a%b%bN%-)+FTC26{2C2CN;/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./VVVVVV33  *..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   ?0K0 0&LL-MMM'P
P4P//P4+Ai =Aa `/ .a /!aa aa i 
a$!i #a$$Bi :Ae i ei ei #e< ;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.rG   Nrp  Frr  r  r  r  )r}   rm   _resolve_profile_home_for_sourcer  )r  rr  r  r  r  s        r.   ,_prepare_profile_scoped_inbound_message_textz:GatewayRunner._prepare_profile_scoped_inbound_message_text1  s+      744002FNN 	'(M(Mf(U(UVV  !??!# +	 @                        77#	 8 
 
 
 
 
 
 
 
 	
s   A11A58A5c                 v    t          | dd           }|sg S t          |                    |g           pg           S )Nr  )r}   rq  r   )r  r  r  s      r.   r~  z1GatewayRunner._consume_pending_native_image_paths21  sE     'OQUVV 	IN&&{B77=2>>>r0   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)	Nr  z*Failed to cache live session source for %sTr   r  r  Fr  )r}   r   r  r  r4  rF   r   rr  move_to_endr   popitem)r  r  r  cached_sourcesmax_sizes        r.   _cache_session_sourcez#GatewayRunner._cache_session_source81  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.r  N)r}   _storer  r  r  )r  facades     r.   r  z!GatewayRunner.async_session_storeM1  sG     5t<<>V]$2DDD&t'9::F(.D%r0   c                     |sd S t          | dd           }|sd S |                    |          }|'	 |                    |           n# t          $ r Y nw xY w|S )Nr  )r}   rB   r  rF   )r  r  r  r  s       r.   r  z(GatewayRunner._get_cached_session_sourceV1  s     	4 '94@@ 	4##K00**;7777   s   A 
AAr
  run_generationc                 
[  ڇۇ܇݇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|9W|9F                    |j         ||t          dFdG          H           d{V }:|:#t          | dI          si | _H        |:| jH        ||f<   | j        I                    |j                    d{V };|;rt          |;          dJk    rd=dKlKmL}<mM}= dL}>dM}?d}@dN}AdO}BdP}Cd}Dd}Ed}Fd}Gd}Hd}Id}Ji }K	 t_                      }K|Kr|K                    dQi           }Lt          |Lt                    r|L}>nt          |Lt                    r|L                    dR          p|L                    dQ          p|>}>|L                    dS          }M|M(	 t          |M          }Dn# t          t          f$ r Y nw xY w|L                    dT          pd}E|L                    dU          pd}F|K                    dVi           }Nt          |Nt                    rt	          |N                    dWd                    R                                dXv }@|N                    dY          }O|O0	 t          |O          }P|Pd=k    r|P}An# t          t          f$ r Y nw xY w|N                    dZ          }Q|Q0	 t          |Q          }P|Pd=k    r|P}Bn# t          t          f$ r Y nw xY w|N                    d[          }R|R0	 t          |R          }P|Pd=k    r|P}Cn# t          t          f$ r Y nw xY w|>}H|E}I|F}J	 | T                    ||t          |Kt                    r|Knd\          \  }>}S|S                    dT          p|E}E|S                    dU          p|F}F|S                    d]          p|G}Gn# t&          $ r Y nw xY w|D,	 d=d^lUmV}T  |T|H|>|J|F|I|E          rd}Dn# t&          $ r d}DY nw xY w|D|Fr	 	 d=d_lWmX}UmY}V  |U|K          }Wn<# t&          $ r/ |K                    d`          }Wt          |Wt                    sg }WY nw xY w |V|>|F|Wa          }X|Xrt          |X          }Dn# t          t          f$ r Y nw xY wn# t&          $ r Y nw xY w|@r |=|>|Fpd|Gpd|D|Epdb           d{V }Yt          |Y|?z            }Zt          |Ydcz            }[t          |;          }\|jZ        }]|]d=k    r|]dd}^n |<|;          de}^|A}_|Zk    p|\|_k    }`|`rt          | dfd          }a|a	i }a|a| _[        |j         }bt          |a                    |b          pdg          }c|ct          j                     k    r@t          	                    dh|bt          dg|ct          j                     z
                       d}`|`rt          	                    di|\dj|^t          |?dkz            |Ydj|Zdj           | =                    || ]                    |                    }d	 d=dll^m_}e d=dml`ma}f | T                    ||t          |Kt                    r|Knd\          \  }>}S|S                    d]          rdn |;D             t          ަ          dJk    rt          | j        do| j                  }g |fdi |S|>dJdddpg|j         |gdqd}h	 d_b        t          t          drd          dsd          }it          |i          r |i|g|j                    d_d        dt _e        t          jf                    }j |e            |jg                    dڈ܈݈fdu          }k	 t          jh        t          ji        |k          |Bv           d{V \  }l}mn;# t          jj        $ r( d}n|n2ݠk                                }n|nt          jl        dw           d{V  |n2|ns|k d{V \  }l}mn| m                    |kdxy           d}h|Cd=k    r#t          j                     |Cz   | j[        |j         <   t          D                    dz|j         |B           d{|Bd|d}}o	 | 8                    |          }p|pr*|j        r#|p<                    |j        |o|d:           d{V  n2# t&          $ r%}qt          D                    d~|q           Y d}q~qnd}q~qww xY w Y nw xY wj         }r|r|j         k    }sta          t          dd                    }t|sr`|r|_         | n                    |||r           | j        o                                 d{V  t          j        | j"        ||d           d{V  |srJ| j        p                    |j         |l           d{V  d=|_Z        |l};t          |l          }u |<|l          }vnJ|tr$d=|_Z        |l};t          |l          }u |<|l          }vn$|\}u}vt          D                    d|j                    t          	                    d|\|udj|vdj           |v|[k    rt          D                    d|vdj           t          drd          }w|wt          |wdd          r|Cd=k    r#t          j                     |Cz   | j[        |j         <   t          |wdd          pd}xd=dlqmr}y  |y|xd          }xd|x d}z	 | 8                    |          }p|pr*|j        r#|p<                    |j        |z|d:           d{V  n# t&          $ r%}qt          D                    d|q           Y d}q~qnd}q~qww xY w|wt          |wdd          rt          |wdd          }{t          |wdd          pd}|d|{ d|| d}}	 | 8                    |          }p|pr*|j        r#|p<                    |j        |}|d:           d{V  n2# t&          $ r%}qt          D                    d|q           Y d}q~qnd}q~qww xY w| %                    |           |hs| s                    dy           d{V  n:# | %                    |           |hs| s                    dy           d{V  w w xY wn2# t&          $ r%}+t          D                    d|+           Y d}+~+nd}+~+ww xY w|;s| j        t                                 d{V sd}~	 d=dlumv}mw}mx}my}mz} t_                      } ||          dk    rP |||          sD|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|sq	 d=dlm} d=dlm} t          |dd          pd                                }|r,|dRk    r& |            }|                    |j                  rd}n# t&          $ r Y nw xY w|sP|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|}t)          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         }|                     |||;||||| ]                    |          |j        t          |dd          ||           d{V }	 | 8                    |          }t          t3          |          dd          }t          t3          |          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          t3          |          dd          |                    ||           n-|r+t          |d          r|j                            |d           	 |                     |           dS |                    d          pd}tC          |          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tI          |          rj|                     |           	 | j                            |           d{V  n3# t&          $ r&}t                              d||           Y d}~nd}~ww xY w|s6tO          ||t          |;                    }tQ          |j        |          }|                    d          r|d         |j         k    r|j         |k    r|d         |_         | n                    |||j                    | j        o                                 d{V  | j                            |j         ||           d{V  t          j        | j"        ||d           d{V  n$t          	                    d|pd||j                    	 tU          t_                      tW          |j                  dta          t          | dd                    |j        t          j        hæ          }n8# 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_                      tW          |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_                      tW          |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 |_        tq          |          D ]O\  }}t          j        |                     |                     |dkz  dk    rt          jl        d=           d{V  Pn2# t&          $ r%}+t                              d|+           Y d}+~+nd}+~+ww xY w	 d=dlm} ty          |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                    }tC          |          }t	          |                    dd                    R                                |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|rd||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  nW|                    dt          |;                    }t          |          |k    r
||d         ng }|sd||n|||n|d}|j        rt	          |j                  |d<   | j                            |j         ||¬           d{V  |r,| j                            |j         d||d|¬           d{V  nd}|D ]}|Ƞ                    d          dk    ri |ȥd|i}|s=|Ƞ                    d          dk    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٦                    }|                     ||||ʐ          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          t3          |ͦ          dd          }t          t3          |ͦ          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        I                    |j                    d{V }n# t&          $ r g }Y nw xY wt          |ϐdd                   D ]=}|Р                    d          dk    r"||n|}|Р                    d          |k    } n>|smd||n|||nt          j                     d}t          |dd          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  rM
  zSinbound message: platform=%s user=%s chat=%s msg=%r reply_to_id=%s reply_to_text=%rr4  z1telegram topic recovery: chat=%s user=%s %r -> %sr  r~   gateway_session_idr   r  z%Failed to read Telegram topic bindingTr   r3  z$compression-tip lookup failed for %szcompression-tip-walkr  z'Failed to record Telegram topic bindingwas_auto_resetF
auto_resetis_fresh_resetzsession:start)rN   r  r3  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,  )rN   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): %srQ
  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: %sr  r  r?
  )	owner_key
generationr  r  r   )estimate_messages_tokens_roughrp  zanthropic/claude-sonnet-4.6g333333?i  r"        r@r  r  rr  r  r  r9   r  >   r;   r=   r>   hygiene_hard_message_limithygiene_timeout_seconds hygiene_failure_cooldown_secondsr  ry  rv  )rt  ry  ru  rz  )r  ry  r|  r  ffffff?actual	estimated&_hygiene_compression_failure_cooldownsr  zXSession 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)rp  r  )CompressionCommitFenceAIAgentc                 @    g | ]}|                     d           dv |S )r[  >   r  ra  rb  r  r  s     r.   r  z<GatewayRunner._handle_message_with_agent.<locals>.<listcomp>3  s8     ) ) )&'#$55==4Q#Q#Q !"#Q#Q#Qr0   r  rr
  )r  rH  
quiet_modeskip_memoryenabled_toolsetsr3  r  context_compressorbind_session_statec                      d S r(   r  )akws     r.   r   z:GatewayRunner._handle_message_with_agent.<locals>.<lambda>3  s    D r0   c                  6                         d           S )Nr|   )approx_tokenscommit_fence)_compress_context)_approx_tokens
_hyg_agent_hyg_commit_fence	_hyg_msgss   r.   r   z:GatewayRunner._handle_message_with_agent.<locals>.<lambda>3  s(    
0L0L,5r:H9J 1M 1* 1* r0   r  gMbP?zsession hygiene timeoutr  z`Session hygiene compression for session %s timed out after %.1fs; continuing without compressionu+   ⚠️ Context compression timed out after .1fu   s. 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: %s_last_compaction_in_placez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_aborted_last_summary_errorrU  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_FLAGrN  rO  profile_build_directiveprofile_build_modeaskr8  z@Profile-build onboarding directive failed, using plain intro: %s)
get_secretrc   r	  r	  rw  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_timestampsr/  r  z2Message timestamp injection failed (non-fatal): %sr  r  )rN   r  r   r  r+  r3  r   zagent:start_moa_config)r   context_promptr  r  r3  r  r  r  ri  
moa_configpersist_user_messagepersist_user_timestamp_stop_typing_with_metadatastop_typinguK   Discarding stale agent result for %s — generation %d is no longer currentr7  pop_post_delivery_callbackr  _post_delivery_callbacksri  #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: %srO  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  last_reasoning)escape_code_fences_for_display   z
_... (z more lines)_r  reasoning_styler
  subtextc              3   (   K   | ]}|rd | ndV  dS )z-# z-#Nr  r,   lns     r.   r/   z;GatewayRunner._handle_message_with_agent.<locals>.<genexpr>T6  sB       , ,;="6J"JJJ$, , , , , ,r0   u   -# 💭 Reasoning

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

)build_footer_linelast_prompt_tokensr  )r	  r  r  context_tokensrr  r  zruntime_footer build failed: %salready_sentz	agent:endrR  r  r  zProcess watcher setup error: %s&Watch notification injection error: %szWatch queue drain error: %srT  r  compression_exhaustedc              3       K   | ]}|v V  	d S r(   r  )r,   r  _err_str_for_classifys     r.   r/   z;GatewayRunner._handle_message_with_agent.<locals>.<genexpr>6  s9        aq11      r0   )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 longrY  rZ  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: %sra  compression_deferredu   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  rN   r/  agent_persistedra  )r[  r   r/  rT  z:Skipping duplicate user turn (message_id=%s) in session %s)skip_dbr  rb  r[  r  )r"  z5Suppressing intentional silence marker for session %s)r$  ztrailing footer send failed: %szAgent error in session %sr  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_secondsr,  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   r  r[  r   z% The request was rejected by the API.z)Sorry, I encountered an unexpected error.r]  r  )rD  r   rN   r{   rC   r   r4  r}   r   ri  rQ  r  r   r  r  r  r  r  r  rF   r  r,	  r  rB   rD   r'
  r  r  r  get_telegram_topic_bindingrr  r
  r3  r-	  r  r  rI	  r.	  r  
created_atrX  r  r  r  r  rG   _set_session_envr?   r   _pinned_session_context_promptr  rb   r  get_reset_policynotifynotify_exclude_platformsr#  at_houridle_minutes_reset_notice_session_infor   rR  r  r@   rq  r
  r  r  r   r2   acquirer?  r  load_transcriptr   r  r  rp  rA   r0  r=  r2  rE   r1  r  r  rw  rK  rt  ry  r"  r  r  r  agent.conversation_compressionr  	run_agentr  compression_in_placer   r  	_print_fnr  run_in_executorr  r  r  try_cancel_before_commitrp  r  _rebind_turn_leaser  rewrite_transcriptr   r   r  has_any_sessionsr\  r  rN  rO  r  r  r  rx  r  r+  r  r2  r  r`   rz  r  r  r	  rz  rq  ry  r%	  r
  _voice_channel_sidecar_noter  r  r  r  r  r  r	  r  _set_pending_turn_sidecar_notes_bind_adapter_run_generation
_run_agentri  r   r  r  _is_session_run_currentr  r  r   _clear_session_envrc  gateway.response_filtersr  rm  r  rK  rg  r   _record_gateway_session_peerr  r  
MATTERMOSTgateway.stream_consumerr  r  r  r  gateway.runtime_footerr!  ra   r<  r  r3  r  r  r  r  rL  rI  rC  _inject_watch_notificationrb  reset_sessionappend_to_transcriptr  rT  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  rr  r  r
  r  _msg_start_time_platform_name_msg_preview	_reply_id
_reply_txtr  r  r  r
  resolved_entrybindingbound_session_idcanonical_session_idr9	  _was_auto_reset_is_new_sessionr   _session_env_tokens_redact_piir  r  _pcfgr  turn_sidecar_notesreset_reasonr  continuity_notepolicyr
  had_activityshould_notifyr   reason_textr  minsdurationr   session_infor  _auto_skill_namesr  r  _combined_parts_loaded_names_snamer?  _loaded_skill
_skill_dir_display_namer  _part_lease_registry_lease_tokenr  r  rp  
_hyg_model_hyg_threshold_pct_hyg_compression_enabled_hyg_hard_msg_limit_hyg_timeout_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_cooldown_hyg_runtimerw  _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_compress
_cooldowns_cooldown_key_cooldown_until	_hyg_metar  r  _hyg_session_db_hyg_cleanup_deferred_bind_hyg_stater   _hyg_future_compressedr  
_cancelled_timeout_msgrg  _werr_hyg_new_sid_hyg_rotated_hyg_in_place
_new_count_new_tokens_comp_errr   	_warn_msg
_aux_model_aux_err_aux_msg_intro_noter  rN  rO  r  r  _onb_cfg_pb_errenv_keyhome_envr  r	  _lgcprofsethome_cmd_vc_noter  _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_idrQ  _typing_adapter_stop_with_metadata_stop_typing_stale_adapterrR  r  _intentional_silenceagent_messages_response_time
_api_calls	_resp_lenr  _show_reasoning_effectiver  r  linesdisplay_reasoningr  _reasoning_style_quoted_footer_line_bfl_footer_errr  r		  r  r  _pr_watch_eventsr0  
synth_texte2agent_failed_earlyhidden_reasoning_incompleteis_context_overflow_failure	new_entryrg  	tool_defsr+  _user_entry_skip_persistrP  r  _user_msg_id_attachedr\  rc  _already_sent_media_adapter_foot_adapter_err_adapter_already_persisted_recent_transcript_msg_expected_user_contentstatus_hintr-  	_hist_len	_err_body	_err_json
_resets_inrY  _hoursr  r(  r  r  r  s                                                                                                                                                                                                                             @@@@@r.   r
  z(GatewayRunner._handle_message_with_agentd1  sA     )++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 't%9:: 1.0D+HT'^(DE 0@@AYZZZZZZZZ"  L	s7||q((        7J!%'+$"&#' ,1))-& M ML$(!'+$'+$Io02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#: % % % $%(1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:VVVVVV33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  
 # 0!(/WY]!^!^J!)%'
FPC$1$<M&+JNN=,I,I,PS&Q&QO&44I)_ty{{%BCC	   +0" }KK>"~$9$9=.455.22488   !% @ @IeIefkIlIl m mIqYYYYYY555555373V3V#)(35?	45P5P(Z		VZ 4W 4 40
L
 (++I66 c*) )+2) ) )I
  #9~~2229$:JESWSc2d2d-4W 	." 	."&2	."*434/3046>Z/</G/>	." 	." 	." 	."
 9> 5G!* 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<%2?F?O,3N;,G,G4H@* @* @* :* :* :* :* :* :*QQ ,3+? 7%2 7%2 7%259
.8.@0A0Z0Z0\0\ -7 0:/A6=mE6J6J0J0J0J0J0J0J0J /9.@ 0: /)2 DO=N=N=N=N=N=NNK,0,W,W0;0:8Q -X -. -. -.
 EI,A/LPQ/Q/Q 59IKKB_4_ 150[4A4L12 -3NN1> 1>0H0D-. -. -.1]9M0V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 -2S :;7%2z 4>3HL3?=C[3[L48(/
<WY^(_(_5& 5&M (4 %*CO(@
 )-(?(?,6)* )* )* /3.F.L.L.N.N(N(N(N(N(N(N(N.5.?,0,M,2M3H/* /* /* )* )* )* )* )* )* )*4 (4 "%*.2.F.Y.Y,9,Dk/* /* )* )* )* )* )* )* )* LM(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 15	>[0[ -1,W0=0H-. 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  3	D6? 3	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     CCCCCC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,,	
 	
 	
o	9 6<_LFO11"!>!>/RHOPVXceiHjHjrSd!C!CDDDpr$V["==C+6'- H *//-::::::::: %2$<!!%$-0'-!%!=!=e!D!D$3"5->>%9'= "1 " "      L$"&":":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V ##$788888S $''(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,,UHn[h,ii >,,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8s  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s8  h0 /s8 0is8 iB+s8 0l s8 ls8 ls8 7m s8 m# s8 "m##s8 >n s8 n*'s8 )n**	s8 4A7p, +s8 ,
p96s8 8p99s8 ?q s8 q'$s8 &q''s8 0r s  6r=:s  <r=="s  s8  s41s8 3s44s8 8
tt
B*AR3 5BAQ8 18 6AQ8 8B?AD0B8AAC:C9AD0C:
AD)DAD$DAD0D$AD)D)AD0D-AQ8 D/AD0D0G)AQ8 LAAM MAQ8 M
ANM&ANNAQ8 NANNAAQ8 OAAP PAQ8 P
AQ PAP;P6AQ8 P;AQ Q AQ8 Q5AR3 Q87AR/R/AR3 R3
AS"R=ASSAS"T	BAV V
AWV$0AWWAWX6)AY  Y AY/Y.AY/Z"#A[ [
A[[A[[AA\9 \9
A]]A]_-BAb b
Ab1bAb,b,Ab1c9C,Bf g&CAk kBf k
AkkBf kAkkB0Bf n)Bf oAo oBf oAo&o#Bf o%Ao&o&B+Bf r Ar3 r2Bf r3
As#r=AssBf sAs#s#D#Bf xA!Ay) y(Bf y)2AzzBf zAzzB.Bf }3A~ ~ Bf ~A~~Bf ~A~~BBf @)BBB= B<Bf B=
BC.CBC)C$Bf C)BC.C.ABf EA4BF: F9Bf F:
BG)GBG$GBf G$BG)G)Bf G-1BI0 HBH<H;BI0 H<
BI+IBI&I!BI0 I&BI+I+BI0 I/Bf I0
BJI:BJJBf JBJJXBf b=A!Bd dBf d
Bed)Be
eBf e
BeeBf e*Bf fBu(fCBi,i+Bu#i,
Bi9i6Bu#i8Bi9i9Bu#jBn4j5%BkkBn4kBk*k'Bn4k)Bk*k*C	Bn4n3Bu#n4'BooBu#oBooA,Bu#qABrrBu#r
BrrBu#rBrrBBu#tBu+ t7Bu#uBu(u	Bu+ u#Bu(u(Bu+ u+Bv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.
        rG   Nrp  F)r}   rm  r  _format_session_infor  s     r.   r9  z(GatewayRunner._reset_notice_session_infok8  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  rr  r  r  rs  ru  ry  rv  rx  rz  r|   r{  rG   u:   default — set model.context_length in config to overridedetectedi@B r  Mi  Ku   ◆ Model: `r   u   ◆ Provider: 
openrouteru   ◆ Context: z	 tokens (ry  	localhostz	127.0.0.1z0.0.0.0u   ◆ Endpoint: r   )r  r  r  r  r?   rB   r@   rA   r0  r=  r2  rK  rt  rF   r^  r  rw  ry  rC   rb   r2   )r  r  r  r  r|  r  r  ry  custom_provsrH  configured_modelconfigured_providerconfigured_base_urlr[  raw_ctxrt  rX  rw  ry  
custom_ctxrr  
ctx_sourcectx_displayr  s                           r.   r  z"GatewayRunner._format_session_info8  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)r7  zYou can run: r   c              3       K   | ]	}d | V  
dS )r%  Nr  )r,   r@	  s     r.   r/   z4GatewayRunner._check_slash_access.<locals>.<genexpr>9  s(      BBGGGBBBBBBr0   r   r4
  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  rG   r  can_runr  r   ri  rN   r{   rH	  user_allowed_commandsr2   r   )r  r  r  _policy_for_sourcerl  allowed_previewr|  s          r.   r
  z!GatewayRunner._check_slash_access8  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Cr0   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 }t          | j                                                  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.
        r  Nr   r+  r|   r}  z
agent:main)r}   rN   r{   r2   rC   rq  r  r  r  r   rb   )r  r  r  r  r   rN   r+  r  matchesr  r@  s              r.   _sibling_thread_run_keysz&GatewayRunner._sibling_thread_run_keys*9  s    FK66	&)T22 	 	I?(FK66<"	 8YGc)nnM
 
 t399;;<< 	$ 	$JCg~~///u/f}}v| < <}s###r0   c                 P   ||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        |                                          }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.
        NFr!  z.restart_last_processed.jsonr  r  r  r  TrN   	update_idr	  r\  )r  platform_update_idrN   r{   rF   r  rf   r}   rD  r  r  r  r  rB   r@   r0  r1  )r  rr  r  marker_pathrH  recorded_uidr	  s          r.   _is_stale_restart_redeliveryz*GatewayRunner._is_stale_restart_redeliveryT9  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35566DD 	 	 	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{   rN   r   r(	  r  rN   r   r(	  r  r   )handle_suggestions_commandr  r  r
  zsuggestions command failed: %szSuggestions command failed: )r
  rD   r  r}   rN   rC   rF   hermes_cli.suggestions_cmdr  r   rr  )	r  rr  rQ  r  r  rN   r   r  r  s	            r.   r
  z)GatewayRunner._handle_suggestions_command9  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{   rN   r   r(	  r  r  r   )handle_blueprint_commandr  r  zblueprint command failed: %s)BlueprintCommandResultzCron blueprint command failed: )r
  rD   r  r}   rN   rC   rF   hermes_cli.blueprint_cmdr  r   rr  r   )
r  rr  rQ  r  r  rN   r   r  r  r   s
             r.   r
  z'GatewayRunner._handle_blueprint_command9  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   r  rA  r3
  )	r@   rG   rA   rB   r}   rK  r  r0  rF   )r  	goals_cfgr  s      r.   _goal_max_turns_from_configz)GatewayRunner._goal_max_turns_from_config9  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: %sr3  r|   r3  default_max_turns)
r  r  rF   r   rr  r  r,	  r  r}   r%  )r  rr  r  r   r  sidrA  s          r.   _get_goal_manager_for_eventz)GatewayRunner._get_goal_manager_for_event:  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 %srN   Nr   r  T)goal continuation: status send failed: %sr  rU  )	r#  r   rr  r}   rR  rF   r   r   r   )r  r  r   r   r~   r.  s         r.   _send_goal_status_noticez&GatewayRunner._send_goal_status_notice:  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,  rN   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.  rF   r   r   )r   r   r  r  s    r.   _deliverzHGatewayRunner._defer_goal_status_notice_after_delivery.<locals>._deliver@:  s      `33FGDDDDDDDDDDD ` ` `JCZ^_________`s   # 
AAAregister_post_delivery_callback_active_sessions_hermes_run_generationr  zAgoal continuation: post-delivery callback registration failed: %sr  )	r#  r   rr  r}   r  rF   r   rB   r2  )	r  r  r   r   r1  r  r  rY  r   s	   ```      r.   (_defer_goal_status_notice_after_deliveryz6GatewayRunner._defer_goal_status_notice_after_delivery1:  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ri  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: %sNr3  r|   r'  )gather_background_processesT)user_initiatedbackground_processesr   should_continuecontinuation_prompt)r   rv  r  rT  ri  z%goal continuation: enqueue failed: %s)r  r  rF   r   rr  r}   r%  r  r7  evaluate_after_turnrB   r5  r#  r  r  r  r$  r  )r  r  r  ri  r  r   r)  rA  mgr
_gather_bg	_bg_procsrh
  r\  r  r   r
  
cont_events                    r.   r
  z*GatewayRunner._post_turn_goal_continuation\:  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.rL
  Nguild_idguild)r}   r   rB  r0  rC  r   )rr  r>  s     r.   _get_guild_idzGatewayRunner._get_guild_id:  st     e]D11;43
## 	% 	%s|$$$3   	 SY 	 9<tr0   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._voice_input_callback_on_voice_disconnect_voice_mode_getterc                     j                                                 t          j        t          |                     d          S )NrC  )r  rB   r@  rx  r  rC   )r   r  s    r.   r   z:GatewayRunner._handle_voice_channel_join.<locals>.<lambda>:  s6    9I9M9M 0#g,,??: : r0   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_sourcesrB  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   rD  get_user_voice_channelr  _handle_voice_channel_inputrG  _handle_voice_timeout_cleanuprH  rI  rF  rF   r   r   rC   rE   r\   r$  r0  r   _voice_text_channelsto_dictrN  r  r@  rN   rR  r\  r   )r  rr  r   rB  voice_channelr  r  	err_lowers   `       r.   _handle_voice_channel_joinz(GatewayRunner._handle_voice_channel_join:  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: %srC  Tr  rG  zLeft voice channel.)r#  r  rD  r   rY  rX  rF   r   r   r  r@  rN   r   rR  rZ  rG  )r  rr  r   rB  r  s        r.   _handle_voice_channel_leavez)GatewayRunner._handle_voice_channel_leave:  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.
        rC  TrZ  N)r  r@  rx  r  rR  r  rB   rZ  )r  r   r   s      r.   rQ  z+GatewayRunner._handle_voice_timeout_cleanup;  so    
 HM)97CCD   -##H$455++GWt+LLLLLr0   rB  r  
transcriptc                    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,   rg  txtr@  rA  s      r.   r  z@GatewayRunner._is_duplicate_voice_transcript.<locals>.<listcomp>,;  s:     
 
 
CRx>)) I)))r0   Tr	  r  )difflibr_  r)   r   rD   rE   rD  rz  r}   r@   rA   r  rB   r   ratiorb   )r  rB  r  r]  r_  r  r  recent_storerecentr  priorr@  rA  s              @@r.   _is_duplicate_voice_transcriptz,GatewayRunner._is_duplicate_voice_transcript;  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ur0   c           	      Z  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}
 t/          ||t0          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).
        NrN  channel)rN   r   r  rQ  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)rB  rC  )r  r   rv  rL
  )r  rB   rx  r  rR  r}   r  	from_dictrC   r  rQ  rP  r   rr  ri  ri  _clientget_channelr4  r   rF   typesrm  r  r  r}  r/  )r  rB  r  r]  r   
text_ch_idsource_datar  rk  	safe_textrm  rr  s               r.   rP  z)GatewayRunner._handle_voice_channel_input?;  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	 	*)))))$*'FFF	
 
 
 $$U+++++++++++s   "A/G 
GGrR  r  r$  c                 V   |r|                     d          rdS |j        j        }| j                            |                     |j        j        |          d          }|j        t          j	        k    }|dk    p|dk    o|}|sdS 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:FrC  rB  rD  c              3      K   | ]K}|                     d           dk    o-t          d |                     d          pg D                       V  LdS )r[  rb  c              3   r   K   | ]2}|                     d           pi                      d          dk    V  3dS )r  r   r  Nr  )r,   tcs     r.   r/   zCGatewayRunner._should_send_voice_reply.<locals>.<genexpr>.<genexpr>;  s[         
##)r..v66:JJ     r0   r  N)rB   rb  )r,   r\  s     r.   r/   z9GatewayRunner._should_send_voice_reply.<locals>.<genexpr>;  s       
 
  GGFOO{*   77<006B    
 
 
 
 
 
r0   T)r   r  r   r  rB   r@  rN   rv  r  r}  rb  )
r  rr  rR  r  r$  r   
voice_modeis_voice_inputshouldhas_agent_ttss
             r.   rV  z&GatewayRunner._should_send_voice_reply;  s    $  	8..x88 	5,&%))$//%,:OQX*Y*Y[`aa
,0AA 5  ?l*=~ 	  	5  
 
 &
 
 
 
 
  	5  	, 	5tr0   c                 H    t          t          | j        dd                    S )zFReturn whether inbound voice/STT transcripts should be echoed to chat.stt_echo_transcriptsT)r   r}   rG   r  s    r.   r  z*GatewayRunner._should_echo_stt_transcripts;  s    GDK)?FFGGGr0   r   c                   K   ddl }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 |j        j        t          j
        k    rdnd}
t          j                            t          j                    dd|                                j        dd	          d
|
           }t	          j        t          j                            |          d           t'          j        |||           d{V }	 t+          j        |          }nt# t*          j        t0          f$ r[ t2                              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                            |          sat2                              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        |          }|tI          |          }d|d<   nddi}|j        j%        |||d} |j&        di | d{V  n4# tN          $ r'}t2                              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.r   N)r  _strip_markdown_for_tts  oggmp3hermes_voice
tts_reply_r   r   T)rL  )r   output_pathz.Auto voice reply TTS returned invalid JSON: %sr   r  r  zAuto voice reply TTS failed: %sr  play_in_voice_channelrY  
send_voicer5  )r   
audio_pathr-  r~   zAuto voice reply failed: %sr   r  )(uuidtools.tts_toolr  r  r`   r   rd   r  rN   rx  r  rg   r2   tempfile
gettempdiruuid4hexmakedirsdirnamer  r  r  r  rG  r=  r   r   rB   isfiler#  rD  r   rY  r  r  rR  rA   r   r  rF   )r  rr  r   _uuidr  actual_pathr  r  tts_textr  	audio_extresult_jsonr.  r   rB  r]  r^  send_kwargsr  s                      r.   rW  zGatewayRunner._send_voice_reply;  sp     
E	SSSSSSSS..tETE{;;H x !+.$7  IaLLLL   D q "'!6(:K!K!KQVI#%%~AU[[]].ss3AAiAA J K
33dCCCC ' 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   M A


AACM "D7 6M 7=F(4M  F
F"!F"'F((A;M /I
IIDM O 
N%NO NO N//
N<;N<O3O"!O3"
O/	,O3.O/	/O3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   )r  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     r.   r  z>GatewayRunner._deliver_media_from_response.<locals>.<listcomp>J<  s/    OOOa444b9OOOr0   )r   imagesr~   Nz0[%s] Post-stream image batch delivery failed: %s)is_voicer   r  r~   r   
video_pathr~   r   r  r~   z*[%s] Post-stream media delivery failed: %sz'Post-stream media extraction failed: %s)pathlibr   urllib.parser  ri  r  r  extract_mediafilter_media_delivery_pathsextract_imagesrR  r  r  r|  rE   rb   send_multiple_imagesr   rF   r   r   r   rN   r  
send_videosend_document)r  rR  rr  r   r   force_document_attachmentsr  r  media_filescleaned_thread_meta_VIDEO_EXTS_IMAGE_EXTSr  non_image_media
media_pathr  r  r  r  r  s                       @r.   rX  z*GatewayRunner._deliver_media_from_response	<  s%     , 	!     000000J	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  rq  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``.
        rG   Nrp  F)r}   _run_background_task_innerr  rm  )r  r  r  r
  r  r  rq  rc  s           r.   _run_background_taskz"GatewayRunner._run_background_taskp<  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	  ry  u   ❌ Background task z, failed: no provider credentials configured.r   _get_platform_toolsr@  disabled_toolsets)r  r  )r  r|   ru  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  rX  rH  r  Tverbose_loggingFr  r  r  r  r  providers_allowedonlyproviders_ignoredignoreproviders_orderorderprovider_sortsortprovider_require_parametersrequire_parametersprovider_data_collectiondata_collectionr3  rN   r  user_id_altrQ  r   r(	  r+  r  r  r  fallback_model)r  r
  r  )r  r  rB   r  r  rQ  r   r(	  r+  r  r}   r  r  run_conversationr  )r@  r  r  r  enriched_promptrH  r  prr  r  r  r
  
turn_router	  s    r.   run_syncz:GatewayRunner._run_background_task_inner.<locals>.run_sync<  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ri  r  zError: r	  r  r   u&   ✅ Background task complete
Prompt: "z"

rI  z(No response generated))r   	image_urlcaptionr~   )r  r  r  rZ   r  r  )r   
image_pathr~   r  z"

(No response generated)zBackground task %s failedz	 failed: ).r=  r  r#  r   r   rN   rR  r?   r  rB   r   r   r  hermes_cli.tools_configr  rH	  r  rW  r  r  r  r  r  r  r   r   rb   r  rF   r  r  ri  r  r  r  
send_imager  r`   rg   r  rE   r  r  send_image_filer  r   )-r  r  r  r
  r  r  rq  r   _thread_metadatar  r  r  rR  r  r  rg   ry  r  r  r.  rR  r  r  r  text_contentr  headerr  alt_text_should_send_media_as_audior  r  r  	_is_voicer  r  r  r  r  rH  r  r  r  r  r	  s-   ` ``                               @@@@@@@@@@r.   r  z(GatewayRunner._run_background_task_inner<  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}   r@   rA   rB   )r   r  mes     r.   _fieldz>GatewayRunner._get_telegram_topic_capabilities.<locals>._fieldk=  s    r4   )r4((( \488J*d++ ,
0B0B!~~d+++"d## $vvd||#4r0   has_topics_enabledallows_users_to_create_topics)r  r  r  )r#  r}   r   r  rF   r   rr  rC   )r  r  r   botr  r  s        @r.    _get_telegram_topic_capabilitiesz.GatewayRunner._get_telegram_topic_capabilities_=  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.r  r   rT  z*Failed to send Telegram System topic intror  pin_chat_message)r   rT  disable_notificationz)Failed to pin Telegram System topic intro)r#  r   r}   r   r0  rF   r   rr  r   rC   r   r  )r  r  r   r  create_topicrT  send_resultr  s           r.   _ensure_telegram_system_topicz+GatewayRunner._ensure_telegram_system_topic{=  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 Settingsr  )r   r  r  r~   z)Failed to send Telegram topic setup imageTr   )r#  r   r   r   r]   r^   r_   rf   r  rC   r  rF   r   rr  )r  r  r   r  s       r.    _send_telegram_topic_setup_imagez.GatewayRunner._send_telegram_topic_setup_image=  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r%	  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.r`  rN  r|   Hermes Chatx   Nu   r   )r)   r   rC   rD   r   r  r  r%	  r  s      r.   _sanitize_telegram_topic_titlez,GatewayRunner._sanitize_telegram_topic_title=  sp    &c%+2&6&677==?? 	! = w<<#dsdm**,,u4Gr0   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)rN   rx  r  r+  r   r}   r  r  s     r.   _is_discord_auto_thread_lanez*GatewayRunner._is_discord_auto_thread_lane=  s{     Ox// H H,HWV%:EBBCCH V%&&H WV%?FFGG	
r0   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.
        r`  rN  r|   r   r  M   r   )r)   r   rC   rD   r  r  r  r  s      r.   _sanitize_discord_thread_titlez,GatewayRunner._sanitize_discord_thread_title=  st     &c%+2&6&677==?? 	! =W""0"==DDFFNGr0   c           	        K   t          j        | j        |           d{V sdS t          | dd          r|                     |          nd}|dS t          |dd          }|dS |                     |          }	  |t          |j                  |t          |dd                     d{V  dS # t          $ r  t          
                    dd           Y dS w xY w)	zCBest-effort semantic rename of a newly auto-created Discord thread.Nr  rename_threadr  )only_if_current_namez@Failed to rename Discord auto-thread for generated session titleTr   )r  r  r  r}   r#  r  rC   r  rF   r   rr  )r  r  r3  r%	  r   r  r1	  s          r.   -_rename_discord_auto_thread_for_session_titlez;GatewayRunner._rename_discord_auto_thread_for_session_title=  sF      &t'H&QQQQQQQQ 	F6=dJPT6U6U_$**6222[_?F$?? F99%@@	l-F$%%%,V5OQU%V%V           
  	l 	l 	lLL[fjLkkkkkk	ls   <5B3 3&CCc                    |r|                      |          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.Nr  z1Discord semantic thread rename failed to scheduler   log_messager%   c                     	 |                                   d S # t          $ r  t                              dd           Y d S w xY w)Nz%Discord semantic thread rename failedTr   r.  rF   r   rr  futs    r.   _log_rename_failurezSGatewayRunner._schedule_discord_semantic_thread_rename.<locals>._log_rename_failure>  sX    U

 U U UDtTTTTTTU    &AAr  )r  r  r  rW  r}   	is_closedr  r4  rF   r   r  r   ro  r  r  r3  r%	  r   copied_sourcer   r  s           r.   (_schedule_discord_semantic_thread_renamez6GatewayRunner._schedule_discord_semantic_thread_rename=  s2     	D==fEE 	F	8+--DD 	8 	8 	84$77DDD	8<4>>++<F	#'/77MM 	# 	# 	#"MMM	#)>>}jZ_``K	
 
 
 >F	U 	U 	U 	U 	  !455555s!   / AA)A> >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  r3  r|   z5Failed to verify Telegram topic binding before renameTr   rename_dm_topic)r   r  r   r  edit_forum_topiceditForumTopic)r   message_thread_idr   z8Failed to rename Telegram topic for auto-generated title)r  r  r  r   r  $_telegram_topic_auto_rename_disabledr#  r}   r   r   rC   rF   r@   rA   r0  rB   r   rr  r  r0  r=  r2  )r  r  r3  r%	  r   get_infooperator_topicr  ra  
topic_namerename_topicr  r   s                r.   (_rename_telegram_topic_for_session_titlez6GatewayRunner._rename_telegram_topic_for_session_title>  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).
        rG   Nr  Fru  disable_topic_auto_rename>   r;   r<   r=   r>   )
r}   rG   r  rB   rN   r@   r   rC   rD   rE   )r  r  r  ru  r{   s        r.   r#  z2GatewayRunner._telegram_topic_auto_rename_disabledk>  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{{r0   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.Nr  z.Telegram topic title rename failed to scheduler  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    r.   r  zPGatewayRunner._schedule_telegram_topic_title_rename.<locals>._log_rename_failure>  sX    R

 R R RADQQQQQQRr  r  )r  r#  r  r  rW  r}   r  r  r4  rF   r   r(  r   ro  r  s           r.   %_schedule_telegram_topic_title_renamez3GatewayRunner._schedule_telegram_topic_title_rename>  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/  rC   r   rD  rz  rB   $_TELEGRAM_CAPABILITY_HINT_COOLDOWN_Sr  s         r.   %_should_send_telegram_capability_hintz3GatewayRunner._should_send_telegram_capability_hint>  s     t;<< 	302D-fn*++ 	4oo044WcBB:AAA558)'2tr0   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    r.   _telegram_topic_help_textz'GatewayRunner._telegram_topic_help_text>  s    M	
 	
r0   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  r5  r   rC   r   r  r  rF   disable_telegram_topic_moder   r   r}   r@   rA   r   )r  r  r5  r   currently_enabledr   r	  stores           r.   %_disable_telegram_topic_mode_for_chatz3GatewayRunner._disable_telegram_topic_mode_for_chat>  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|   rc	  )r   r  limitz)Failed to list unlinked Telegram sessionsTr   zPrevious unlinked sessions:r   r|   r%	  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_userrC   r   r  rF   r   rr  rb   rB   rD   extendr2   )	r  r  r  rC  r@  r3  r%	  r  r  s	            r.   #_telegram_topic_root_status_messagez1GatewayRunner._telegram_topic_root_status_message>  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|   r!  zNThat session is not a Telegram session and cannot be restored into this topic.r  z3That session does not belong to this Telegram user.r  r  r3  z9That session is already linked to another Telegram topic.restored)r   r  r  r  r3  managed_modezalready linkedr[  rb  r   zSession restored: z

Last Hermes message:
)r  r  resolve_session_idrD   r  rC   rB   r  #is_telegram_session_linked_to_topicr0  r   r  r  r  r2  get_session_titler  get_messagesrF   )r  rr  rA  r  r3  r@  linkedcurrent_bindingr  r   r%	  last_assistantr   rR  s                 r.   _restore_telegram_topic_sessionz-GatewayRunner._restore_telegram_topic_session%?  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|   ra  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_toolrN  rO  rP  r  rc   r  r@  r   rb   r2   rH	  r   rS  r}   rq  r  r@   r  rF   r   rr  r  r,	  r  rR  r3  r   )r  rr  r   rN  rO  rP  r  old_servers	new_toolsconnected_serversaddedr  reconnectedr  rS  r	  rX	  	_sess_keyr	  r	  _excchange_partstool_summarychange_detail
reload_msgr  r  s                              r.   _execute_mcp_reloadz!GatewayRunner._execute_mcp_reloada?  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   rn
  r  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``
        Tr  Ndestructive_slash_confirmchoicec                 Z  K   | dk    rd dS | dk    ra	 ddl m}  |dd           t                              d	           n2# t          $ r%}t                              d
|           Y d }~nd }~ww xY w              d {V }| dk    rd}t          |t                    r||z   S |S |S )Nrn  u   🟡 /z# cancelled. Conversation unchanged.r<  r   )save_config_valuez#approvals.destructive_slash_confirmFz8User opted out of destructive slash confirm (session=%s)z5Failed 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.)r  re  r   ri  rF   r   r@   rC   )rc  re  r   r.  noter   ro
  r  s        r.   _on_confirmzCGatewayRunner._maybe_confirm_destructive_slash.<locals>._on_confirm@  s)     !!LLLLL!!
555555%%&KUSSSKKR#    !   NNOQT        #799______F!!R 
 fc** )!D=( Ms   -A 
A4A//A4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`._)rr  r   r%	  r   handler)_read_user_configr@   rA   rB   r   rF   r  r  rC   _typed_command_prefix_forrN   _request_slash_confirm)r  rr  r   r%	  rn
  ro
  confirm_requiredrQ  r  rg  _pprompt_messager  s     `  `      @r.   r
  z.GatewayRunner._maybe_confirm_destructive_slash?  s     4  	((**C0:30E0EO,,,4I)T** Z#'	6QSW(X(X#Y#Y  	 	 	D	   	# ??????"225<@@	c 	 	 	 	 	 	 	 	< ++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   r8
  r  NrZ   F)r   r%	  r   r  r>
  r~   r  Tz*send_slash_confirm failed for %s on %s: %s)r
  r9
  r  r  r}   r  r   r  nextregisterr#  rR  r  send_slash_confirmr   rF   r   rr  rN   )r  rr  r   r%	  r   rh  r  r  r  counterr  r>
  r   r~   used_buttonsbutton_resultr   s                    r.   rk  z$GatewayRunner._request_slash_confirm6@  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   r  )rK  r  r@   rA   rF   )r  r  rQ  s      r.   ri  zGatewayRunner._read_user_configz@  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.rN   Nr   r  r+  rT  r+  r  scope_idslack_team_id)r  r}   rx  ry  rA   rC   )r  r  r  r~   team_ids        r.   rR  z)GatewayRunner._thread_metadata_for_source@  s     33FJ--FIt,,FK..fk488 3 Zwv|UY7Z7Z 4 
 
 6:t,,>>fj$77G 9B//,/LL)r0   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.Nr  r+  r   T telegram_dm_topic_reply_fallback>   r|   r;   direct_messages_topic_idtelegram_reply_to_message_idrT  )_is_telegram_dm_topic_targetrC   rx  ry  )	r  rN   r   r  r+  r  r   r~   r  s	            r.   r  z)GatewayRunner._thread_metadata_for_target@  s     4$/#;,, - 
 
 	T <@H78 i..C ;s)++7:34".;>?R;S;S78x~%%*=*I &))<%=%=H\"r0   r}  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   )rx  r  r}   r   r   rC   r@   rA   rF   r   rr  )rN   r   r  r+  r   get_dm_topic_info
topic_infos          r.   r  z*GatewayRunner._is_telegram_dm_topic_target@  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  )rr  s    r.   r  z%GatewayRunner._reply_anchor_for_event@  s     'u---r0   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}   rp  r  r  _watch_update_progressr  rW  r   rr  )r  existing_tasks     r.   r  z1GatewayRunner._schedule_update_notification_watch@  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       @      @poll_interval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          }|rO"rMt          |          &| j
                            &           |                     &"|||           %|
s| d" }
 n# t          $ r Y w xY w# r"sQt                              d           |                                s|                                r$                                |	k     r|                                r|                                  d{V rdS t          j        |           d{V  |                                s|                                r$                                |	k     |                                s|                                rC|                                s/|                    d           |                                  d{V  dS dt$          dt$          fdd}$                                #d!d4 !"#$%&fd}$                                |	k     r|                                r|                                rU	 |                                }t'          |          |k    r!||d         z  !t'          |          }n# t(          $ r Y nw xY w |             d{V  	 |                                                                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           | j                            |
d           dS |                                rU	 |                                }t'          |          |k    r!||d         z  !t'          |          }n# t(          $ r Y nw xY w!                                r+$                                #z
  |k    r |             d{V  |                                r|
r| j                            |
          s	 t          j        |                                          }|                    d!d          }|                    d"d          }|r |             d{V  d#}t=          t?                     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-| d.t1          %&                     d{V  d| j        |
<   t                              d/|
|dd0                    n># t
          j"        t(          f$ r%}t          !                    d1|           Y d}~nd}~ww xY wt          j        |           d{V  $                                |	k     |                                st                              d2|           |                    d            |             d{V  	                      "d3t1          %&                     d{V  n# t          $ r Y nw xY w|||||fD ]}|                    d           t           d z                      d           | j                            |
d           dS dS )5a  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_coder2
  NrN   r   r+  r  r  rT  r  r}  zOUpdate watcher: cannot resolve adapter/chat_id, falling back to completion-only124r   r%   c                 .    t          j        dd|           S )Nz\x1b\[[0-9;]*[A-Za-z]r|   )r)   r   r   s    r.   _strip_ansiz9GatewayRunner._watch_update_progress.<locals>._strip_ansiSA  s    62B===r0   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     r.   r  zOGatewayRunner._watch_update_progress.<locals>._flush_buffer.<locals>.<listcomp>hA  s&    VVVeAa)mO,VVVr0   r   ```

```rR   r   zUpdate stream send failed: %s)	rD   rD  rM	  r   r   r   rF   r   rr  )chunkschunkr  r  r  r  r   bufferr   last_stream_timer   r~   rN   s      @@r.   _flush_bufferz;GatewayRunner._watch_update_progress.<locals>._flush_bufferZA  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(r;   u   ✅ Hermes update finished.rR   r   u(   ❌ Hermes update failed (exit code {}).z&Update finished (exit=%s), notified %sz$Update final notification failed: %sTr  r1
  r  r  Fsend_update_prompt)r   r  r  r  r~   z%Button-based update prompt failed: %sz (default: ry  typed_command_prefixr%  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.r  )#r  r  r  rD  rf   r  r  r  rB   rx  r  r  rF   r   r   r  rp  rP  rC   r   rd   rD   r0  r   r   formatri  r   r   r   r}   r   r  rr  rG  )'r  r  r  r  pending_pathclaimed_pathr  exit_code_pathr
  r  r  rg   r"	  r  r+  r  rT  
bytes_sentr  r   exit_code_rawr  r  r  prompt_dataprompt_textr  sent_buttonsbtn_errdefault_hintrm  r  r   r  r   r  r   r~   rN   s'                                  @@@@@@@@r.   r  z$GatewayRunner._watch_update_progress	A  sj      $&<<#&DD"%99%(;;"%::'))99;;( !<0 	 	D{{}} "j)9)9::G#*;;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))%000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"9"9w<<*44"gjkk&::F),WJ"   #moo%%%%%%%N$2$<$<$>$>$D$D$F$F$M#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+//TBBB !!## )3355G7||j00'*++"66%(\\
   D ||~~ &499;;1A#Ao"U"U#moo%%%%%%% ""$$ ,H ,H 7;;KHH,H*H"&*[-B-B-D-D"E"EK"-//(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 #/ # #        DH3K@$GVabecebeVfggg,g6 H H HLL!CQGGGGGGGGH -.........U iikkH$$Z $$&& 	?NNA7KKK%%e,,,-//!!!!!!!llC9(XVVV #          
    "L+$k3 * *D))))..66$6GGG'++K>>>>>!	? 	?s   C5F
FF&AN* *
N76N7CR 
SR==S5AU9 9
VV<B]+ 1Z4 3]+ 4
[#>[]+ [##B]+ +^&^!!^&1-a 
a,+a,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          }|                                st          
                    d           d}|}|                    |           	 |rZ|                    d           |                    d           |                    d           |                    d           dS dS |                                                                pd}t          |          }d}|                                r|                                }t          |          }| j                            |          }|s|	rt          
                    d|           d}|}|                    |           	 |rZ|                    d           |                    d           |                    d           |                    d           dS dS |r|	r|                     ||	||
||          }t!          j        dd|                                          }|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  FTr  rN   r   r+  r  rT  z2Update notification deferred: update still runningr;   r|   z:Update notification deferred: %s adapter not connected yetr  z\x1b\[[0-9;]*mr  r4
  iTNr   u!   ✅ 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.rR   r   z0Sent post-update notification to %s:%s (exit=%s)z#Post-update notification failed: %s)r  rf   r4  rF  r   r  r  r  rB   r   ri  rD   r0  rx  r  r  r)   r   r   r   r   rF   r   )r  r  r  r  r  cleanupactive_pending_pathr"	  r  r   r+  r  rT  r  r  r8  rN   r   r~   r\  r  s                        r.   r  z'GatewayRunner._send_update_notificationA  s      $&<<#&DD"%99%(;;""$$ 	\-@-@-B-B 	5*^	7""$$ $ ((6666( $ $ $'..00 $#h  7#**d*;;;##t#444""d"333%%%66666	7 7k$ $$ "((** d  7#**d*;;;##t#444""d"333%%%66666	7 7a j!7!7!9!9::G";;z22Lkk),,GK00IK00I \22J!((** PQQQ&2#$$\222H  7#**d*;;;##t#444""d"333%%%66666	7 7E +4466<<>>E#MM**I F!!## 1$..00  --Hm''11G w  P     &2#$$\222L  7#**d*;;;##t#444""d"333%%%66666	7 7I   7  ;;'(2# <    12v>>DDFF 
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$ 0CR$ CR$ #T1 $
S.S	T1 ST1 1AVc           
         K   t           dz  }|                                sdS 	 t          j        |                                          }|                    d          }|                    d          }|                    d          }|                    d          }|                    d          }|r|s	 |                    d	           dS t          |          }| j                            |          }	|	s4t          
                    d
|           	 |                    d	           dS | j        j                            |          }
|
;|
j        s4t                              d|           	 |                    d	           dS |                     ||||||	          }|	                    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 # t*          $ 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  NrN   r   r+  r  rT  Tr  z6Restart notification skipped: %s adapter not connectedzJRestart notification suppressed: %s has gateway_restart_notification=falser  u;   ♻ Gateway restarted successfully. Your session continues.rR   r   r  Fz3Restart notification to %s:%s was not delivered: %sr  r  z"Sent restart notification to %s:%szRestart notification failed: %s)r  rf   r  r  r  rB   r   rx  r  r   rr  rG   r  r  ri  r  r   rC   r   r}   r   rF   )r  notify_pathrH  r  r   r+  r  rT  rN   r   r  r~   r.  r  s                 r.   r  z(GatewayRunner._send_restart_notificationhB  s     "%;;!!## 	4@	0:k335566D88J//Lhhy))G--I--I,//J w n $/////k  --Hm''11G L    \ $/////Y  ;044X>>L'0Y'`    L $/////I 77#$. 8  H #<<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J AJ /AJ BJ :AJ 
K"&KK% K""K% %K=r  r  c                "  K   t                      }|pt                      }d}| j                                        D ]Q\  }}| j                            |          }|r|j        s*| j        j                            |          }|(|j        s!t          
                    d|j                   s|j        t          |j                  |j        rt          |j                  ndf}	|	|v s|	|v r	 |                     ||j        |j        |          }
|
r@|                    t          |j                  |t!          |
|                     d{V }nqt!          |          }|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}~Kd}~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=falserw  rR   r   r  TFz6Home-channel startup notification failed for %s:%s: %sr  r  z/Sent home-channel startup notification to %s:%s)rc   r  r  rG   r  r   r  rB   r  r   ri  r{   rC   r  r  r   r   r}   r   re   rF   )r  r  	deliveredskippedr   rN   r   r6  r  r  r~   r.  _startup_metar   s                 r.   r  z6GatewayRunner._send_home_channel_startup_notificationsB  s"      :=	'#%%G!%!4!4!6!6 =	 =	Hg;//99D t| ;044X>>L'0Y'mN   nc$,&7&7PTP^9hT^9L9L9LdhiF  Fi$7$7,;;LN#	 <    P#*<<DL))!=hQY!Z!Z!Z $0 $ $      FF %A($S$S$SM$ P'.||--#%2 (4 ( ( " " " " " " (/||C4E4Ew'O'O!O!O!O!O!O!O%'&)T*J*Je*S*SNNP 1NOO	   f%%%ENL   
    LNL	        s   0D!I;I
J'JJc                 f   ddl m} t          | dd          pi }|                    |j        j                  }t          |dd          } ||j        j        j        |j        j        |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|	
  
        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|   rw  )
rN   r   r(	  r  r  rQ  r  rT  rw  async_delivery)r
  r  r}   rB   r  rN   r{   r   r(	  r  rC   r  rQ  r  rT  )r  r   r  	_adaptersrg  _async_deliverys         r.   r2  zGatewayRunner._set_session_env C  s.    	=<<<<< D*d339r	==!899!(,EtLL^,2N*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*
 
 
 	
r0   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      r.   rJ  z GatewayRunner._clear_session_env!C  s+    >>>>>>6"""""r0   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_executorr  )r  funcrQ  r   r  s        r.   r  z+GatewayRunner._run_in_executor_with_context&C  sx      '))nn)T)  G
 	
 
 
 
 
 
 
 
 
 	
r0   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.r  Nr  Fz.Gateway is shutting down; executor unavailabler  	_shutdownrc	  r  )max_workersthread_name_prefix)	r}   r  r  r  rW  
concurrentfuturesThreadPoolExecutorr  r  r  executors      r.   r  zGatewayRunner._get_executor1C  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.r  NTr  F)rl  cancel_futures)rl  )r}   r  r  ru  r=  r  s      r.   r	  z GatewayRunner._shutdown_executorDC  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_providerr  r|   Nr  r  rO  uO   image_routing: session runtime resolution failed, falling back to config — %s)rO  u;   image_routing: decision failed, falling back to text — %sr   )agent.image_routingr  r  r  r  rK  r  r@   rA   rD   r  rC   rB   rF   r   rr  )r  r  r  r	  r  r  r  r  r  r  rQ  resolved_providerresolved_modelresolved_requested_providerneeds_session_runtimehas_session_identityr  r  runtime_providerruntime_requested_providerr   s                        r.   r  z&GatewayRunner._decide_image_input_modeWC  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_textr  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   rr  r  r  rB   rb   rF   r  r2   )r  r  r  r  r  analysis_promptenriched_partsrg   r  r.  r   r  r  s                r.   r  z)GatewayRunner._enrich_message_with_visionC  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                 j  K   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
}	 g }
g }|D ]}	 t                              d|           t          j        |	|           d{V }|d         r7|d         }|                    |           |
                    d| d           nG|                    dd          }t                              d||           |
                    d           # t"          $ r;}t                              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.
        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_audiozTranscribing user voice: %sr  r]  r  r  rU  z%Voice transcription failed for %s: %sz([voice message could not be transcribed]zTranscription error: %s)r}   rG   r`   rg   abspathr  rb   r2   rD   tools.transcription_toolsr  r   rr  r  r  rB   ri  rF   r  )r  r  r  notesrg   abs_pathduration_strr  _placeholderr  r  successful_transcriptsr.  r]  r  r  s                   r.   r  z0GatewayRunner._enrich_message_with_transcriptionC  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:>>>>>>,. 	R 	RDR:DAAA&01A4HHHHHHHH)$ V!'!5J*11*=== #))*;j*;*;*;<<<<"JJw@@E KK GuUUU"))*TUUU R R R6:::%%&PQQQQQQQQR  		2[[00F LL 6Y__..,>>555 J 11i113III111000s   &B<F##
G(-0G##G(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  rb   )r  rr  r  r  r  rg   s         r.   rY  z(GatewayRunner._pending_event_audio_paths>D  se    !#UL$77=2
 ,, 	) 	)GAt(22 )""4(((r0   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.
        rX   _gateway_pending_stt_transcriptsNr   r|   )r   r}   rq  rY  r  r7  )	r  rr  r  cached_textcached_transcriptsr  r   enriched_textr  s	            r.   $_transcribe_pending_audio_event_oncez2GatewayRunner._transcribe_pending_audio_event_onceGD  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4r0   
Transcriptr~   rE  transcriptsrE  c                B  K   |r'|                                  r|t          |dd          rdS t          |dd           |D ]]}	 |                    |j        d| d|           d{V  +# t
          $ r&}t                              d||           Y d}~Vd}~ww xY wdS )	z<Echo pending-event STT transcripts to the chat at most once.N_gateway_pending_stt_echo_sentFTr^  r  r   z%s echo failed (non-fatal): %s)r  r}   r7  r   r   rF   r   rr  )	r  rr  r   r  r  r~   rE  txecho_excs	            r.   "_echo_pending_stt_transcripts_oncez0GatewayRunner._echo_pending_stt_transcripts_onceeD  s      	4466	 u>FF  F7>>> 	V 	VBVllN%%%%% #          
  V V V={HUUUUUUUUV	V 	Vs   'A,,
B6BB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)	rY  r  _UNSETrR  r  r  rF   r   r   )r  rr  r   r  r   rE  r~   r  r  	echo_meta	trans_excs              r.   rZ  z0GatewayRunner._transcribe_and_echo_pending_voiceD  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r0  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: %srN   r+  r   zcSynthetic event source unresolvable: session_key=%r platform=%r chat_type=%r chat_id=%r evt_type=%sr   r7  r  z9Synthetic process event has invalid platform metadata: %rr  r  rQ  )rN   r   r+  r  r  rQ  )r:  r  rC   rB   rD   r  r  r  r}   r  rF   r   rr  r  r/  rE   r   rx  r{   r  r  r  r	  r2  )r  r0  r  r  derived_platformderived_chat_typederived_chat_idrc  r   cached_sourcer  r
  r+  r   rN   r  s                   r.   _build_process_event_sourcez)GatewayRunner._build_process_event_sourceD  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   r3  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 %sr3  r4  r{   )r  )r  parent_session_idr  rT  )r   rv  r  rA  rT  r~   uA   Watch pattern notification — injecting for %s chat=%s thread=%sr%  )r  rC   rB   rD   r/  r  rx  r*  gateway.waker  r  r   ri  rF   r   r   rN   r{   r  r   r  r  r$  r  r/  r  )r  r  r0  r  raw_sidr	  r   r  r  r  r
  r  r  _wake_push_okr~   r	  synth_events                    r.   rP  z(GatewayRunner._inject_watch_notificationD  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_idNr2  r3  r}  )rC   rB   )r0  r=  producer_idr}  s       r.   _completion_delivery_identityz+GatewayRunner._completion_delivery_identitynE  s     swwv,"--)))cggo66<"==K2=GHk2..4G|##cggl339r::K..J ;z5 +z::tr0   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  Nrz
  z7Async-completion pre-flight parent lookup failed for %sTr   r|  r
  deliverr
  r9   z4Async-completion pre-flight tip lookup failed for %s)r}   r  rF   r   rr  rB   r
  )r  r	  r  r_   tip_session_idtips         r.   _classify_completion_targetz)GatewayRunner._classify_completion_targetE  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_deliveryr	  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   rz
  )release_completion_deliveryz*Could not release durable completion claimr  )complete_completion_deliveryz5Could not acknowledge durable async completion %s: %s)r  rB   rC   r1  r  r   
__import__r  r  rF   r   r   rD   r  r  rr  r  r  r  r  re   rP  rW  r   r  r  r  )r  r  r0  identitydurable_claim_iddurable_delegation_idr  r   r	  verdictr  r  r  injection_resultr  s                  r.    _deliver_completion_notificationz.GatewayRunner._deliver_completion_notificationE  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.
        rN   Nr  r|   r+  r   r  )rB   r/  )r  r0  r6  s      r.    _enrich_async_delegation_routingz.GatewayRunner._enrich_async_delegation_routing:F  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 	3r0   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  rp  r<  r  r  rI  rF  rG  rF   rB   rb   rH  r$  rC  r"  r   r  rr  )	r  rl  r  rK  async_eventsr0  r  r  r  s	            r.   r  z'GatewayRunner._async_delegation_watcherOF  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  r3  check_intervalr  r|   rN   r   r  r  rQ  rT  Nnotify_on_completeFzCProcess watcher started: %s (every %ss, notify=%s, agent_notify=%s)rC  Tz"Process watcher ended (silent): %s)r;  r  )redact_terminal_output)
strip_ansir   rl  r   r   rZ   u'   [… output truncated — showing last z chars]
r   r2  r+  r}  r  completion_reasonexitedtermination_sourcer8  ug   Process watcher: completion for %s already consumed via wait/log — skipping raw notification (#65379)>   rB  r.  r  >   Nr   iz[Background process z finished with exit code z~ Here's the final output:
rO  rR   r   zWatcher delivery error: %srB  iz is still running~ New output:
zProcess watcher ended: %s)r<  r  rB   rC   rD   r  r   rr  r  rp  r-  r   output_bufferr;  is_completion_consumedr   r*  tools.ansi_stripr+  r}   r   r  r  r"  r  r  r{   r   r   rF   r  )'r  r  r  r3  rl  r  r
  r   r  r  rQ  rT  agent_notifynotify_moder@  last_output_lencurrent_output_lenhas_new_outputr;  	_pr_checkr*  r+  _command_raw_LIMIT_tail_nlrA  completion_evtr  r  rn  
new_outputr  r   r  r  	send_metar  s'                                          r.   r  z"GatewayRunner._run_process_watcherF  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  rr  )r  rM  )r9   r  )r9   r:   )r9   	threshold)r9   model_thresholds)r9   threshold_tokens)r9   codex_gpt55_autoraise)r9   codex_app_server_auto)r9   target_ratio)r9   protect_last_n)r9   proactive_prune_tokens)r9    proactive_prune_min_result_chars)r9   "proactive_prune_min_reclaim_tokens)r9   min_tail_user_messages)r@  r  )rr
  r  )r   r  )r   r  )r   r  )r   r  _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     r.   r  zDGatewayRunner._empty_honcho_cache_busting_config.<locals>.<dictcomp>lG  s    DDDcTDDDr0   )_HONCHO_CACHE_BUSTING_KEYS)clss    r.   "_empty_honcho_cache_busting_configz0GatewayRunner._empty_honcho_cache_busting_configjG  s    DDS%CDDDDr0   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)rN  r|   rL  )plugins.memory.honcho.clientrT  rU  statst_mtime_nsrd   rC   rM  rB   rA   from_global_configuser_peer_aliases	peer_nameai_peerr   pin_peer_nameruntime_peer_prefixr@   rH	  r  rF   rR  )
rQ  rT  rU  rg   mtime_nsmemo_keycachedhcfgaliasesr  s
             r.   $_extract_honcho_cache_busting_configz2GatewayRunner._extract_honcho_cache_busting_confignG  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.
        r   r  Nr   r   )registry_generationztools.registry_generationrr
  r  honcho)r@   rA   rK  rB   r   tools.registryrf  r}   rF   r   rC   rE   rf  rd  rR  )	rQ  r	  r  rQ  sectionr  section_valrf  r  s	            r.   _extract_cache_busting_configz+GatewayRunner._extract_cache_busting_configG  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rX  r  ephemeral_prompt
cache_keysr  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          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   Nry  r|   r  r  rO  rP  T)	sort_keysr  r	  )
r	  r  rC   rB   r	  r	  r	  rH	  r  rQ  )r  rX  r  rm  rn  r  r  r	  _j_api_key_api_key_fingerprint_cache_keys_sortedblobs                r.   _agent_config_signaturez%GatewayRunner._agent_config_signatureG  st   J 	#""""""" 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"==r0   c                 `   || j         v r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).
        Nr  z/Failed to read persisted session model overrideTr   r  r  r  )r  r  r  ry  rP  rR  zdCredential re-resolution failed for persisted override (provider=%s); using credential-less overridezIRehydrated persisted /model override for session=%s: model=%s provider=%sr|   )	r=  r}   get_model_overriderF   r   rr  rB   ra  ri  )r  r  r8  	persistedr  r  rX  s          r.   r  z/GatewayRunner._rehydrate_session_model_overrideG  s	    $777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       6>%k2Wg..B	
 	
 	
 	
 	
s"   8 &A"!A" BE 'E/.E/c                    | j                             |          }|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.
        r  )r  ry  r  rP  rR  Nry  rR  r  )r=  rB   rc  )r  r  r  r  r  r  r	  s          r.   r  z+GatewayRunner._apply_session_model_override6H  s     044[AA 	).((We,,U 	* 	*C,,s##C&)s#y))	""#455=Z(( > 1NZ((1 1N,- n$$r0   c                 f    | j                             |          }|du|t          |          nddS )z<Capture a gateway session override before a one-turn switch.N)had_overrider  )r=  rB   rA   )r  r  r  s      r.    _snapshot_session_model_overridez.GatewayRunner._snapshot_session_model_overrideSH  sA    044[AA$D0*2*>XD
 
 	
r0   r  c                     |sdS |                     d          r-t          |                     d          pi           | j        |<   n| j                            |d           |                     |           dS )z?Restore the session override captured before a one-turn switch.Nr|  r  )rB   rA   r=  r   r.	  rV  s      r.   rU  z-GatewayRunner._restore_session_model_override[H  s     	F<<'' 	A9=Z((.B: :D)+66 )--k4@@@  -----r0   agent_modelc                 p    | j                             |          }|duo|                    d          |k    S )zGReturn True if *agent_model* matches an active /model session override.Nr  )r=  rB   )r  r  r  r  s       r.   _is_intentional_model_switchz*GatewayRunner._is_intentional_model_switchgH  s9    044[AAt#LW(=(=(LLr0   r  c                   |sdS ||                      ||          sdS t          | di                               |d          }|B	 |                                 n,# t          $ r t
                              dd           Y nw xY w| j                            |d           | j                            |d           t          | d          r| j
                            |d           |                                  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.
        FNr  z%Failed to release active session slotTr   r  )rI  r}   r   releaserF   r   rr  r  r  r   r  r  )r  r  r  leases       r.   r0  z*GatewayRunner._release_running_agent_statelH  s'   :  	5%d.J.J/
 /
% 56;;??TRRU U U UDtTTTTTU  d333##K6664(( 	5!!+t444
 	##%%%ts   A &BBc                    |sdS t          | dd          }t          | dd          }||dS |                    ||fd          }|dS 	 |                    |          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).
        Fr  Nr  zFailed to release turn leaseTr   )r}   r   r  rF   r   rr  )r  r  r  r  rf  rx  s         r.   r
  z!GatewayRunner._release_turn_leaseH  s      	53T::466>X-5

K8$??=5	##E*** 	 	 	LL7$LGGG55	s   
A &B	B	new_session_idc                    |r|sdS t          | dd          }t          | dd          }||dS |                    ||f          }|dS 	 |                    ||          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.
        Fr  Nr  zFailed to rebind turn leaseTr   )r}   rB   rebindrF   r   rr  )r  r  r  r  r  rf  rx  s          r.   rB  z GatewayRunner._rebind_turn_leaseH  s      	. 	53T::466>X-5

K899=5	??5.999 	 	 	LL6LFFF55	s   A! !&B
Bc                    |sdS 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))rE  r}   r@   rA   r   &_clear_session_boundary_security_stater   rr  )r  r  rJ  r	  r8  s        r.   rI	  z'GatewayRunner._clear_conversation_scopeH  s    @  	F. 	- 	-DD$--E%&& -		+t,,,33K@@@4k6	
 	
 	
 	
 	
r0   c                    |sdS t          | dd          }t          |t                    r|                    |d           t          | dd          }t          |t                    r|                    |d           t          | dd          }t          |t                    r|                    |d           	 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.N_pending_skills_reload_notesr  r   r   r8
  z?Failed to clear slash-confirm state for session boundary %s: %sclear_sessionz:Failed to clear approval state for session boundary %s: %s)r}   r@   rA   r   r
  r9
  rF   re  r   rr  rU  r  )r  r  pending_skills_reload_notespending_approvalsupdate_prompt_pendingr  r  _clear_approval_sessions           r.   r  z4GatewayRunner._clear_session_boundary_security_stateI  s8    	F&-0$'
 '
# 1488 	?'++K>>>#D*>EE'.. 	5!!+t444 '.F M M+T22 	9!%%k4888	&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   :C CCC, ,
D6DD D' '
D54D59E 
E7E22E7c                     |sdS | j                             d          }|	i }|| _        t          |                    |d                    dz   }|||<   |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   r  NrZ   )r  rB   r  r0  )r  r  generationsnext_generations       r.   r
  z+GatewayRunner._begin_session_run_generation1I  sj      	1m''(ABBK+6D(kook1==>>B#2K r0   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   ri  )r  r  rJ  r  s       r.   r
  z0GatewayRunner._invalidate_session_run_generationCI  sG    77DD
 	KK?	   r0   r  c                     |sdS | j                             d          pi }t          |                    |d                    t          |          k    S )zEReturn True when ``generation`` is still current for ``session_key``.Tr  r   )r  rB   r0  )r  r  r  r  s       r.   rI  z%GatewayRunner._is_session_run_currentOI  sQ     	4m''(ABBHb;??;2233s:FFr0   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.Nr3  r4  )r}   rB   r7  r0  rF   )r  r   r  r  interrupt_events        r.   rG  z*GatewayRunner._bind_adapter_run_generationVI  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_staterG
  rH
  r  c                  K   |sdS | j                             |          }|r|t          ur|                    |           |                     ||           |                     |          }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%t'          |d          r|                    |           | j                            |d           |r,|                     |           |                     |           dS dS )	zFInterrupt the current run and clear queued session state consistently.Nr  interrupt_session_activityr~   c              3   F   K   | ]}|j         t          j        j        u V  d S r(   kindinspect	ParameterVAR_KEYWORDr,   params     r.   r/   z=GatewayRunner._interrupt_and_clear_session.<locals>.<genexpr>~I  sC       ? ? J'"3"??? ? ? ? ? ?r0   Fr   r  )r  rB   r  r  r
  r#  r}   r   r   rR  r  r  
parametersrb  r  r=  r2  r  r   r   r  r  r   r0  r.	  )r  r  r  rG
  rH
  r  r  r   r  r~   paramsaccepts_metadatas               r.   r
  z*GatewayRunner._interrupt_and_clear_sessionfI  s^       	F,00== 	6]2III##$4555//DW/XXX**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"";555  	2--k::: $$[11111	2 	2s   2AC; ;DD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  message_countr   r  r  rZ   )	r  r}   r  rB   rF   r@   r  r   r  )	r  r  r3  rX	  r	  	_sess_row_livera  _snapshot_sids	            r.   rU  z0GatewayRunner._refresh_agent_cache_message_countI  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                 n    |r|sdS t          | d          si | _        t          |          | j        |<   dS )zDStage per-turn must-deliver notes for the next agent run (one-shot).NrD  )r   rD  rq  )r  r  r  s      r.   rF  z-GatewayRunner._set_pending_turn_sidecar_notesI  sJ     	% 	Ft:;; 	2/1D,8<U(555r0   c                     |sg S t          | dd           }t          |t                    sg S |                    |d           }t          |t                    rt	          |          ng S )NrD  )r}   r@   rA   r   rq  )r  r  r  stageds       r.   #_consume_pending_turn_sidecar_notesz1GatewayRunner._consume_pending_turn_sidecar_notesI  sj     	I;TBB%&& 	I;--)&$77?tF|||R?r0   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t          | d          si | _        |r| j                            |          nd}|r
|| 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   r  z5[Voice channel now: not connected to a voice channel]z[Voice channel now: rO  )rN   rx  r  r  rB   rD  r   r  rF   r   rr  r  )r  rr  r  r  r   rB  vc_nowvc_prevs           r.   rE  z)GatewayRunner._voice_channel_sidecar_noteI  sM    ?h...4-##H$455%%e,, 	W 	:U)V)V 	4	66x@@FBFF 	 	 	LL<tLLLL44	 t/00 	'$&D!<GQ$'++K888T 	817D!+.!4gg"==4 	KJJ/f////s   (B   &B*)B*r  c                    t          | d          si | _        |                     ||          }|r| 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, ...).
        r  Nr   rZ   )r  )r   r  _ephemeral_change_keyrB   r  )r  r   r  r  _eph_key_eph_pinr   s          r.   r3  z,GatewayRunner._pinned_session_context_promptJ  s     t566 	-*,D'--gzBBCNX4.22;???TXHQK8$;$;A;+G
KKK 	H8@$7GD'4r0   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  rl  r;   r  )_slack_tools_loaded)display_hermes_homerw  c              3   $   K   | ]}|j         V  d S r(   r?  r  s     r.   r/   z6GatewayRunner._ephemeral_change_key.<locals>.<genexpr>jJ  s$      ??a!'??????r0   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{   rC   r}   )r,   r  hcs      r.   r/   z6GatewayRunner._ephemeral_change_key.<locals>.<genexpr>kJ  s{         Ar	 GFB//5266Ir228b99     r0   r9  )#r	  r  rN   r{   rx  r  r:  rm  rC   rB  r  r  r   rT  ry  r  rj  r  rF   r+  r(	  
chat_topicrQ  r  r}   r   shared_multi_user_sessionr  connected_platformshome_channelsr  r	  r   r	  r	  )r   r  r	  srcrN   discord_idsdiscord_toolsrm  slack_toolsr  r  home_display	key_tuples                r.   r  z#GatewayRunner._ephemeral_change_key)J  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           	         t          | dd          }t          |t                    r|                    |d           t          | dd          }t          |t                    r|                    |d           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 t          | di                                           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.
        r  Nr  r  r  r   c                 B    h | ]}||t           ut          |          S r(   r  r   r,   r  s     r.   r  z4GatewayRunner._evict_cached_agent.<locals>.<setcomp>J  8     
 
 
}*A!A!A qEE!A!A!Ar0   r  Tzagent-evict-r  r  rQ  daemonr   )r}   r@   rA   r   r  r  r  r  r   r  Thread_release_evicted_agent_softrC   r
	  rF   )	r  r  
_pin_store	_vc_storer  evictedr	  r@  running_idss	            r.   r.	  z!GatewayRunner._evict_cached_agentxJ  s   6 T#;TBB
j$'' 	.NN;---D"4d;;	i&& 	-MM+t,,,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
 
T#4b99@@BB
 
 

 e99##F	7X;C$4$4SbS$9;;	  
 eggggg 	 	 	00777777   	s=   B88B<?B<AF& &
G1G		
GGGGinterrupt_depthc                     |dk    r6t          j                     | _        d| _        t          | d          rd| _        d| _        dS )u  Reset per-turn state on a cached agent before a new turn starts.

        Both _last_activity_ts and _last_activity_desc are only reset for
        fresh external turns (depth 0); they are semantically paired —
        desc describes the activity *at* ts, so updating one without the
        other would make get_activity_summary() misleading.
        For interrupt-recursive turns both 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   zstarting new turn (cached)_last_flushed_db_idxN)rD  _last_activity_ts_last_activity_descr   r  _api_call_count)r@  r  s     r.   _init_cached_agent_for_turnz)GatewayRunner._init_cached_agent_for_turnJ  sP     a&*ikkE#(DE% u455 /-.* !r0   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_session_memory_managerr  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  rB   is_session_finalizablerG	  r  r@   rq  r   rr  rF   )r  r@  r  r  rc  r  r  s          r.    _commit_memory_before_soft_evictz.GatewayRunner._commit_memory_before_soft_evictJ  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  r  )r  r@  r  s      r.   _commit_then_release_softz'GatewayRunner._commit_then_release_softK  s4     	--eS999((/////r0   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  rF   r  )r  r@  s     r.   r  z)GatewayRunner._release_evicted_agent_softK  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 t          | di                                           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                 B    h | ]}||t           ut          |          S r(   r  r  s     r.   r  z9GatewayRunner._enforce_agent_cache_cap.<locals>.<setcomp>RK  r  r0   r  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_SIZErq  r  rB   r@   r  r   rb   r   r   r   ri  r  r  r  r
	  )r  r	  r  excess
evict_planordered_keysr  rc  r@  r  remaining_over_caps              r.   _enforce_agent_cache_capz&GatewayRunner._enforce_agent_cache_cap8K  s0    ~t44>F v}-- 	F

 
T#4b99@@BB
 
 
 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	  
 %'''#	 	r0   c                    t          | dd          }t          | dd          }||dS t          j                    }g }d t          | di                                           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                 B    h | ]}||t           ut          |          S r(   r  r  s     r.   r  z:GatewayRunner._sweep_idle_cached_agents.<locals>.<setcomp>K  r  r0   r  r  r  z3Agent cache idle-TTL evict: session=%s (idle=%.0fs)Tzagent-cache-idle-r  r  )r}   rD  r  rq  r  r@   r  r   _AGENT_CACHE_IDLE_TTL_SECSr  r  rB   rF   r  rG	  rb   r   r   ri  r  r  r  r
	  r   )r  r	  r  r@  to_evictr  r  rc  r@  last_activityr  r  r  s                r.   rK	  z'GatewayRunner._sweep_idle_cached_agentsK  s    ~t441488>U]1ikk "
 
T#4b99@@BB
 
 

  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F5 0D10F51E =F5?E  A(F55F9<F9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%  r  	proxy_urlN)r`   rz  rD   r  r?   rB   )r  r  rQ  s      r.   _get_proxy_urlzGatewayRunner._get_proxy_urlK  s     i+R006688 	#::c??""$$wwy!!'R,,[99yb!! 	#::c??"tr0   r  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 t          j        dd                                          }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}m}                      |          }|rd} |j        t4          j        k    rt9          |d          r||j        f	 dLd } t          |d!d          }!|!r|j        nd}"d"}#|j        t4          j        k    rd}"d}#|j        t4          j        k    r tA          t          |d#d$          pd$          nd$}$ ||j!        |j"        |"|#|$|j        pd%t          |d&d          pd'          }% |||j        |%|| ||(          }n2# tF          $ r%}&tH          %                    d)|&           Y d}&~&nd}&~&ww xY wd}'|r&tM          j'        |(                                          }'                     |          }|r4	 |)                    |j        |*           d{V  n# tF          $ r Y nw xY wd}(tU          j*                    })	  |
dd+,          }* |	|*-          4 d{V }+|++                    | d.||/          4 d{V 	 },|,j,        d0k    r|,-                                 d{V }-tH          .                    d1|,j,        ||-dd2                    d3|,j,         d4|-dd5          g dg dcddd          d{V  cddd          d{V  |r|/                                 |'rS	 tM          j0        |'d6-           d{V  S # tL          j1        tL          j2        f$ r |'3                                 Y S w xY wS d}.|,j4        5                                2 3 d{V }/ |            stH          6                    d7pd8pd           dg dg to          |          |d"d9c cddd          d{V  cddd          d{V  |r|/                                 |'rS	 tM          j0        |'d6-           d{V  S # tL          j1        tL          j2        f$ r |'3                                 Y S w xY wS |/8                    d:d;<          }0|.|0z  }.d=|.v r|.9                    d=d>          \  }1}.|1                                }1|1s4|1:                    d?          r|1d@d         }2|2                                dAk    rn	 tw          j<        |2          }3|3
                    dBg           }4|4rP|4d         
                    dCi           }5|5
                    dd          }|r|(|z  }(|r|=                    |           n# tv          j>        $ r Y nw xY wd=|.v to          |.          t~          k    rt          dD          !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# tL          j2        $ r  tF          $ r}6tH          A                    dE||6           |(szdF|6 g dg dcY d}6~6|r|/                                 |'rS	 tM          j0        |'d6-           d{V  S # tL          j1        tL          j2        f$ r |'3                                 Y S w xY wS Y d}6~6nd}6~6ww xY w|r|/                                 |'rS	 tM          j0        |'d6-           d{V  n# tL          j1        tL          j2        f$ r |'3                                 Y nuw xY wnp# |r|/                                 |'rS	 tM          j0        |'d6-           d{V  w # tL          j1        tL          j2        f$ r |'3                                 Y w w xY ww xY wtU          j*                    |)z
  }7 |            s7tH          6                    dGpd8pd           dg dg to          |          |d"d9S tH          6                    dH||pdddI         |7to          |(                     |(pdJd|ddK|(dgd>g to          |          ||duot          |(          d9S )MaT  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 aiohttpri  r  r^  r
  uH   ⚠️ Proxy URL not configured (GATEWAY_PROXY_URL or gateway.proxy_url)GATEWAY_PROXY_KEYr|   r%   c                  <     sdS                                 S r!  rI  r  r  r  s   r.   _run_still_currentz>GatewayRunner._run_agent_via_proxy.<locals>._run_still_current"L  )    %[%t//^LLLr0   r  r_  r[  r   >   ra  rb  ra  zContent-Typezapplication/jsonzBearer AuthorizationzX-Hermes-Session-Idzhermes-agentT)r  r  streamNrG   	streamingStreamingConfigr  rC  GatewayStreamConsumerStreamConsumerConfigpause_typing_for_chatc                 0    |                      |           d S r(   r
  rg  _chat_ids     r.   _pause_typing_before_finalizezIGatewayRunner._run_agent_via_proxy.<locals>._pause_typing_before_finalizehL  s     %::8DDDDDr0   SUPPORTS_MESSAGE_EDITINGFfresh_final_after_secondsr  editr+  edit_intervalbuffer_thresholdcursorbuffer_onlyr  	transportr+  )r   r   rG   r~   on_before_finalizeinitial_reply_to_idrun_still_currentz+Proxy: could not set up stream consumer: %sr   r?
  )r  	sock_readr  z/v1/chat/completions)r  headersr   zProxy error (%d) from %s: %sr  u   ⚠️ Proxy error (z): r\  r#   uK   Discarding stale proxy stream for %s — generation %d is no longer currentr7  )ri  r  r^  r
  r  r3  response_previewedr9  r4  )r  r   rZ   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 charsr3
  z(No response from remote agent)rb  r  )Baiohttpr  r  r  r  r`   rz  rD   r   rb   rB   r}   rz  r  r  rN   r?   r  r  r  r  rR  rN  r  r	  r#  rx  r  r   r   r  MATRIXr1  r  r  rF   r   rr  r  r  r  send_typingrD  postrD
  r   r   finishr  r  rm  rn  r   iter_anyri  r   r  r1   r   r  r  on_deltarG  #_GATEWAY_PROXY_SSE_BUFFER_MAX_CHARSr2  r  )8r  r   r  r  r  r3  r  r  r  _AioClientSessionr  r  	proxy_keyr   api_messagesr\  r[  r   r  r   _stream_consumer_scfgr  r  r	  r  _plat_streaming_streaming_enabledr  r  r	  rg  r  _adapter_supports_edit_effective_cursor_buffer_only_fresh_final_secs_consumer_cfg_sc_errstream_taskfull_response_start_timeoutr@  resprj  r  r  r   r  rH  objr   r  r  _elapseds8   `     ``                                                r.   _run_agent_via_proxyz"GatewayRunner._run_agent_via_proxyK  s     .	QQQQQQQQQ 	 	 	"i	    	 ''))	 	"l	   I1266<<>>		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________33F;; (481(*;;;Ri@j@j;%-%+^E "E E E E
 .5X?Y[_-`-`*8N(VTV%#(L(/99,.)'+ "?h.??? ge-H#NNURUVVV  &
 %9$8&+&9).)?0$02C"'/";V")&+r"B"B"Hb% % %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   $$<DK	 	
K8K33K8="M   
M-,M-] %"\4A)\1\4] .R/R=<R=\[="A\%\47] "U??/V10V15B\>A<Z;:\;[	
\[	1\?\4
\	\4\	\4"] 4
\>>] \>] a0 `'_<`a0 $_/_32_37a0 <`a0 `: :/a,+a,0c
b'&c'/cccc_interrupt_depthri  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 )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.
        rG   Nrp  F)r  r  r=  r  ri  r  r  r  )r}   _run_agent_innerr  rm  )r  r   r  r  r  r3  r  r  r=  r  ri  r  r  r  rc  s                  r.   rH  zGatewayRunner._run_agent!M  sc     2 wtXt446JERR 	..&*'!1DT-*%9'= /          <<VDD#L11 	 	..&*'!1DT-*%9'= /        	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	s   /(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.
        rG   Nrp  Fprofile_routesr   )match_profile_routerB  r  r  )rN   rB  r   r  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_routingrB  rN   r{   r   rF   r   r   rw  rr  )r  r  rG   routesrB  matcheds         r.   _profile_name_for_sourcez&GatewayRunner._profile_name_for_sourceOM  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)r#  Nr|   r  z\Profile %r does not exist for source %s/%s (guild_id=%s), falling back to global HERMES_HOMErB  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	  rH  rj  r#  rw  rD   rF  r   r   rN   r{   r   r}   rF   )	r  r  r  r	  rH  r#  explicit_profiler   profile_dirs	            r.   r  z.GatewayRunner._resolve_profile_home_for_sourceM  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           *      G   	
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#                                nd |d-dj$        h.          }j        j         k    o|d+k     |d/dj$        h.          }|d+k    pr#                                nddgdgdgdgdgdgj        j%        k    r j&                            j%                  } tE          | d0d          }!t          |!t                    rktO          | d1          r[|!(                                D ]F\  }"}#t7          |#          t7          j)                  k    r| *                    |"          r|"d<    nGtW          j,                     fd2t           d3                    r !                              nd}$|$$t[          |$          j.        t^          j.        u rdd}$g dgd4dd5t6          d"t6          d#t6          d$t          f fd6d}%j        j0        k    rX !                              }&|&A	 t          |&j1        j2                            d7d                    }%n# t(          $ r d}%Y nw xY wtg          j        j4        	|%8          }'|'rT|'j4        k    r 5                    	          n4 6                    j        j)        |'tE          d9d          	:          ndto          j        ;          j        j8        j$        fv rj4        r	r	ndfd<}( fd=})dgdgdgdgtW          j,                     j9        d>t&          d?tt          ddffd@d5t6          dAt          ddffdB !                              j)        j        j8        k    rj4        r	r|'	dCnX|'rT|'j4        k    r 5                    	          n4 6                    j        j)        |'tE          d9d          	:          ndd5t6          dDt6          ddffdE
	 f*dF}*d}+rtW          j;         |)                      }+d},rtW          j;         |(                      },d}-fdG}.tW          j;         |.                      }- fdH}/tW          j;         |/                      }0tW          j<                     fdI}1tW          j;         |1                      }2t{          dJdK          }3|3dk    r|3nd |dLddM          d+k    rdt}          j>                     fdN}4tW          j;         |4                      }5ddOdPt6          dQt
          dt
          fdR}6	 t{          dSdT          }7|7dk    r|7nd}8t{          dUdV          }9|9dk    r|9nd}:d};tW          j?         @                    |*                    d}<dW}=|8d}>	 tW          jA        h|=X           d{V \  }?}@|?rB                                }>nWC                                s@r= !                              }Ad         }B|Ar|BrtO          |AdY          r	|AD                              r|AjE                                      }C|Cr|CjF        nd}D|CrtE          |CdZd          pg }E G                    |C          r7 H                    |C|A|Dpd[d\j4        r	d]j4        ind^           d{V \  }D}@n|Ds|Ert          |C          }Dt          K                    d_|2L                                rd`nda           |BM                    |D                                            nd}>	 tW          jA        h|=X           d{V \  }?}@|?rB                                }>ned         }Fdb}G|FrLtO          |Fdc          r<	 |FN                                }H|H                    dddb          }Gn# t(          $ r Y nw xY w|;s|:|G|:k    rd}; !                              }I|Irt'          |:dez            pdf}Jt'          |8|:z
  dez            pdf}K	 |IO                    j)        dg|J dh|K dij           d{V  n2# t(          $ r%}Lt          P                    dk|L           Y d}L~Lnd}L~Lww xY w|G|8k    rd}<nWC                                s@r= !                              }Ad         }B|Ar|BrtO          |AdY          r	|AD                              r|AjE                                      }C|Cr|CjF        nd}D|CrtE          |CdZd          pg }E G                    |C          r7 H                    |C|A|Dpd[d\j4        r	d]j4        ind^           d{V \  }D}@n|Ds|Ert          |C          }Dt          K                    d_|2L                                rd`nda           |BM                    |D                                            |<rd         }Mi }N|Mr6tO          |Mdc          r&	 |MN                                }Nn# t(          $ r Y nw xY w|N                    dldm          }O|N                    ddd          }P|N                    dn          }Q|N                    dod          }R|N                    dpd          }St          Q                    dq|P|8|O|R|S|Qpdr           |Mr*tO          |Mds          r|MM                    t                     t'          |8dez            pdf}Tdt|T dug}U|Qr$|US                    dv|Q dw|Pdxdy|R dz|S d{	           n#|US                    d||O d}|Pdxd~|R dz|S d	           |US                    d           dT                    |U          d         rd                             dg           ng |Rd         pg ddd}>d         }Vd         }W|Wr|W                    d          nd}X|VtO          |Vd          r|Xst                      }Y	 ddlVmW}ZmX}[ tE          |Vdd[          pd[}\|\r|\|Zvr |[|Y|\          }Yn# t(          $ r Y nw xY w|VjY        |Yk    r0 Z                    |VjY                  s [                               d         }] !                              }^d}_d}`|]rN|^rKrHt          |^          }_ ]                    |^|_          }_|]                    d          r]|_s[|]                    d          rF|]                    d          }at          |a          rt          K                    dpd|a           n|a}`n|_r|_jF        pd[}btE          |_dZd          pg }c G                    |_          rF H                    |_|^|bdj4        r	d]j4        ind^           d{V \  }`}@|`st          |_          }`n|bpt          |_          }`|`r#t          P                    d|`dd                    |]r@|`s>|_s<|]                    d          }d|dr%|d}`t          P                    d|`dd                    |`r|`_                                `                    dz          r|`_                                a                    ddf          }e|er"|ed         dfd         b                                nd[}f|frB	 ddlcmd}g  |g|f          rt          K                    d|f           d}_d}`n# t(          $ r Y nw xY w je        r8|_s|`r4t          K                    dpd f                                           d}_d}`|_s|`rt          P                    d|`dd                    |^r:tO          |^d          r*r(|^jg        v r|^jg                 h                                  ji        k    rt          j                    d            !                              }^|^r|_rt          |^jE        |_           n(|^r&tO          |^d          r|^l                    |`           d         p|>d	 |+r|+m                                 |,r|,m                                 |2m                                 |5m                                 |-ro	d         du}h|hs3|-m                                 	 |- d{V  n# tV          jn        $ r Y nvw xY w	 tW          jo        |-dWX           d{V  nT# tV          jp        tV          jn        f$ r6 |-m                                 	 |- d{V  n# tV          jn        $ r Y nw xY wY nw xY w|0m                                 r q                                je        r r                    d           |+|,|2|0|5fD ]#}i|ir	 |i d{V  # tV          jn        $ r Y w xY w$S |]                    d          }j|jsډd         }k|kr|-r	 tW          jo        |-dWX           d{V  n# tV          jp        tV          jn        f$ r6 |-m                                 	 |- d{V  n# tV          jn        $ r Y nw xY wY n1t(          $ r%}lt          P                    d|l           Y d}l~lnd}l~lww xY wt          |>t                    r|>n|]pi }mt          |m                    d                    }n|m                    dd[          }o |6|k|o|nO          }p	 ddlsmt}q  |q|m|o          }rn# t(          $ r d}rY nw xY w|rrt          K                    dpd           n|orv|pst	 t          K                    dpd           |^O                    j)        |oj           d{V  nQ# t(          $ r%}lt          j                    d|l           Y d}l~ln'd}l~lww xY w|ort          K                    dpd           tE          t[          |^          dd          _|^u                              }st          |s          r8	  |s            }tt          jx        |t          r|t d{V  n# t(          $ r Y nyw xY wnt|^rrtO          |^d          rb|^jy        z                    d          }st          |s          r8	  |s            }tt          jx        |t          r|t d{V  n# t(          $ r Y nw xY w|]                    d          }u}v|`}wd}xd}y}z|_tE          |_dd          p}v {                    |_          r |                              st          K                    dpd           |]|+r|+m                                 |,r|,m                                 |2m                                 |5m                                 |-ro	d         du}h|hs3|-m                                 	 |- d{V  n# tV          jn        $ r Y nvw xY w	 tW          jo        |-dWX           d{V  nT# tV          jp        tV          jn        f$ r6 |-m                                 	 |- d{V  n# tV          jn        $ r Y nw xY wY nw xY w|0m                                 r q                                je        r r                    d           |+|,|2|0|5fD ]#}i|ir	 |i d{V  # tV          jn        $ r Y w xY w$S 	  }                    |v          }zn/# t(          $ r" t          P                    dpdd           Y nw xY w ~                    |_|v|u|z           d{V }w|w|]|+r|+m                                 |,r|,m                                 |2m                                 |5m                                 |-ro	d         du}h|hs3|-m                                 	 |- d{V  n# tV          jn        $ r Y nvw xY w	 tW          jo        |-dWX           d{V  nT# tV          jp        tV          jn        f$ r6 |-m                                 	 |- d{V  n# tV          jn        $ r Y nw xY wY nw xY w|0m                                 r q                                je        r r                    d           |+|,|2|0|5fD ]#}i|ir	 |i d{V  # tV          jn        $ r Y w xY w$S                      |_          }xtE          |_dd          }y !                              }{|{r4	 |{                    j)        j           d{V  n# t(          $ r Y nw xY w                                d{V                       |w|u|v|zdfz   |x|y
  
         d{V }|t          |]||          |+r|+m                                 |,r|,m                                 |2m                                 |5m                                 |-ro	d         du}h|hs3|-m                                 	 |- d{V  n# tV          jn        $ r Y nvw xY w	 tW          jo        |-dWX           d{V  nT# tV          jp        tV          jn        f$ r6 |-m                                 	 |- d{V  n# tV          jn        $ r Y nw xY wY nw xY w|0m                                 r q                                je        r r                    d           |+|,|2|0|5fD ]#}i|ir	 |i d{V  # tV          jn        $ r Y w xY w$S 	 |+r|+m                                 |,r|,m                                 |2m                                 |5m                                 |-ro	d         du}h|hs3|-m                                 	 |- d{V  n# tV          jn        $ r Y nvw xY w	 tW          jo        |-dWX           d{V  nT# tV          jp        tV          jn        f$ r6 |-m                                 	 |- d{V  n# tV          jn        $ r Y nw xY wY nw xY w|0m                                 r q                                je        r r                    d           |+|,|2|0|5fD ]#}i|ir	 |i d{V  # tV          jn        $ r Y w xY w$n# |+r|+m                                 |,r|,m                                 |2m                                 |5m                                 |-ro	d         du}h|hs3|-m                                 	 |- d{V  n# tV          jn        $ r Y nvw xY w	 tW          jo        |-dWX           d{V  nT# tV          jp        tV          jn        f$ r6 |-m                                 	 |- d{V  n# tV          jn        $ r Y nw xY wY nw xY w|0m                                 r q                                je        r r                    d           |+|,|2|0|5fD ]#}i|ir	 |i d{V  # tV          jn        $ r Y w xY w$w xY wd         }kt          |>t                    rn|>                    d          sX|>                    d          pd[}}|} p|}dk    }~t          |>                    d                    }nt          |kotE          |kdd                    }t          |>                    d                    } |6|k|}|nO          }|~s,|s*|s|r&t          K                    dpd||n|           d|>d<   n|~s|r|k|kj        }|r	 |kj                            j)        ||>d         d           d{V  d|>d<   t          K                    d|pd           n5# t(          $ r(}t          j                    dpd|           Y d}~nd}~ww xY wr|$rrt          |>t                    r|>                    d          stO          |$d          rtu                    j)        |$tW          j,                    dfd}	 |$                    |           n2# t(          $ r%}t          P                    d|           Y d}~nd}~ww xY w|>S )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   r  r  r  r3  r  r  r  Nr   r  r%   c                  <     sdS                                 S r!  r  r  s   r.   r   z:GatewayRunner._run_agent_inner.<locals>._run_still_currentM  r  r0   r  r@  r  r  r  )set_tool_preview_max_lentool_preview_length)set_friendly_tool_labelsfriendly_tool_labelsTtool_progressHERMES_TOOL_PROGRESS_MODEr  tool_progress_overridesrB  tool_progress_grouping
accumulate)choose_status_phraseresolve_status_phrase_catalogF)r  r  allow_genericr
  r  r  rX  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     r.   r  zPGatewayRunner._run_agent_inner.<locals>._display_surface_mode.<locals>.<setcomp>0N  s0     ! ! ! ,D11! ! !r0   rC  genericr>  )rP   rN   r  r@   rC   rD   rE   r   )r
  r  r  rX  r  r  r{   r  r  r  r	  s          r.   _display_surface_modez=GatewayRunner._run_agent_inner.<locals>._display_surface_mode&N  s     - 
!#:6?#K#K ! ! =! ! !
 %55:;V]^^ 6 !5++KwPWXXE%%% =%++--*=*=*?*?9*L*L$1<yyu< KK255U2r0   )r  r  rQ  r  r  r  rQ  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  rQ  rg  catalogz*generic status phrase selection failed: %s>   rD
  waiting	heartbeatlong_runningzstill on itzone sec)rF   r   rr  )r  r  r  rQ  _phrase_err_generic_status_catalog_generic_status_recentrV  s        r.   _generic_status_phrasez>GatewayRunner._run_agent_inner.<locals>._generic_status_phrase>N  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rh  >   logrC  live_statusfullsupports_status_textrC  rg  interim_assistant_messages)r  r  thinking_progressrR  voice_mixer_activec                 ~   d         sd         dS              sdS dd<   
j                             j                  }|t          |d          sdS 	 t	          |                    d                   	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 errorr  zvoice ack schedule failed: %s)	r  rB   r  r   r   ro  r   rF   rr  )r  r  rQ  rg  _ack_errrx  r   _voice_ack_fired_voice_ack_guild_voice_ack_loopr  s        r.   voice_ack_callbackz:GatewayRunner._run_agent_inner.<locals>.voice_ack_callbackN  s   " &6q&9&A%%'' "&Q}(()9::Hwx9L'M'MH(../?/BCC#! <	       H H H<hGGGGGGGGGHs   1B 
B<B77B<cleanup_progressr"   r   c                    ()dk    r|dk    r	 | dk    rB|r@ *            r6ddl m}  ||)dk    r|nd          }(                    6j        |           n!| dk    r(                    6j        d           n2# t          $ r%}t
                              d	|           Y d}~nd}~ww xY w0q| dk    rg|re|dk    r_t          j                    	                    d
          }|rd| dnd}	0
                    | d| d|	                                            3sdS 3r
 *            sdS | dk    r߉1d         s	 |                    d          pd}
|
'k    r2dk    r~ddlm}m}m}m} t%                      }t'          t)          |dd          d          }|rB |||          s6d1d<   3
                     |                        |t*          dz  |           n2# t          $ r%}t
                              d|           Y d}~nd}~ww xY wdS | dk    s|dk    r0+sdS |dk    r|n|}|rd| nd}|r3
                    |           dS 7sdS | dvrdS |dk    rdS 	 ,r,d         nd}|t-          |dd          rdS n# t          $ r Y nw xY w2dk    r|.d         k    rdS |.d<   ddl m}  ||d           }d}d}	 5                    6          }n# t          $ r d}Y nw xY wt-          |d!d          r|d"k    rt3          |t4                    rt3          |                    d#          t6                    r|d#                                         rdd$l m} |d#                                         }/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(}2d.k    r|d/d<   3
                    |           dS d/d<   |rdd$l m}  |            }tA          j!        |dt6          /          }"|dk    r#t?          |"          |k    r|"d|d+z
           d,z   }"| d%| d0tE          |#                                           d1|" }n|r| d%| d2| d}n| d%| d,}3
                    |           dS ||}d/d<   n|rdd3l m}m$}#m%}$m&}%  |            }|dk    r|nd)}t?          |          |k    r|d|d+z
           d,z   } |#|          }&|&r( |%|          r| d%|& }n | d%|&  |$|           | }n| d%| d2| d}d/d<   n| d%| d,}d/d<   |-d         k    r04dxx         d*z  cc<   3
                    d4|4d         f           dS |-d<   d4d<   3
                    |           dS )5z3Callback invoked by agent on tool lifecycle events.NrC  	_thinkingtool.startedr   )build_status_phraseri  ztool.completedzlive status update failed: %sz%Y-%m-%d %H:%M:%Sz "r  r|   z  r}  rq  rB  )TOOL_PROGRESS_FLAGrN  rO  tool_progress_hint_gatewayr  tool_progress_commandFr  Tr8  z(tool-progress onboarding hint failed: %su   💬 >   rx  clarifyis_interruptedrI
  )get_tool_emojiu   ⚙️supports_code_blocksr|  r   )get_tool_preview_max_lenrN  r   r  r  (   rZ   r  r   z ...r^
  )ensure_asciir  (z)
z: ")r  get_tool_verbtool_verb_connectorverb_drops_preview	__dedup__)'agent.displayry  set_status_textr   rF   r   rr  r   r@  strftimerH  r  rB   r\  rz  rN  rO  r{  r?   r(  r   r  r}   r  r#  r@   rA   rC   rD   r  r  r   r  rQ  rq  r  r  r  r  )8r   r  r  rQ  kwargsry  _phrase_ls_errrg  preview_strrq  rz  rN  rO  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  rd  _LONG_TOOL_THRESHOLD_S_live_status_adapter_live_status_moder   _thinking_enabledagent_holderlast_progress_msg	last_toollast_was_terminal_block	log_queuelong_tool_hint_firedprogress_modeprogress_queuerepeat_countr  r  tool_progress_enableds8                                          r.   progress_callbackz9GatewayRunner._run_agent_inner.<locals>.progress_callbackN  sd	    %0%..,,K!^33	3FXFXFZFZ3EEEEEE"5"5%$5$?$?DDT# # -<<V^WUUUU#'777 -<<V^TRRR  K K KLL!@'JJJJJJJJK
 $//I/){BZBZ!001DEEB5<"D/w////"KMMR"D"D9"D"D{"D"D"K"K"M"MNNN% F! ););)=)=  ---6J16M-X%zz*55:H#999mu>T>T             455"1#D)5LMM$)# # # # X7749K+L+L X6:03*../I/I/K/KLLL%Il]&BDVWWW  X X XLL!KYWWWWWWWWX [((I,D,D( F+4+C+C1>H-m---D ,"&&s+++ )  !222 I%%:F'P|AD$'3(*:E9 93 F    %%)y|*C*C$IaL 544444"N9h???E  $ $)$($<$<V$D$D!! ) ) )$(!!!) )+A5IIM++tT** ,txx	22C88 , O))++ ,
 CBBBBB O2244	
 2!4RBBU:R:RY:R:R:R  '4#J#J)#J#J#J ..00!Aggss2"--//*0?VAYYi
 [[1_
z??T))!+ITAXI!6!>JJ 5!+f!4J'4$L$L:$L$L$L! 	))#/15+A."&&'7888F-2'* 4FFFFFF2244C#z$UCPPPH Qww3x==3#6#6#+HS1WH#5#="QQYQQdiikk1B1BQQxQQCC 4"??Y??G???CC"33Y333C""3''' !,'-1'** 3            /.00!Aggss2w<<$&&%itaxi058G &i00 @)))44 Z!&0000!&YYY0C0CI0N0NYPWYY"??Y??G???C-2'**/////-2'*
 '***Q1$ ""Kl1o#FGGG#&a LOs#####sU   A)A; ;
B*B%%B*=B!G 
H)H		H"J 
JJK K*)K*r   r   r+  rx  rR   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RedactingFormatterlogsTrK  ztool_calls.logi  P r  r9  )maxBytesbackupCountr;  z%(message)szhermes.tool_calls.Fro  333333?zwrite_tool_log error: %srZ   )logging.handlersr  r   r  r  rO  setFormatterr  r  r   setLevelINFO	propagate
addHandlerri  rG  Emptyr  rp  rF   r   r  rm  removeHandlerflushr  )r  r  log_dirfile_handlertool_loggerr  r  r}  s         r.   write_tool_logz6GatewayRunner._run_agent_inner.<locals>.write_tool_logO  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'c            	        K   'sd S *                     +          sd S t                    j        t          j        u rP'                                s:	 '                                 n# t          $ r Y nw xY w'                                :d S g d &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          d||dk    rdnd	z
            d
!rh	 t          j        j                  j        }d|v p*t!          d |                                D                       n# t$          t&          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}	 	  #            sP'                                s:	 '                                 n# t          $ r Y nw xY w'                                :d S '                                }	 $r$d	         nd }|,t          |dd
          rt/          j        d	           d {V  n# t          $ r Y nw xY wt          |t2                    rBt          |          dk    r/|d	         dk    r#|\  }}}	r| d|	dz    dd<   rd         n|}
n[t          |t2                    r/t          |          dk    r|d	         dk    rd g d %d	<   d	)d	<   W|}
                    |
            |             d {V r[t7          j                    } t/          j        d            d {V   #            r"                    +j        !!           d {V  t7          j                    }||| z
  z
  }|d	k    rt/          j        |           d {V   #            sd S r85d"                              } |           d {V }|j         st          |d#d$          pd$!                                }t          |d%d
          r"tD          #                    d&j$                   d'|v sd(|v r4tD          %                    d)j$                   t7          j                    } nd
&                    +j        |
"!*           d {V } rIt          |d+d
          r8t          |dd           r'                    t)          |j'                             nr:d"                              }&                    +j        |"!*           d {V }n$&                    +j        |
"!*           d {V }|j         r7|j'        r0|j'         r'                    t)          |j'                             t7          j                    } t/          j        d            d {V   #            r"                    +j        !!           d {V  n'# (j(        $ r t/          j        d            d {V  Y n t.          j)        $ r '                                sC	 '                                }t          |t2                    rFt          |          dk    r3|d	         dk    r'|\  }}}	r| d|	dz    dd<    |             d {V  nt          |t2                    rst          |          dk    r`|d	         dk    rT |             d {V  r3r1r/           }	  |           d {V  n# t          $ r Y nw xY wd g d %d	<   d	)d	<   n%                    |            |             d {V  n# t          $ r Y nw xY w'                                Crrr |             d {V  r3r1r/           }	  |           d {V  n# t          $ r Y nw xY wY d S t          $ r?}tD          *                    d,|           t/          j        d           d {V  Y d }~nd }~ww xY w~).Nseparater  g      ?MAX_MESSAGE_LENGTHr  rZ   r    @   r   Fr~   c              3   F   K   | ]}|j         t          j        j        u V  d S r(   r  r  s     r.   r/   zQGatewayRunner._run_agent_inner.<locals>.send_progress_messages.<locals>.<genexpr>YP  sC         % "J'*;*GG     r0   rT  r   c                 ~   K   j         | |d}t          dd          rd|d<   r|d<    j        di | d {V S )N)r   rT  r   REQUIRES_EDIT_FINALIZEFTfinalizer~   r  )r   r}   edit_message)rT  r   r  _edit_accepts_metadata_progress_metadatar   r  s      r.   _edit_progress_messagez^GatewayRunner._run_agent_inner.<locals>.send_progress_messages.<locals>._edit_progress_messageaP  s|      %~",& 
 7$<eDD .)-F:&) <);F:&1W1;;F;;;;;;;;;r0   r  r%   c                 @    d                     d | D                       S )Nr   c              3   4   K   | ]}t          |          V  d S r(   r  )r,   r  s     r.   r/   ziGatewayRunner._run_agent_inner.<locals>.send_progress_messages.<locals>._progress_text.<locals>.<genexpr>nP  s(       = =tT = = = = = =r0   )r2   )r  s    r.   _progress_textzVGatewayRunner._run_agent_inner.<locals>.send_progress_messages.<locals>._progress_textmP  s#    yy = =u = = ====r0   c                     g }g }| D ]=}||gz   }|r1  |                    k    r|                     |           |g};|}>|r|                     |           |S )z>Partition progress lines into platform-sized editable bubbles.)rb   )r  groupsrF  r  r  _PROGRESS_TEXT_LIMIT_progress_len_fnr  s        r.   _split_progress_groupsz^GatewayRunner._run_agent_inner.<locals>.send_progress_messages.<locals>._split_progress_groupspP  s    %' "! , ,D '4& 0I ,#3#3NN94M4M#N#NQe#e#eg...#'&"+ +MM'***r0   c                     rKt          | dd          r<t          | dd           r-                    t          | j                             d S d S d S d S )Nr  FrT  )r}   rb   rC   rT  )r.  _cleanup_msg_ids_cleanup_progresss    r.   _track_progress_resultz^GatewayRunner._run_agent_inner.<locals>.send_progress_messages.<locals>._track_progress_resultP  s    %D	599D  d;;D
 %++C0A,B,BCCCCCD D D D D Dr0   r   c                 j   K                        j        |            d {V } |           |S )Nr,  )r   r   )r   r.  r  _progress_reply_tor  r   r  s     r.   _send_progress_textz[GatewayRunner._run_agent_inner.<locals>.send_progress_messages.<locals>._send_progress_textP  sc      &||"N //	  ,           '&v...r0   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.
                FrZ   r   N	retryableu>   [%s] Transient overflow edit failure — keeping can_edit=TrueTr   )r   r  r}   r   rr  r   rT  )r  
first_textr.  r   r  r  r  r  r   can_editprogress_linesprogress_msg_ids       r.   !_roll_progress_overflow_if_neededziGatewayRunner._run_agent_inner.<locals>.send_progress_messages.<locals>._roll_progress_overflow_if_neededP  s      & !X ! 5//??v;;!## 5+^F1I66
".#9#9/:#V#VVVVVVVF!> 	%"6;>> ("LL ` '   $(4#($u	% $7#6z#B#BBBBBBBF~ <&*; <*0*;#ABBZ < <E#6#6~~e7L7L#M#MMMMMMMF~ <&*; <*0*;
 "(tr0   Tr~  r  r  u    (×ry  r   	__reset__r  r   r   r  r|   r  u5   [%s] Transient edit failure — keeping can_edit=Truefloodzretry afterz-[%s] Progress edit flood control, backing offr,  r  zProgress message error: %sr  )+r#  r   r  r  rF  rG  rF   r@   message_len_fnr   r0  r}   r  r  r  r  rb  r  r=  r2  rC   rq  r   r  rp  r  rb   rD  rz  r"  r   r2   r  rE   r   rr  r   ri  r   rT  r  rm  r  ),_last_edit_ts_PROGRESS_EDIT_INTERVAL_raw_progress_limit_edit_paramsr  r>  r  r  base_msgr   r\  _now
_remaining	full_textr.  r  _flood_result_pending_textr  r  r  r  r  r  r  r  r  r   r  r  r  r  r  r  r  r   r  r  progress_groupingr  r}  r  r  r  s,                      @@@@@@@@@@@@r.   send_progress_messagesz>GatewayRunner._run_agent_inner.<locals>.send_progress_messages(P  s     ! ..v66G 
 G}})-@-MMM(..00 &113333$    )..00 
 N"O(J6HM&)# g':;;&& 
+&)'';OQU*V*V*^Z^&_&_## + + +&*###+ $'#-@3-F-FrrAN$ $  &+"! 3
3#*#4W5I#J#J#UL"l2   )5)<)<)>)>     +* ":. 3 3 3-2***3
< 
<s 
< 
< 
< 
< 
< 
< 
< 
< 
<>d >s > > > >d tDz        D D D D D D D          *T * * * * * * * * * * * * *X|+{+--// "0"6"6"8"8 && . 9 9 ; ; ; ;#, & & & %& #1"6"6"8"8 &
 (3355C	BN/X|ATX,/;02BEA A; #*-"2"22222222$$    "#u-- 3#c((a--CFkDYDY-0*8U) O4<1N1N%!)1N1N1NN2.4BPnR00#C// 3CHHMMc!fP[F[F[ +/)+/3)!,*+Q !&--c222>>@@@@@@@@ !(,(8(8%mC000000000--// c")"5"5fnOa"5"b"bbbbbbbb   >++D!8D=<P!QJ!A~~ &mJ777777777 --//  <PO$?$(IIn$=$=	'='=oy'Y'Y!Y!Y!Y!Y!Y!Y%~ "W$+FGR$@$@$FB#M#M#O#OD  'v{EBB ) &$[$+L!" !" !" !)&$-42G2G !'$S$+L!" !" !" 150@0@+029,,(.(+););	 3? 3 3 - - - - - -M !2W$+M9e$L$LW %,M<$N$NW
 !1 7 7M<T8U8U V V V# (,		.(A(AI+2<<(.(1););	 ,8 , , & & & & & &FF ,3<<(.(+););	 ,8 , , & & & & & &F "> Pf.? P.4.?O0 P 0 7 7F<M8N8N O O O$(N$4$4M "-,,,,,,,,,))++ _%11&.K]1^^^^^^^^^{ - - -!-,,,,,,,,,,,- ' ' ',2244 """0";";"="=C)#u55 J#c((a--CPQFVaLaLa58 28U#1 !N<D9V9V%RS)9V9V9VN2$6*K*K*M*M$M$M$M$M$M$M$M!+C!7!7 JCHHMMcRSfXcNcNc 'H&G&I&I I I I I I I I#+ !- !-? !-4BN>4R4RM%-.D.D_Vc.d.d(d(d(d(d(d(d(d(d+4 %- %- %-(,%-26137; 1! 423Q . 5 5c : : :&G&G&I&I I I I I I I I( " " "!E"5 -2244 ":   BN B B??AAAAAAAAA !N ! !$2N>$B$B	!"8"8)"T"TTTTTTTTT( ! ! ! D!FF  + + +LL!=qAAA!-**************+u|+s8  "A7 7
BB C0 0C?>C?"AE0 0FFY  H5 4Y 5
I?Y IY Y 09J+ *Y +
J85Y 7J88BY B Y ;Y 
Y !BY .F%Y $a9<$a9!C^>&]98^>9
^^>^7^>=a9>
_a9
_?a9`a9
`+(a9*`++a91	a9:5a44a9r~  
prev_toolsc                                 sd S g }|pg D ]d}t          |t                    r+|                    |                    d          pd           B|                    t	          |                     et                              dj        rj        j        ndj	        | ||d          t          d           d S )Nr   r|   z
agent:step)rN   r  r3  r~  
tool_namesr
  z agent:step hook scheduling errorr  )r@   rA   rb   rB   rC   r   r  rN   r{   r  r   )	r~  r  _names_t
_hooks_ref_loop_for_stepr   r3  r  s	       r.   _step_callback_syncz;GatewayRunner._run_agent_inner.<locals>._step_callback_syncQ  s    %%''  !#F!'R + +b$'' +MM"&&.."6B7777MM#b''****$9? P 5 5b%~",!*"('/ /   >     r0   r   c                     	 t          j                            | |                     d S # t          $ r&}t                              d|           Y d }~d S d }~ww xY w)Nzevent_callback hook error: %s)r  run_coroutine_threadsafer  rF   r   rr  )r   r   r  r  r  s      r.   _event_callback_syncz<GatewayRunner._run_agent_inner.<locals>._event_callback_syncQ  s    B0OOJ88"      B B B<bAAAAAAAAABs   ). 
AAA)r  r  r   c           
         	r
             sd S t          j        | |          }|Vt                              dj        rj        j        nd| t          t          |pd                    d d                    d S t          t          	
| |          t          d|  d          }|d S rd
fd	}|	                    |           d S d S )Nz(status_callback suppressed for %s/%s: %sr4  r|      zstatus_callback (z) scheduling errorr  r%   c                     	 |                                  }n# t          $ r Y d S w xY wt          |dd           }t          |dd          r&|r&                    t	          |                     d S d S d S )NrT  r  F)r.  rF   r}   rb   rC   )r  resmidr  s      r.   _track_status_idzWGatewayRunner._run_agent_inner.<locals>._status_callback_sync.<locals>._track_status_idQ  s    !jjll$   !#|T::CsIu55 :# :(//C99999: : : :s    
&&r  )
r   rN   r   rr  r{   r   rC   r   r   ro  )r   r   prepared_message_futr  r  r  r  r   _status_adapter_status_chat_id_status_thread_metadatar  s        r.   _status_callback_syncz=GatewayRunner._run_agent_inner.<locals>._status_callback_syncQ  s;   " *<*<*>*> >   
  '>-3_KFO)))7GMr8J8JKKDSDQ	   ++O_jZj  mD  E  EN
NNN	  D |  	9: : : : : : &&'788888	9 	9r0   c                  0  *qrstuvwxyz j         |j        k    rdnj         j        } pd}pd                                }|r|dz   |z                                   }                    j         j        pdt          dd           t          dd                     }|r|dz   |z                                   }t                      }	                               \  }}t          
                    d||                    d	          pd           n!# t          $ r}d
| g dg dcY d }~S d }~ww xY wj        }                    |          }	|	_                                      _        d vd }
t          t          dd           dd           }|ddlm}  |            } | d          }||j        o
|j        dk    nt-          |          }|}}|}|s|r^	 ddlm}m}                               }|r
d }j         |j        k    rt9          |d          r|j        f	 dd}t          |dd          }|st;          d          |j        }d}j         |j        k    rd}d}j         |j        k    r tA          t          |dd          pd          nd} ||j!        |j"        ||||j        pdt          dd          pd          } ||j        |fd nd |!          v|rd"tF          dd fvfd#}
vd<   n2# t          $ r%}t          
                    d$|           Y d }~nd }~ww xY wdd%d"tF          d&t,          dd fvfd'}$                    ||          }%                    |d(         |d)         |&                              t          d*d           t          d+d           ,          }d yd}t          d-d           } t          d.d           }!d }"| rN|!L| 5  |!                              }#d d d            n# 1 swxY w Y   |#rtO          |#          d/k    r|#d/         }"d}$|"64|"k    r.	 j(        )                    |"          }$n# t          $ r d}$Y nw xY wd }%j*        KrI	 j*        j+        ,                              }&|&r|&                    d0d          }%n# t          $ r Y nw xY wd }'| r|!| 5  |!                              }(|(r|(d1         |k    rtO          |(          d2k    r|(d2         nd })tO          |(          d/k    r|(d/         nd }*|*d uo	d uo|*k    }+|+o|$o|*|"k    },|,rft          -                    d3|*           j.        /                    d           }-ta          |-tb                    r
|-r|-d         nd }.|.r|.td          ur|.}'n|+sq|)o|%m|%|)k    rgt          -                    d4|)|%           j.        /                    d           }-ta          |-tb                    r
|-r|-d         nd }.|.r|.td          ur|.}'ny|(d         yt9          |!d5          r'	 |!3                               n# th          $ r Y nw xY w5                    y           |y_6        t          
                    d6           d}d d d            n# 1 swxY w Y   |r*y(7                    y8                                           |'	 ts          j:        j;        |'fdd7tG                    d d8          9          <                                 n7# t          $ r* 	 ;                    |'           n# t          $ r Y nw xY wY nw xY wy {dd(|d(         i|d)         t{                    i d:|d;dd<dd=d>d?|pd d@j>        pd dA|	dBj        dC|                    dC          dD|                    dE          dF|                    dG          dH|                    dI          dJ|                    dK          dL|                    dMd          dN|                    dO          dPdQ| d*j?        d+j@        dRjA        dSj        dTjB        djC        djD        dUdVt          j*        dWj*                  dX8                                y| r9|!7| 5  y||%f|!<   E                                 d d d            n# 1 swxY w Y   t          
                    dY|           ssnd y_F        d         nd y_G        ~jH        rnd y_I        |
y_J        |r|nd y_K        y_L        dfdZ}/|/y_M        d y_N        }y_O        |	y_P        j        y_Q        |                    dC          pi y_R        dS                    T                                        y_U        ts          jV                    tg rts          jW                    sd[tF          dd ffd\udrstufd]}0d[tF          dd frstufd^}1|1y_X        rQrOt          t                    d_d           Z                    |0`           nt          dad           }2|2|0|2<                       dbi                               dc          }3ta          |3t,                    r|3rddnd}3|3r!tG          |3          [                                nddy_\        detF          dtF          ffdf}4|4y_]        y_^        yd<   t9          ydg          ryj_        nd d<   t          t          t                                h          \  }5}6|rt          ydPd           k    r|t          |5t          ydid                     }7|7|5urYt          d                    djtO          |5          tO          |7                     t          |7t          jf                    k          }5t          |5          }8ddllhmi}9mj}:mk};ml}< dmt          dd fqfdn}=}>}?t          doi           }@r|@/                    d           nd }A|Ar|Adz   z   t                      }Bt          t                    |Bp          }Cd }Dr3	 j(        jq                                      }Dn# t          $ r d }DY nw xY wd}E|D1t          |Ddqd          r t          t          |Ddrd           |Bp          }Et-          |Dd uot          |Ddqd          o|Cp|E          }Ft-          |5o |5ds                             dt          duk    o|C          }G|Fr[t          |Ddvd           pdw}H}>                              }It-          t          |Idxd                    }Jt          |H|Jy          n	|Gr}>dzz   t          d{d           }@|@r&r$|@v r |@/                    d           }K|Kr|Kdz   z   ta          tF                    r}                                si|Dgt          |Ddqd          rVt          |Ddvd           pdw}L                              }Mt          |Ldt-          t          |Mdxd                    y          pdq |;q          }N |9q|=           	 s                              }O|Or	 dd|ltmu}P  |P|O          \  }Q}R|Rr)t          d                    d}tO          |R          |R           t          d~ |QD                       r|Q}Sn}Sn6# t          $ r'}Tt          d                    d|T           }SY d }T~Tn
d }T~Tww xY w}St          |S|6          }U|5d}V|>|>|Vd<   n|6r|Vd<   |Vd<   |?|?|Vd<    yjx        |Ufi |V}W |<q           	 ddlymz}X  |Xq           n# t          $ r Y nw xY w |:|N           n>#  |<q           	 ddlymz}X  |Xq           n# t          $ r Y nw xY w |:|N           w xY w|Wd<   vv{                                 |W                    d          }Yd}Zd}[d}\d}]d         }^|^r`t9          |^d          rPt          |^j|        dd          }Zt          |^dd          }[t          |^dd          }\t          |^j|        dd          pd}]|^rt          |^d(d           nd }_d         yd}`yrt-          t          ydd                    nd}ayrt          ydP          n}byrr|bk    rd}`t          -                    d|b           j(        jq                                      }cd}d|crt          |cdPd           }e             st          -                    dpd           nm|e|bk    rd}dnd|ek    r t          -                    dpd|e           n>|b|c_}        j(        ~                                 j(                            |b           d}d|drt          dQd           |j        k    rt          dd           dk    rt          dd           j*        	 j*        j+                            |b          }f|frQ|f                    d          r<tG          |fd                   _D        t          
                    djD        |b           n,# t          $ r t          
                    dd           Y nw xY w|dr                    |cd           |bz                    zy           |`s|ardntO          |5          }g|Ysdt          |W|YpdtO          |5                    }Yt	          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                    dd          d|W                    d          d|W                    dd          d|W                    d          d|W                    d          d|W                    dd          d|W                    dd          dgd         pg d|gd|adPzd|Zd|[|\|_|]dS d|Yvrt          |W                    dg           tO          |5          |8          \  }h}i|hrwt                      }jg }k|hD ]0}l|l|jvr*|j                    |l           |k                    |l           1|ir|k                    dd           |Ydz   dS                    |k          z   }Y|YrNj*        rF	 ddlm}m d         rd                             dg           ng }ndtF          dt          dd fd}oyrt          yd(d           nd wyrt          yd	d           nd x|oyrSt          yd(d           t          yd	d           t          ydd           t          ydd           t          ydd           dnd yrwxyfdnd d}p                              rzfd|pd<   n                              r
zfd|pd<    |mt          j*        dWj*                  z|Y|nfi |p n# t          $ r Y nw xY wi d|Yd|W                    d          dd         rd                             dg           ng dd         rd                             dd          nddd         rd                             d          nd dd         rd                             dd          nddd         rd                             dd          nddd         rd                             d          nd dd         rd                             d          nd dd         rd                             dd          nddgd         pg d|gd|ad|Zd|[d|\d(|_|]z|W                    dd          |W                    dd          d         rd                             dd          nddS )Nr  r|   r   r  r  r  r  z3run_agent resolved: model=%s provider=%s session=%sr  u'   ⚠️ Provider authentication failed: r   r  r  r[  rG   r  r  rC  r  r
  r%   c                 0    |                      |           d S r(   r  r  s     r.   r  zWGatewayRunner._run_agent_inner.<locals>.run_sync.<locals>._pause_typing_before_finalizeNR  s     !) > >x H H H H Hr0   r  Tz(skip streaming for non-editable platformFr  r  r  r+  r  c                  .                          d          S )N)r  )rH  )r  s   r.   r   zBGatewayRunner._run_agent_inner.<locals>.run_sync.<locals>.<lambda>{R  s    ););N)K)K r0   )r   r   rG   r~   on_new_messager  r  r  r   c                 J                 r                     |            d S d S r(   )r&  )r   r   r+  s    r.   _stream_delta_cbzJGatewayRunner._run_agent_inner.<locals>.run_sync.<locals>._stream_delta_cbR  s;    #5#5#7#7 !D$4$=$=d$C$C$C$C$C!D !Dr0   z$Could not set up stream consumer: %s)already_streamedr  c                2                sd S | }.|r                                  n                    |           d S |s%r#t          |pd                                          sd S t	                              |          t          d           d S )Nr|   r   z+interim_assistant_callback scheduling errorr  )on_segment_breakon_commentaryrC   rD   r   r   r   )	r   r  display_textr  r   r  r	  r
  r+  s	      r.   _interim_assistant_cbzOGatewayRunner._run_agent_inner.<locals>.run_sync.<locals>._interim_assistant_cbR  s    ))++ F##/' E(99;;;;(66|DDDF# ? #lFXVXBYBYB_B_BaBa F(#(('$!8 )  
 #! M	 	 	 	 	 	r0   r  rX  r  r  )rn  r  r  r  r  r  r  rZ   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 writer  z#Reusing cached agent for session %szagent-xproc-evict-r  r  rH  r  r  r  r  ephemeral_system_promptprefill_messagesr  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r3  rN   rQ  r   r(	  gateway_session_keyr  r  r  z)Created new agent for session %s (sig=%s)c                     r
             sd S 	 t          |           }n-# t          $ r  t                              dd           Y d S w xY w|sd S t	                              |          t          d           d S )Nzrender_notice_line failedTr   z)notice_callback delivery scheduling errorr  )r   rF   r   rr  r   r
  )r   r  r  r   r  r  r  s     r.   _notice_callback_synczOGatewayRunner._run_agent_inner.<locals>.run_sync.<locals>._notice_callback_syncS  s    & .@.@.B.B F-f55DD    LL!<tLLLLFF  F(11&$??"! K	     s   ! &A
Ar   c           
          r
             sd S t                              | t          j                            t          d           d S )NrR   r   z+background_review_callback scheduling errorr  )r   r   r   rN   r   )r   r  r   r  r	  r
  r  s    r.   _deliver_bg_review_messagezTGatewayRunner._run_agent_inner.<locals>.run_sync.<locals>._deliver_bg_review_messageS  s    & .@.@.B.B F(#(('!=>U`f`o!p!p!p )  
 #! M	 	 	 	 	 	r0   c                                                        5  t                    }                                  d d d            n# 1 swxY w Y   | D ]} |           d S r(   )rc   rq  re  )r"	  queued_bg_review_pending_bg_review_pending_lock_bg_review_releaser  s     r.   _release_bg_review_messageszUGatewayRunner._run_agent_inner.<locals>.run_sync.<locals>._release_bg_review_messagesT  s    "&&(((, / /"#566G&,,.../ / / / / / / / / / / / / / / & 7 7F..v66667 7s   $AAAc                    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  rb   )r   r!  r"  r#  r  r   r  s    r.   _bg_review_sendzIGatewayRunner._run_agent_inner.<locals>.run_sync.<locals>._bg_review_sendT  s   & .@.@.B.B F)0022 #0 # #188:: #.55g>>>"# # # # # # # ### # # # # # # # # # # # # # # +*733333s   +A++A/2A/r2  r  r  r  memory_notificationsr<   questionc           
      $   ddl m} dd l}sdS |                                j        d d         }|                    |pd| |rt          |          nd            	                                n# t          $ r Y nw xY w	 rd         nd }t          |dd           }t          |          r |d           n,# t          $ r t                              d	d
           Y nw xY wd}t                              | |rt          |          nd |pd          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|                    pd           dS |                                }|                    |t+          |                    }||dk    rdt-          |dz             dS |S )Nr   r5
  r|   rc	  )r
  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 scheduler  r  r  zClarify send failed: %sz'[clarify prompt could not be delivered]z[user did not respond within r  zm])r
  r6
  r  r  r  rq  rq  r
  rF   r}   r   r   rr  r   send_clarifyr.  r   r   r  get_clarify_timeoutwait_for_responser1  r0  )r(  r   r
  r  r
  _scr  send_okr  r.  r   r  rR  r  r  r	  r
  r  stream_consumer_holders                r.   _clarify_callback_synczPGatewayRunner._run_agent_inner.<locals>.run_sync.<locals>._clarify_callback_sync7T  s   AAAAAA$$$$& 2"[[]].ss3
%%) + 1r%-4>DMMM$	 &   #99/JJJJ    D	7MW033SWC$S*>EEF'' ,s++++    LLL!% !       .#00 /!)18 BWd#-$/$52!8 1   #! A   ;#GG(!$B!7!7"&wvy%'H'H"I"I$ ( ( ('@#FFF"'(  E !..{/@bAAADD&::<<'99*eT[nn9]]#x2~~P3w|;L;LPPPPs<   A4 4
B B8B> >&C'&C'64E+ +
F5FFr
  r  r  zPersisted 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                                                    |                     dd          }|                     dd          }t          |          }t          t	                    dd          	 t                              |	||                     dd          |                     d	d          |                     d
d                    
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          dd          }t          ||||                     dd          |                     d	d          |                     d
d                    }	 t                              |          
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 errorr  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: %sr  r%  r   r   z#Approval text-send scheduling errorz#Failed to send approval request: %s)r
  rB   r   r}   r   r   r8  r   rW  r.  r  r   r  rF   r   r   )r6  r   desc_approval_fut_approval_resultr  rm  r\  _approval_send_fut_approval_session_keyr  r  r	  r
  s            r.   _approval_notify_synczOGatewayRunner._run_agent_inner.<locals>.run_sync.<locals>._approval_notify_syncT  s     55oFFF#''	266$((8KLL /s33
 4002FMMY(@+>>(7(+,A,0)@0=0A0ABSUY0Z0Z.;.?.?QU.V.V-:->->~u-U-U ? 	 	 +#)(M) ) ) )0"./U"V"VV+8+?+?+?+K+K(+3 #"Fj,2    %   TVX        _.DcJJ4$1$5$56G$N$N"/"3"3OT"J"J!.!2!2>5!I!I  L)A',,+%< -  
 '%$I	* 	* 	*& *5*11"1===== 65  L L LLL!FKKKKKKKKKLs8   1BD1  D1 1
E ;EE AH 
I H;;I rA  )rA  rS  rW  r   r[  r  rT  rL  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.]

r  )build_native_content_partsz:Native image attachment: skipped %d unreadable path(s): %sc              3   H   K   | ]}|                     d           dk    V  dS )r   r  Nr  r  s     r.   r/   zCGatewayRunner._run_agent_inner.<locals>.run_sync.<locals>.<genexpr>U  s1      LLquuV}};LLLLLLr0   z8Native image attachment failed, falling back to text: %s)conversation_historyr
  r  r  r  r  ri  r  r"  session_prompt_tokenssession_completion_tokensrr  r  u/   Session split detected: %s → %s (compression)uS   Skipping session split sync for stale run %s — generation %s is no longer currentr7  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-compressionr  rO  r  u   ⚠️ r  r^  rT  r`  rl  r_  interrupt_messager&  r)  r  compacted_in_placeinput_tokens)output_tokensr  rr  r  )r  r  r  r   )maybe_auto_titler   r   c                 >    t                               d| |           d S )Nz@Gateway auto-title failure suppressed (not user-visible): %s: %s)r   rr  )r   r   s     r.   _title_failure_cbzKGatewayRunner._run_agent_inner.<locals>.run_sync.<locals>._title_failure_cbV  s*    ^ #    r0   r  ry  rP  )r  r  r  ry  rP  c                  X    t          dd            k    ot          dd           k    S )Nr  r  rN  )_title_model_title_providerr@  s   r.   r   zBGatewayRunner._run_agent_inner.<locals>.run_sync.<locals>.<lambda>V  s6    #E7D99\I T 'z4 @ @O S r0   )failure_callbackmain_runtimeruntime_validatorc                 2                         |           S r(   )r-  r%	  effective_session_idr  r  s    r.   r   zBGatewayRunner._run_agent_inner.<locals>.run_sync.<locals>.<lambda>V  s#    RVR|R|"0!S S r0   title_callbackc                 2                         |           S r(   )r  rS  s    r.   r   zBGatewayRunner._run_agent_inner.<locals>.run_sync.<locals>.<lambda>V  s#    RVRR"0!S S r0   r  rH  r  response_transformedr+  )rr  r3  r  rW  r+  r  r  )rN   r  r{   rD   r  r   r}   rW  r  r   rr  rB   rF   r  r  r  r  r  rz  r  r  r  r   rN  r  r	  r#  r  r   rW  r  r!  r1  r  r  rC   r  rv  rl  r   r  _is_session_ended_in_dbr  r  r  ri  r  r   r@   r  r  r  r*	  r  rH  r  r  r  r  r  r
	  r  r  r  r  rQ  r(	  r+  r  r  tool_progress_callbacktool_start_callbackr  step_callbackstream_delta_callbackinterim_assistant_callbackstatus_callbacknotice_callbacknotice_clear_callbackevent_callbackr  r  r  r2   r  _gateway_turn_context_notesr  r  background_review_callbackr   r2  rE   r'  clarify_callbackrl  r
  r  r  r?   r  r   r  rD  r  rU  r2  r3  r4  r5  rA   r;  rG  r  r  rS  r~  r  r@  rb  r  r  tools.clarify_gatewayr  r$  r  r3  r  rL  %get_telegram_topic_binding_by_sessionr  r  rg  r   r  rc   re   rb   rh   agent.title_generatorrI  BaseExceptionr  r  )r  combined_ephemeralevent_channel_promptcfg_channel_promptrH  r  r  r   r  r  r  r,  r  r-  r.  _want_stream_deltas_want_interim_messages_want_interim_consumerr  r	  rg  r  r/  r0  r1  r2  r3  r4  r  r  _sigreused_cached_agentrX	  r	  _peek_cached_sid_peek_entry_cached_sid_is_dead_current_msg_countr  _xproc_evicted_agentra  
_cached_mc_cached_sid_session_id_mismatch_stale_dead_sid_reuser  	_ev_agentr  r$  r&  _pdc
_mem_notifr1  r  r  	_selected_history_media_pathsr2  r3  r4  r5  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@  rS	  r  _run_message_img_exc_api_run_message_conversation_kwargsr.  _clear_clarify_sessionri  _last_prompt_toks_input_toks_output_toks_context_lengthr	  _resolved_model_session_was_split_compacted_in_placeagent_session_idrc  _session_split_entry_persistedentry_session_id_binding_effective_history_offsetr  r  rp   unique_tagstagrI  all_msgsrK  maybe_auto_title_kwargsr=  r!  r"  r#  r  r+  rM  rN  r@  rT  r  rx  r  r  r=  r  r  r   r  r  r	  r
  r  r  rr  r  ri  r  r  r  r  r  "interim_assistant_messages_enabledlog_mode_enabledr   r  needs_progress_queuer  r  r  r  r  result_holderr  r  r3  r  r  r0  tools_holderr	  rt  s                                                                                                                    @@@@@@@@@@r.   r  z0GatewayRunner._run_agent_inner.<locals>.run_syncQ  sk%   4 %+Ox~$E$E556?K`L
 "0!52$2$8b#?#?#A#A # b&86&ADX&X%_%_%a%a"!%!D!D$"!&+t<<!&*:DAA	 "E " " " `&86&ADV&V%]%]%_%_"466N(,(K(K! + + )L ) )%~
 I>--j99;;L"       &UPS&U&U "!"	        'B#EE'  F    
 &6D"!%!C!C; "D " "D  $#GD(D99;MME}::::::'))
 65\; O #* :%/U":/** 
 #5%G"%;"" BR&< BRARcccccccc#77??H <E8<5!?h.???GHVmDnDn?)1)/I "&I I I I 29C]_c1d1d.5 ["./Y"Z"ZZ,1L) (-!?ho==02-+/L  &(2CCC "'%1Lc"R"R"YVYZZZ!$ *
 )=(<*/*=-2-C#4(46G&+o&?&-fk2&F&F&L") ) ) ,A+@$,$*N#0%< $2#= "L!K!K!K!K%)/L0@.@, , ,( / DDs Dt D D D D D D D 5E.q1  R R RLL!GQQQQQQQQR NS   C d W[           . 88%XXJ
 //7#9% "==kJJ	488#FM4@@ 0  D E"'!$(;TBBKT>488F   $ 6v1  : :"(**["9"9K: : : : : : : : : : : : : : : 63{#3#3a#7#7'21~$"' ,*$
220*.*<*T*T(+ +'' ! 0 0 0*/'''0 "&+
+ $ 0 4 @ @ L LI  O-6]]?A-N-N*    D $(  n7v1  m7 m7#ZZ44F k7&)t"3"3 36f++//VAYYt
36v;;??fQii (t3 : *$ 6: +z 9 - 1 @ 3@ +/? ? .
 1 M7  #KK!F
 !,[   '+&7&;&;K&N&NG6@%6P6P(fU\(f

bfI( AY>U-U-U
 8A 4 4-7 * 6 2 > 2j @ @ #KK!? !,Z9K	   '+&7&;&;K&N&NG6@%6P6P(fU\(f

bfI( AY>U-U-U 8A 4$*1IE  'v}== )!)$*$6$6{$C$C$C$C'/ !) !) !)$(D!) <<UDTUUU 4BE0"LL)NP[\\\26/[m7 m7 m7 m7 m7 m7 m7 m7 m7 m7 m7 m7 m7 m7 m7l # u'83347799   $/$#?24#I#k2B2B3B32GII	  
 egggg    889MNNNN$    } ! !$W-! +! /{;;! ! ! $2>	!
  $t! %*E! &6%5! '8&7! -?,F$! &*%;%Ct! &6%5! "&!3!3! '1nn5H&I&I&I! ')ffVnnn! ')ffX&6&6&6!  %'FF7OOO!!" #%&&...#!$ 137KU0S0S0S%!& .0VV4E-F-F-F'!(  *z)!* *\+!, #NN-!. !' 2 2/!0 %..1!2 #NN3!4 %..5!6 %..7!8 %..9!: )4;!<  't'7@PQQQ=!@ $(#?#?#A#A#AA! !D  
86#5$ 	8 	8 "4);Z/{+ 55777	8 	8 	8 	8 	8 	8 	8 	8 	8 	8 	8 	8 	8 	8 	8 H+W[\\\ ) ( ,7	 "!  ( '7q&9&E""4 % :D9P"Z"5"5VZE*:E'H^/h/D/DdhE,$9E!         " %:E!*.E'#7E %5E"!%!3E&0nn5H&I&I&ORE# 1788EE1 1E- "+!2!2,.&/n&6&6#C D           7 7 7 7 7 7 7 7 74 4 4 4 4 4 4 4 4 4 4 4 4 0?E,  
H; 
H4002SUYZZf#CC#3#1 D     #?4NPTUUD',G[)
 %B77;;<RSSJ*d++ ;%/:TTU
DN)XZ)>)>)@)@)@TXE&O  O # O  O  O  O  O  O  O  O  O  O  O b &<E"
 '8E##LO-4UG-D-DNekk$LO  5Q-"=>R>T>T"U"U5 5 51M1 # wulD'I'IZ'W'W8!752Et#L#L 	 M11NNO $S%7%7Y	   %I!ty{{% % %M )E](S(S            YLT YLd YL YL YL YL YL YL YL YL YL YL| =Q*@V, %T+A2FFN<GQ>%%k4888TD 2-'10 !@ A A%C*733-& & &"
 !M ))$($6$?$C$CK$P$PMM  ) ) )$(MMM)  %*!(W]DTV[-\-\((FM+BDII 1) ) )% "&T) FM+;UCCF+D/D" "
 $( +!"%))&11V;+*$ $  " !-$GG\K\18. #'":":6"B"B&*O-A4HH' '# 5W2E   & 18.[ 	  %T+I4PPN 6+ 6+2O2O%))+t<< 6"Vmg5G 7C(( "-M+;UCC . M?DAAVEV  #66v>>4 $-A4HH! !   %0$52!&=&=>S&T&T###$9;PQQQ;C
  $GGTT +/RRRRRR+E+E#(, ,( $ "NN \ #Hx   LLVLLLLL 306LL ,3L$ / / /V$   (// $+L#N *$ $ 
 -:)( ($ 2=Ca()?@@+ KCJ()?@)9C(63?Ee()AB//0@YYDXYY))*?@@@]]]]]]**+@AAAA    D))*ABBBB *)*?@@@]]]]]]**+@AAAA    D))*ABBBB%M!  + ''))) $ZZ(899N !"KLO!!_F _'&*>?? _$+F,EG[]^$_$_!%f.EqII&v/JANN")&*CEUWX"Y"Y"^]^@FPgfgt<<<DO
 !OE!& _d"n$wu6QSX'Y'Y"Z"Z"ZinKP`wulJGGGV` J J)9Z)G)G%)"E 0   *377DD16. >'.ulD'I'I$--// >A'.3*	    *-===9=66)Z773 (.3&,    ,<(*00222*GG,'"  
 :>6 2 FJ559JJJT::dBBT::B(4#'#3#7#]#]'7 $^ $ $ $ [(A(A /28K3H/I/IF,"LL i & 0 * 0	   %   Z%) %     
 2 55.E 6    $4 //0DeLLL )X,?Xc-FXFX & " !@N0bc->P>P" " " "B&/Sa!b!b% `DJJJwDWDW%_%@vg%@%@%@]_N$n

:r : :  K!;!; fjj599	
 vzz)U;;  K!8!8 "6::mU#C#C (4G)H)H VZZ00 ,VZZ8OQV-W-W +FJJ7Mu,U,U \!_2 %&? )*= !"6  )*;!" #K#$ &2,&5)   V ~--2QJJz2..#&}#5#5(<3 3 3/
/  	T55D"$K) 4 4d?? HHSMMM'..s333* D#**1.BCCC%3d%:TYY{=S=S%SN  7$"2 76FFFFFFGTUVGW_}Q/33JCCC]_H - D     EJ#S75'4#@#@#@tLJO&YgeZ&F&F&FUYO,= #)-%,UGT%B%B(/z4(H(H(/z4(H(H'.ui'F'F(/z4(H(H) ) ) )- $.. / / / / / / / *./ /+ 33F;; E E E E E E/0@AA
 ::6BB E E E E E E/0@A
 %$ 0%9IJJ,&   2    !   D! .! &**-=">">! MRSDT\M!,00R@@@Z\! ]STEU\]1-11+qAAA[\	!
 -PQBR\]1-11+>>>X\! ][\M]h}Q/33M5IIIch! ]STEU`=+//	5AAA[`! -:JTq)--g666PT! $R_`aRb%l]1%5%9%9:M%N%N%Nhl! '$Q'3M!$(()?GGG-2!" a.B#!$ !";%!& %&9'!( %&7)!* +!,  -!. /!0 #22&,jj1Eu&M&M(.

3I5(Q(Q
 VccdUe$oM!$4$8$89JD$Q$Q$QkoA! ! ! !s  AD 
D:&	D5/D:5D:1D*L 
M&MM
P,,P03P0!Q< <R
R7S 
SS,E+[Y.-[.
Y;8[:Y;;=[[[>A] 
];]('];(
]52];4]55];:];$ddd;s s*)s*, A|< ;, <
}-}(#, (}--A, > 
,A@'9A@@
A@'@
A@@A@'@A@@A@'I!A3AK K&AK>K=AK>U/D4AZ$ Z$
AZ1Z0AZ1c                     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&  )rM	  r  r  rp  )r  r0  s    r.   _start_stream_consumerz>GatewayRunner._run_agent_inner.<locals>._start_stream_consumer*W  s      3ZZ * *)!,80377999999999FFmD))))))))))	* *r0   c                  4  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|   ro  )r  rp  rI  r   ri  r  r  re  )r  r  r  r  s   r.   track_agentz3GatewayRunner._run_agent_inner.<locals>.track_agent6W  s      q/)mD))))))))) q/) 
 )$2N2N^3 3) b%2"  
 0<QD -~ 8++J777778 8r0   c            	        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 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-interruptr  rE  r~   z3Interrupt detected from adapter, signaling agent...z,monitor_for_interrupt error (will retry): %s)r  rp  r#  r   r  r  rB   r   r}   rY  rZ  r  r  r   rr  r  rc   rm  rF   )rg  r@  _peek_eventpending_textrv  r  _mon_err_interrupt_detectedr  r  r  r  s          r.   monitor_for_interruptz=GatewayRunner._run_agent_inner.<locals>.monitor_for_interruptWW  s*      4[mC(((((((((2[  $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!E-     [ [ [LL!OQYZZZZZZZZ[g4[s   E D	E F!FFr     long_running_notifications)r  rX  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|   rF  r[  rJ  rG  r%  rH  rI  rA
  r  r   r\  rD
  u   ⏳ Working — z minzHeartbeat edit failed: %sr  FrR   r   rT  z#Long-running notification error: %s)r#  r  rp  	NameErrorr  r0  rD  r   r   r[  rb   rB   rC   r2   rF   r  r   r   rr  r}   r   r   rN   rT  )_notify_adapter_heartbeat_msg_id	_exec_ref_elapsed_mins
_agent_ref_status_detail_want_iteration_detail_arS	  r
  _heartbeat_text_notify_res_ee_ne_NOTIFY_INTERVALr  r  _executor_taskrf  _long_running_mode_notify_startr
  r  r  r  r  r  r  r	  s                 r.   _notify_long_runningz<GatewayRunner._run_agent_inner.<locals>._notify_long_runningW  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_textr  c                    | dS t          | dd          r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_sentThas_delivered_text)r}   r   r   rF   )consumerr  r  r  s       r.    _stream_confirmed_final_deliveryzHGatewayRunner._run_agent_inner.<locals>._stream_confirmed_final_deliveryW  s     ux!6>> t %%,X7KT%R%R".// %%#$6$6z$B$BCCC$ % % %$uu%5s   A 
A! A!r  r?
  r  i  r#   r  r  r  r|   zVoice-backup-interruptr  r  zABackup interrupt detected for session %s (monitor task state: %s)rp  rd  r  r[  r@
  r  rZ   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: %srA
  r4  rI  rG  rH  zaAgent idle for %.0fs (timeout %.0fs) in session %s | last_activity=%s | iteration=%s/%s | tool=%srW  r  u   ⏱️ Agent inactive for u(    min — no tool calls or API responses.z!The agent appears stuck on tool `z` (rB
  z!s since last activity, iteration r%  z).zLast activity: rK  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  )ri  r  r^  r
  r  rT  rT  r  )_AGGREGATOR_PROVIDERSnormalize_model_for_providerr  r_  rE  z5Ignoring control interrupt message for session %s: %sr7  zVoice-drainz9Processing queued message after agent completion: '%s...'r  pending_steerz0Delivering leftover /steer as next turn: '%s...'r/
  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...'r3  u^   Interrupt recursion depth %d reached for session %s — queueing message instead of recursing.queue_message)ri  r  r  ro  z5Stream consumer wait before queued message failed: %sr  ri  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  r  uN   Discarding stale goal continuation for session %s — goal is no longer activez:Queued follow-up session-key resolution failed; reusing %sr   r  ri  )
r   r  r  r  r3  r  r  r=  r  ri  r  final_content_deliveredrW  zSuppressing normal final send for session %s: final delivery already confirmed (streamed=%s previewed=%s content_delivered=%s).r$  )r   rT  r   r  zPEdited streamed message %s for session %s to include plugin-transformed content.z2Failed to edit streamed message for session %s: %sr2  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(   )delete_messagerF   )_mid_adapter_snapshot_chat_id_snapshot_ids_snapshots    r.   _delete_allzRGatewayRunner._run_agent_inner.<locals>._cleanup_temp_bubbles.<locals>._delete_allZ  s       - ! !!"3"B"B 14# #          ) ! ! ! D!! !s   &
33z$Temp bubble cleanup scheduling errorr  r  )r   r   rF   )r  r  r  r  _loop_snapshots    r.   _cleanup_temp_bubblesz=GatewayRunner._run_agent_inner.<locals>._cleanup_temp_bubblesZ  s    ! ! ! ! ! ! ! !,#~%$J     
 !   DDs    - 
;;z-Post-delivery cleanup registration failed: %sNNNr  )r  r<  r=  r  r}  r   r?   r  rN   r  r  rH	  rB   r@   rA   r  r  r  rM  r0  rF   rO  r`   rz  gateway.status_phrasesrV  rW  rC   rc   r   rz  rx  r+  r#  r}   QueuerM  r  r  r   r  r   rm  r  r  r   r  r  ry  rG   ru  r  r  rR  r  r   FEISHUr  rq  r  r  r?  rD  rk  r  rl  r.  r  r  r  r   rY  rZ  r  r   ri  rp  r  r[  r   rr  r  _INTERRUPT_REASON_TIMEOUTrb   r2   r  hermes_cli.model_normalizer  r  r  r  r.	  r  r  r  rD   r   r1   rE   r(  r0
  r  rw  r3  re  _MAX_INTERRUPT_DEPTHr   r  r  rn  rm  r  r  r0  re  rK  r  r  r   r  isawaitabler  r   r  r  r  r  r  r"  rU  rH  rs  rT  r   r  r2  )r  r   r  r  r  r3  r  r  r=  r  ri  r  r  r  r  agent_cfg_localdisplay_configrM  _tplrO  _ftl_resolved_tp_env_tp_display_cfg_platforms_cfg_platform_cfg_legacy_tp_overrides_tool_progress_configuredrW  r]  interim_assistant_messages_mode_thinking_mode_va_vtc_gid_tc_cleanup_adapter_progress_reply_in_thread_slack_adapter_for_progress_progress_thread_idr  r  r  progress_tasklog_taskr5  r  r  tracking_taskr  interrupt_monitor_NOTIFY_INTERVAL_RAWr  _notify_taskr  _agent_timeout_raw_agent_timeout_agent_warning_raw_agent_warning_warning_fired_inactivity_timeout_POLL_INTERVALrR  rp  r  _backup_adapter_backup_agent	_bp_event_bp_text_bp_media_urlsr  
_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_modelr  r  _agent_providerr.  r   r  r"	  rE  r  rv  _leftover_steer_pending_parts_pending_cmd_word_rc_pending_has_stream_consumerr   was_interruptedr.  r  _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_followup_adapterro  _final_is_empty_sentinel_content_delivered_transformed	_streamed
_sc_msg_id	_edit_errr  _rper  rx  r  r  r  r  r  r  r  r  rd  rf  re  r  r  r  r  r  r  r  r  r  r  r  r   r  r  r	  r
  r  r  rq  rr  rs  r  rV  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r}  r  r  r  r0  r  r  r	  rt  s   ``````````````                                                                                                                        @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@r.   r?  zGatewayRunner._run_agent_innerM  s8     :    
	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	H 	H 	H 	H 	H 	H 	H 	H 	H 	H4 !##K?QRR
 
 @QZ433F;;;VZ'!""15H5WWW !&#&( !&w!%y	$ y	$# y	$# y	$s y	$ae y	$ y	$ y	$ y	$ y	$ y	$ y	$ y	$ y	$ y	$ y	$ y	$ y	$ y	$ y	$ y	$ y	$ y	$ y	$ y	$ y	$ y	$V %)!?hn,,*.*B*B6*J*J'*65043:@DD-t 1 1--
 ! 5 5 504---59OV-/?5
 
 
 !
+"f&666 ,,V5EFFF11#!&+t<<$4 2    '+ 	 ::LW]Wfggg 8?H4G"HHHVM]HbrH  	5	 5	 5	 5	 5	 5	nQ	+ Q	+ Q	+ Q	+ Q	+ Q	+ Q	+ Q	+ Q	+ Q	+ Q	+ Q	+ Q	+ Q	+ Q	+ Q	+ Q	+h
 vv"& !133Z
	3 	D 	T 	 	 	 	 	 	 	 	 	 	8	BS 	B4 	BD 	B 	B 	B 	B 	B 	B 	B 226:: .?ho--&2B-GW- 1'7A A## %
'/&&*::: 009IJJJ55ON'%fk4@@(8 6    +/ $!	9c !	9C !	9D !	9 !	9 !	9 !	9 !	9 !	9 !	9 !	9 !	9 !	9 !	9 !	9 !	9Fo	 o	 o	 o	 o	 o	 o	 o	 o	 o	 o	 o	 o	 o	 o	 o	 o	 o	 o	 o	 o	 o	 o	 o	 o	 o	 o	 o	 o	 o	 o	 o	 o	 o	 o	 o	 o	 o	 o	 o	 o	 o	 o	 o	 o	 o	n)  	J#/0F0F0H0HIIM  	=*>>+;+;<<H 	* 	* 	* 	* 	* )*@*@*B*BCC	8 	8 	8 	8 	8 	8 	8 	8.  +KKMM:: &moo8	[ 8	[ 8	[ 8	[ 8	[ 8	[ 8	[ 8	[ 8	[t $/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 $		 	 		 		
 	 	 	 	(G		 ",,BD!I!I3E3I3I//tN!+,JC!P!P3E3I3I//tN"N$2228<< N #( N%  %6$+L'(.% % %      GD!  #1#8#8#:#: /5577 6K 6*.*B*B6*J*J(4Q+ 6 6$+O=T$U$U6$3$I$I+$V$V6 )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5K%6 H  C6$+L'(.% % %      GD!  #1#8#8#:#:!-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+.5577 6K 6*.*B*B6*J*J(4Q+ 6 6$+O=T$U$U6$3$I$I+$V$V6 )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5GC6J # =#/? 	# 0@BX(Y(Y $4$I$I$K$K		$    ']]+?KK
%MM*BAFF	%MM.99	#--(8!<<%MM*:A>>	E~{'   $ J0@+(N(N J$../HIII #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 !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--//  
 !% CY C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_/`/```  '$$&&& "!!!$$&&&!!!  ! + >.q1= % , !&&((()))))))))"1   !%.{CHHHHHHHHHHH#0'2HI ! ! !#**,,,!"---------&5 ! ! ! D!	!   """  11 2    ~ 8++J777 '2C]T`a   "







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







"1   c+/+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!	!   """  11 2    ~ 8++J777 '2C]T`a   "







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







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







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







"1   ( %Q'h%% 8	hll8.D.D 8	\\"2339rF%+!Bv/B
 hll+?@@AAJ!%F%>FF" "  -C D DEEL 98$  I
 & l 	 M_  V&3&   ,0((' 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 s6   0E1 1
E>=E>,F/ /
F<;F<,-W W)(W)3IB@	 *n. -B@	 .
n;8B@	 :n;;AB@	 *p8 7B@	 8
q'q"B@	 "q''FB@	 +x  ?B@	  
x
B@	 xGB@	 -A@ @B@	 @
A@@B@	 @A@@I+B@	 J 0AJ1 J0B@	 J1
AJ>J;B@	 J=AJ>J>D2B@	 Q*AQ3Q3ARRARR	AR&R&/AS7SASSAS7SAS1S.AS7S0AS1S1AS7S6AS7UAUUAU*U)AU*U/$B@	 VAV1 V0B@	 V1/AX/W!AW*W)AX/W*AW<W9AX/W;AW<W<AX/W?B@	 X	AX/X
AX*X%B@	 X*AX/X/A$B@	 ZAZ' Z&B@	 Z'AZ6Z3B@	 Z5AZ6Z6'B@	 [A A\ \B@	 \
A]\)A]	]B@	 ]	A]]A&B@	 ^5&A_ _B@	 _
A_)_&B@	 _(A_)_)A B@	 `*&Aa aB@	 a
AaaB@	 aAaaBB@	 eAe#e#Ae5e4Ae5e9Aff/Ag'gAggAg'gAg!gAg'g Ag!g!Ag'g&Ag'h?AiiAiiAii Ai6 i5B@	 i6)Aj"jB@	 j!Aj"j"&B@	 mAm
m
AmmAmm Am=m=/Aon-An6n5Aon6AooAooAooAooAop&Ap/p/Aqq Aqq=B@	 r"Ar' r&B@	 r'
Ar4r1B@	 r3Ar4r4AB@	 vAvvAvvAvv#Aw w /Axw0Aw9w8Axw9AxxAxx
AxxAxxAxy)Ay2y2AzzAz|A| |A||A||"A|? |?/A~}/A}8}7A~}8A~
~A~~	A~
~
A~~A~(A11B@@B@@	A9BFBBBBBFBBBBBFBBBBBFB"BB?B>BFB?/BDC/BC8C7BDC8BD
	DBDD	BD
	D
BDDBFDBDDABFE(BE1E0BFE1BF	F BFFBF	FBFJABK" K"
BLK,BLLBLNBN' N'
BON1BOOBOr(   r  )r"   r  )r  r|   r  )r	  )r\  )rr  r  r  )r	  r  r  )NNr   NNNNN(s  r   r^  r_  r`  r  r
   rC   r1  __annotations__r  r  r  r  r  r   r0  r  r   r  r  r  r  r  r  r  r  r  r  re	  r  r  rx  r  r   r=  r>  r?  r@  rD  r   r  r  r  r  r  r  r  r  rn  r   r&  r  r=  r  rE  r@  r  rR  rZ  r\  rh  r   rr  ru  r  rt  r  r  r  propertyr  r  r  r  r  r  	frozensetr  r  r  r  r  r  r  r  r  r  r  r  rA   r  r  r  r  r  r	  r  r  r"  r$  r(  r&  r'  r4  r<  rF  rT  r[  rb  rf  rk  rr  rw  r{  r  r  r  r  staticmethodr  r  r  re  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  rq  r  r  r  r  r  r  r  r  r  r  r%  r  r&  r  r  r  r  r  r  r  Futurer  r  r  r  r  rc   r  r  r  r	  r   r+  rU  r2  r4  r9  r>  rP  r^  r`  rd  r
	  r	  r	  r  r  r	  r  r  r  rh	  rp	  rr	  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
  r9  r  r
  r  r  r
  r
  r%  r*  r.  r5  r
  rD  rV  r[  rQ  ri  rP  rV  r  rW  rX  r  r  r  r  r  r  r  r  r  r  r(  r#  r-  r0  r1  r3  r9  r@  rL  r`  r   r
  rk  ri  rR  r  r  r  _APPROVAL_TIMEOUT_SECONDSr  ry  WHATSAPPr
  r!  EMAILSMSDINGTALKr  WECOMWECOM_CALLBACKr
  r
  r

  r  _UPDATE_ALLOWED_PLATFORMSr  r  r  r  r  r  r2  rJ  r  r  r  r  r  r	  r  r  r  rY  r  r  r  rZ  r  rP  objectr  r  r"  r$  r  r  r  rK  rP  rM  classmethodrR  rd  rl  rv  r  r  r}  rU  r  r0  r
  rB  rI	  r  r
  r
  rI  rG  r
  rU  rF  r  rE  r3  r  r.	  r  r  r  r  r  rK	  r  r<  rH  rF  r  r?  r  r0   r.   r  r    s57          ,.S%Z(---'c'''&OS&&&$IEIII $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}+++:<d3S#X#67<<<BD$d3S#X+>&?DDD>@ $sDcN':";@@@@B#T#x}*<%=BBB8:c49n!5:::/1De,111')d38n)))). $... 6:(>2999!$$$$;?X&78???-2$d222x8 x8x6 x8 x8 x8 x8v   >-
 -
 -
 -
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 6 6 6 6  :?  26	   .<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@@ 
@ @ @ @> +/%)&*R% R% R% 'R% c]	R%
 d^R% 
sDy	R% R% R% R%h-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 \ \ \ \|## #$ # # # #
)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 !! !  /	!
 
.	!! ! ! !F @D          U3 U4 U U U \US 3 SV    >	 	 	 	 	 	
 
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" '+#'#'3 3 33 3
 d^3 C=3 C=3 
3 3 3 38 $(#'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 28TT #4.T 
	T T T T" %)) ) c]) 
#	) ) ) )6 	M MM 	M
 
M M M M. d
    \$ 
$ 
 
 
 \
 
3 
 
 
 \
 A# A A A \A.     \$     \6 D    \ $+    \($ $ $ $ $@ !$c !$$+ !$$ !$ !$ !$ \!$F
$sCx. 
 
 
 
hsm    
 
# 
 
 
 
  
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j| jZ] jbf j j j jX9#% 9#E$sCx.RVBV<W 9# 9# 9# 9#vQ Q Q Q Q QE E E EN2T#s(^ 2PT 2 2 2 2hc]   }	
 
   < $.$. $.
 $. 
$. $. $. $.N -/& & &&&)&	& & & &P'c 'd ' ' ' 'R 0S T    6/c / / / /b     *w w w wr]S ]S ]S ]S~ 38U   4 d W[    J %9FFF ?$? ? 	?
 
? ? ? ?:, 4     C    4` ` ` `"hc h h h hTI I# I I I IV
t 
 
 
 
 26'+ -. 8$ 
	   4CT C C C CJ  !  #?Ca K K K K KZ0* 0*u 0*t 0* 0* 0* 0*dq>$sCx. q>T q> q> q> q>fp' p'c p' p' p' p'dc    H' H' H' H'T   @         !& %p p p p 	p
 p 
p p p pd* * * *G G G G GRdd/5d@DUCZ@Pd	d d d dL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 $X $X# $X $X $X \$XL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l\B< \BHSM \B \B \B \B|0> c d    *
UC 
UD 
U 
U 
U 
U$ &*X X X X 	X
 d38n%X c]X 
#X X X X@ &*
 
 
 
 	

 d38n%
 c]
 
#
 
 
 
0?s ?tCy ? ? ? ?     * %6    Xc    E9# E9_b E9 E9 E9 E9N8+ +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B,B,&)B,7:B, B, B, B,R #4 44 4 	4
 4 
4 4 4 4lHd H H H HJ\ J J J J J JXcIcI cI
 
cI cI cI cIX +/*.+/    	
 #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 
 
 
 
C C    ll l 	l
 
l l l l2"6"6 "6 	"6
 
"6 "6 "6 "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V
 V
 	V

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

  g
 g
 g
 !g
 #3-g
 
c3hg
 g
 g
 g
d	  (, !*.(,%).226, ,, , d38n%	,
 , , , !, , #3-, !, TN, 'sm, !), 
c3h, , , ,\.} .# . . . .`6%} 6% 6% 6% 6% 6%~  (, !*.(,%).226[4 [4[4 [4 d38n%	[4
 [4 [4 [4 ![4 [4 #3-[4 ![4 TN[4 'sm[4 !)[4 
c3h[4 [4 [4 [4 [4 [4r0   r        ?)r  
stop_eventr  c                   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  Fr  Nz#Planned-stop watcher tick error: %s)r  rR  rS  r  rf   r}   rl  call_soon_threadsaferF   r   rr  )	rP  runnerr   shutdown_handlerr  rR  rS  r  r  s	            r.   _run_planned_stop_watcherrW  Z  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  rl  c                 <   ddl m}m} ddlm} d}d}d}	d}
t
                              d|           d}|                                 s9|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    r	  |d          }|rt
                              d|           n2# t          $ r%}t
                              d|           Y d	}~nd	}~ww xY w	  |d          }|rt
                              d|           n2# t          $ r%}t
                              d|           Y d	}~n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    rU	 ddlm}  |t!          d          d            n2# t          $ r%}t
                              d|           Y d	}~nd	}~ww xY w|                     |           |                                 9t
                              d           d	S )u  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/document cache + expired ``hermes debug share`` pastes once per
    hour, and polls the curator hourly (its inner gate enforces the real
    weekly cadence).
    r   )cleanup_image_cachecleanup_document_cache)_sweep_expired_pastesr  r)  z+Gateway housekeeping started (interval=%ds)rZ   r  Nz*Channel directory refresh scheduling errorr  r{  r  z#Channel directory refresh error: %sr  )max_age_hoursz-Image cache cleanup: removed %d stale file(s)zImage cache cleanup error: %sz0Document cache cleanup: removed %d stale file(s)z Document 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: %s)r   ri  )r\  s    r.   r   z-_start_gateway_housekeeping.<locals>.<lambda>~[  s    6;;}c+J+J r0   )idle_for_seconds
on_summaryzCurator tick error: %szGateway housekeeping stopped)ri  rY  rZ  hermes_cli.debugr[  r   ri  r  r  r  r   r.  rF   rr  agent.curatorr]  r1  rl  )rP  r  r   rl  rY  rZ  r[  IMAGE_CACHE_EVERYCHANNEL_DIR_EVERYPASTE_SWEEP_EVERYCURATOR_EVERY
tick_countr  r  r  r  deleted	remainingr]  s                      r.   _start_gateway_housekeepingrj  .[  s    SRRRRRRR666666M
KK=xHHHJ!! =*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..A--B??? ZKK OQXYYY A A A<a@@@@@@@@AD00rBBB ]KK RT[\\\ D D D?CCCCCCCCD ))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: 	))){ !! =*| KK./////sy   AB 
C&CC)D 
D1D,,D15)E 
F)F		F+G 
G6G11G6!H% %
I/II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   rl  N)cron.scheduler_providerrl  r
	  )rP  r  r   rl  rl  s        r.   _start_cron_tickerrn  [  sC     ?>>>>>"":tV^"_____r0   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  rD  r  is_aliverp  )r-  r  ro  r  s       r.   _await_thread_exitrr  [  s       ~t'))..003sG3D3DDH
//

 " 8 : : ? ? A AH L LmD!!!!!!!!! //

 " 8 : : ? ? A AH L L    r0   r4  	verbosityc                 |  <=K   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          |           =ts          |          =_:        d	<dT<=fd,	}"=f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          |&=|$|"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t                       	 dd8lTmU}- tw          j<                    }.|.V                    d|-           d{V  n2# t          $ r%}t                              d9|           Y d}~nd}~ww xY w=L                                 d{V }/|/sd	S =jW        rD=jX        r t                              d:=jX                   =jY        t          =jY                  dS =j[        s=\                                 d{V  =j]        r)=jX        r t                              d;=jX                   d	S 	 dd<lTm^}0  |0             n# t          $ r Y nw xY w=jY        t          =jY                  dS dd=l_m`}1ma}2 t          jI                    }3 |2            }4=jb        tw          j<                    d>}5t          |4|1          rt          =je        d?d	          r	 dd@lfmg}6 t           |6dA                    }7|7r8|7|5dB<   t                              dCt          |7          dD |7D                        n2# t          $ r%},t                              dE|,           Y d},~,nd},~,ww xY wt          |4|1          r=fdF|5dG<   t          jJ        |4jL        |3f|5ddHI          }8|8L                                 t          jJ        t          |3f=jb        tw          j<                    d>ddJI          }9|9L                                 t          =dKd          }:t          |:          r
 |:             =\                                 d{V  	 ddLlQml};  |;             n# t          $ r Y nw xY w=j]        r)=jX        r t                              d;=jX                   d	S |3m                                 	 |4n                                 n2# t          $ r%}t                              dM|           Y d}~nd}~ww xY wt          |8t          N           d{V s t                              dOt                     t          |9t          N           d{V  |&m                                 |'r                    dPN           	 dd<lTm^}0  |0             n# t          $ r Y nw xY w=jY        t          =jY                  <r#=js        st                              dQ           d	S =jt        r)t                              dR           t          dS          dS )Ua7  
    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_existsr3
  TrO  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.pidr  )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_stderrr  )r-  r  )log_startup_security_warnings)r  )r-  rG   z-Startup security audit failed (non-fatal): %sr  )r   rZ   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 cleanlysignal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#   )timeout_secondsz!spawn_async_diagnostic failed: %s)r  r  rF   r   rr  r  SIGINTr  r  r  r  r  ri  r  r   r  r  r  r  )received_signalplanned_takeoverr  r  planned_stopr  r  r  r  _shutdown_ctxr  	_diag_logr  rU  s               r.   shutdown_signal_handlerz.start_gateway.<locals>.shutdown_signal_handler\  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+  rU  s   r.   restart_signal_handlerz-start_gateway.<locals>.restart_signal_handler]  s"    4@@@@@r0   SIGUSR1z6Skipping signal handlers (not running in main thread).zplanned-stop-watcherr  )write_pid_filer	  rw  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.)start_nous_auth_keepalivez%Nous auth keepalive did not start: %s)rO  zMCP tool discovery failed: %szGateway exiting cleanly: %sz Gateway exiting with failure: %s)rN  )rl  resolve_cron_scheduler)r  r   rp  )r	  r	  profile_homesz:Cron scheduler will tick %d profile(s) under multiplex: %sc                 L    g | ]!}t          |t                    r|d          n|"S )r   )r@   r  r  s     r.   r  z!start_gateway.<locals>.<listcomp>]  s/    PPPQZ5118QqTTqPPPr0   z6Could not resolve profile homes for multiplex cron: %sc                  "     j         p j         S r(   )r  r  r  s   r.   r   zstart_gateway.<locals>.<lambda>]  s    = =5
 r0   can_dispatchzcron-scheduler)r  rQ  r  r  r   zgateway-housekeepingrp	  )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(   )ugateway.code_skewru  r  rv  rw  rx  r	  r	  ry  r`   r  r   ri  rz  rF   rr  r{  ProcessLookupErrorPermissionErrorrd   r  r|  r}  rM	  rD  rp  r   r~  r#  r   r  rC   printtools.skills_syncr  hermes_loggingr  r  r  !hermes_cli.security_audit_startupr  rK  r  r   r  r  WARNINGr  rB   DEBUGStreamHandlerr  r  r  r  levelr  r   r  r  r  set_exception_handlerr   r  current_threadmain_threadr  r  r  add_signal_handlerNotImplementedErrorr   r  r  r  rW  r
	  atexitr  FileExistsErrorrq  hermes_cli.nous_auth_keepaliver  ry   rT  rO  r@  r  r  r  
SystemExitr  r	  r  rN  rm  rl  r  r  r@   r}   rG   r  r	  rq  r   rj  r   r  rc   r  rr  _CRON_SHUTDOWN_DRAIN_TIMEOUT$_HOUSEKEEPING_SHUTDOWN_DRAIN_TIMEOUTr2   r  r  )>rG   r4  rs  ru  rv  rw  rx  r	  r	  ry  existing_pidexisting_start_timerz  r  r{  _old_gateway_childrenr|  r}  old_gateway_exitedr  r~  r  	_releasedr-  r  r  r  r  
_audit_cfgr  
_audit_excr  _stderr_level_stderr_handlerr  r  r   sig_planned_stop_watcher_stop_planned_stop_watcher_threadr  r  _current_pidr  r   rO  _loopr  rN  rl  r  	cron_stopcron_providercron_start_kwargsr	  r  cron_threadhousekeeping_threadstart_watchdogr  r  rU  s>                                                               @@r.   start_gatewayr  [  sI     $ :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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 LLNN""""""G u!  	LLL68JKKK 'V-...t?  &&(((((((((* 	! U?ASTTT5	;;;;;;  """" 	 	 	D	'V-...t 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4s  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5` 
`0`++`0.c? ?
ddAg- -
h7hh;l 
ll!m6 6
n% n  n%+p< <
q	q	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--configr  zPath to gateway config file)r_
  z	--verboser  
store_truezVerbose output)r  r_
  r9  r:  rZ   )hermes_cli.stdior  rF   argparseArgumentParseradd_argument
parse_argsrG   rH  rI  rJ  rn  rn  r  r  r  r  r
  r@   r0  _exit_after_graceful_shutdown)r  r  parserrQ  rG   rH  rP  rH  r  r  r  s              r.   r*  r*  7^  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                 R   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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	  )drain_log_queuer  r  N)r\   r  r  r  rF   r  r	  r	  r  r  r`   _exit)r  r  r	  r	  r  s        r.   r  r  l^  s   @ :sz*  	LLNNNN 	 	 	D	PPPPPPPP$$&&&&   222222$$$$$   HYs0   1
>>A 
A,+A,0B 
BB__main__r  r(   r?  r  )r   N)r6  r   r%   N)rc  r   )r%   rn  )r%   rD  )r   rt  r%   N)NNr  )r  )NFr   (  r`  hermes_bootstrapModuleNotFoundErrorr  concurrent.futuresr  r  r  r  r  r`   r)   r  ri   r\   r  r  r  rD  sqlite3collectionsr   contextvarsr   r  r   r   typingr   r	   r
   r   r   r   r   r   agent.account_usager   r   agent.async_utilsr   r   r<  r   r   r   r   r   r   r   r   agent.conversation_loopr   
agent.i18nr   rK  r   rh  r   r  r  r  r  r'  compiler*  
IGNORECASEDOTALLr   rC   r4   r2   r   r   rI   rB  rQ   rS   _GATEWAY_PROVIDER_ERROR_REr   r   r   r   ry   rP   r   rh  r   r   r   r   r   r   r   r   r   r   r   r   r  rA   r  rc   r  r+  rC  r1  r6  r;  r?  rG  rS  rZ  r  r@  rh  rk  r  r  rl  rs  r{  r  r  r  r  r  r  r  r  agent.replay_cleanupr  _is_interrupted_tool_resultr  r  r  r  r  r  r  _is_dangerous_confirmationr  r  r  r  r  r  r0  r  r  r	  r  r  r  r  r  r!  ra   rg   rh   r]   r_   rj  r#  r$  utilsr%  r&  r'  r(  r  dotenvr)  hermes_cli.env_loaderr*  	_env_pathr^   r4  r5  r3  rW  
contextlibrX  _contextmanagerrz  rY  _PORT_BINDING_PLATFORM_VALUESrZ  r	  rW  r\  rb  rm  rs  r{  r0  r1  _config_pathrf   rH  rO  rI  rl  rJ  r  r=  rL  r?  rM  rF   r  _key_valr@   rB   _terminal_cfgrD   rE   _terminal_backend_terminal_env_map_cfg_key_env_varr|	  r  r  rq  rQ  _auxiliary_cfg_aux_bridged_keysr  r  r	  re   	_task_key	_task_cfg_prov_model	_base_urlrr  r  _upper
_agent_cfg_sessions_cfgr  _tz_cfg_security_cfg_redact_gateway_cfg_strict_allow_dirs_allow_dirs_strrl   _trust_recent_trust_recent_seconds_bridge_errr  r   r   r  r  dir_network_cfg_bootstrap_excr  r  gateway.cwd_placeholderr  r  _configured_cwdrz  r6  _resolved_cwdr   r  rx  r  rn  r  ru  rq  r:  r  r   r  r  r  r  r  r  r  r  r	  gateway.deliveryr
  r  gateway.turn_leaser  gateway.authz_mixinr  gateway.kanban_watchersr  gateway.slash_commandsr  ri  r  r  r  r  r  r  r  r  gateway.shutdown_watchdogr  r  r  r  gateway.restartr  r  r  r  gateway.whatsapp_identityr   _canonical_whatsapp_identifierr!  _expand_whatsapp_auth_aliasesr"  _normalize_whatsapp_identifierr  r   rJ  r
  r
  r

  rF  r5  r<  rM  r  rE  r  r^  ra  rc  rV  rs  rz  r  r  r  r  r  r  r  r  r
  r
  r   _INTERRUPT_REASON_SSE_DISCONNECTr	  r	  r  r  r  r  r  r  r  r?   r  r  r  r  r  r'  r/  rC  rL  weakrefr  rN  r  rg  rc  rm  rs  rx  r}  r~  r  r  AbstractEventLooprW  rj  rn  r  r  r  rr  r  r*  r  r  r0   r.   <module>r'     s*    "	 	 	 	
 	D	             				 				   



         # # # # # # $ $ $ $ $ $             N N N N N N N N N N N N N N N N N N N N P O O O O O O O T T T T T T T T	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 G F F F F F       % % % % % % 9 9 9 9 9 9  # )- &+. (&6 #)rz*TUU &BJ	> MBIA! ! H
= 
= 
= 
= 
= 
=, #-"*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	
 
 
 
)] )t ) ) ) )X ,
% ,04S#X ,	 ,  ,  ,  ,F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 %S Xe_    D, , , , ,$S 5 U    $  #'	) ) )) 
%) %	)
 
) ) ) )> 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 . . . . .h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6!	  |h9O9O9Q9Q9YZ[9\_e9e f f f f0 0 0 0:!V !V !V !VH     9 8 8 8 8 8           <   P P P P P&: P P P / / / /D       F: HX ]a    ( $$dee (1:'> $ m+ o
n
T,111 	-R"5?2&&,"D	- 	- 	- 	- 	- 	- 	- 	- 	- 	- 	- 	- 	- 	- 	- 	766666%%	0000006=6t<<DD 	 	 	D	 **,, 	- 	-JD$z$c5$ 788 -T=S=S#&3t99
4  R00 8	9ZZt<< 8	9 #!!),,T
~0N0NTRT! !eggeegg !>!~! -! 1	!
 #$?!  7! %&C! $%A! 5!  !9! /! /! /! -!  !9!  #$?!!" !";#!$ )H";3%A1Y";+M3](G5$?9! ! !< '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LcAd=e=e
9:0J>>?Bs@A@ @
;<
 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
>"                                           Q P P P P P P P 7 7 7 7 7 7 9 9 9 9 9 9 > > > > > > < < < < < <	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	                                
	8	$	$ NVOZ^N6b (3-    J !&(( ,% E    
Dt D D D DN     ,HSM    "/t / / / /d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 !'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
ax ax ax ax ax-/IKd ax ax axTq	 V' V' V'V' 
#V' V' 
V' V' V' V'rV0 V0IO V0ad V0 V0 V0 V0r` `9? `X[ ` ` ` `(  $  (, $ GJ! !Y%&!16!>C!	! ! ! !.t	 t	 7 t	 t	bjknbo t	x| t	 t	 t	 t	n2- 2- 2-j:S :T : : : :z zDFFFFF s   
 5y Z%y %Z))y ,Z)-y [ y [!y  [!!G>y  .d y dy dUy z)Az$$z)-A#| |>|77|>} ~}==~~ 
#
