
    Jjn)                    t&   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! ddl"m#Z#m$Z$ dd	l%m&Z& dd
l'm(Z( ddl)m*Z* ddl+m,Z, dZ-dZ.dZ/dZ0dZ1 ej2        d          Z3 ej2        dej4        ej5        z            Z6 e7h d          Z8dede9fdZ: ej2        dej4                  Z; ej2        dej4                  Z< ej2        dej4                  Z= ej2        dej4                  Z> ej2        d           ej2        d           ej2        d           ej2        d           ej2        d            ej2        d!           ej2        d"          fZ?dd#Z@dedeAfd$ZB	 ddd%d&eeeAef                  dedeeeAef                  fd'ZCd(eDde9fd)ZEd*d+d,eeAef         ddfd-ZFd.eAdeAfd/ZGd0d1deAfd2ZHd.eAdeAfd3ZI ej2        d4ej4                  ZJd.eAde9fd5ZKded.eAdeAfd6ZLded7eAd8eAdeeA         fd9ZMdeAfd:ZNd; ZOded<ed=edeeA         fd>ZPd?eQd@eAdAeAde9fdBZRdCdddDd?eQd@eAdAeAdEe9dedFeSe         dz  de9fdGZTd.eAdedeAfdHZUdIZVdJedeeW         fdKZXdeWfdLZYdMeAdEeWdeWfdNZZdddOdJedPeeW         dQeeW         de9fdRZ[dSZ\e]eAdTf         e^dU<   dVeAdWedXeeAef         deeAef         fdYZ_dZZ`d[Zad\Zbd]eeA         de9fd^Zcd?eeQ         de9fd_ZdddCd`dae eeAef                  d]eeA         dbe9de]e eeAef                  eeA         f         fdcZedde eeAef                  deede eeAef                  fdfZfd8edgeeA         defdhZgdaee eeAef                           defdiZhh djZiddkljmkZlmmZnmoZp dlZqdmZrdWede9fdnZsdWedefdoZtdpZu ej2        dqej4                  Zv	 	 ddre eeAef                  dsewdteeS         de]e eA         e9f         fduZxdve eeAef                  deSfdwZyddxZzdyeAdeAfdzZ{dyeAdeAfd{Z|de9fd|Z}defd}Z~de9fd~ZddZde
j        d<    ez             ej                            d eA 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ewfdZddlmZ  e7h d          Z G d de          Zedd            Z ej2        d          ZddhZedz  Ze                                r	 ddlZ eed          5 Z ej        e          pi Zddd           n# 1 swxY w Y   ddl)mZ  ee          Z	 ddlmZ  ej        e          Zn# e$ r Y nw xY we                                D ]1\  ZZ eeeAeweWe9f          ree
j        vr eAe          e
j        e<   2e                    di           Zerr eeeQ          re eAe                    d          pe
j                            d          pd                                                                          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 eAe          dv r%edk    rJ eeeA          r>ddlmZ  eee                                          se
j                            e          Z eeeeQf          r ej        e          e
j        e<    eAe          e
j        e<   e                    di           Zer eeeQ          rh dϣZ	 ddlmZ  eæ            D ]Ze                    ed                    n# e$ r Y nw xY weD ]DZe                    ei           Z eeeQ          s& eAeǠ                    dd                                                    Z eAeǠ                    dd                                                    Z eAeǠ                    dd                                                    Z eAeǠ                    dd                                                    ZeƠ                                Zeredk    ree
j        de͛ d؝<   eree
j        de͛ dٝ<   eree
j        de͛ dڝ<   eree
j        de͛ d۝<   Fe                    di           Zer eeeQ          rdev r eAed                   e
j        d<   dev r eAed                   e
j        d<   dev r eAed                   e
j        d<   dev r eAed                   e
j        d<   dev r eAed                   e
j        d<   dev r eAed                   e
j        d<   e                    di           Zer eeeQ          r}dev r eAed                   e
j        d<   dev r eAed                   e
j        d<   dev r eAed                   e
j        d<   dev r"de
j        vr eAed                   e
j        d<   e                    dd          Zer( eeeA          reР                                e
j        d<   e                    di           Z eeeQ          r<eѠ                    d          Zeҁ% eAeҦ                                          e
j        d<   e                    di           Z eeeQ          r+eӠ                    d          Zeԁerdnde
j        d<   eӠ                    d          ZerP eeeA          reZn5 eeee]f          r%e
j                            d eD                       ZndZer
ee
j        d<   eӠ                    d          Zeفerdnde
j        d<   eӠ                    d           Zeځ eAeڦ          e
j        d<   dev rIe
j                            dd                                          s eAeӐd                   e
j        d<   nO# e$ rGZ eܐd eeۦ          j         deۛ ej                    eܐdej                   Y dZ[ndZ[ww xY w	 ddlmZ d	 e            v reni                     d
i           Z eeeQ          r$e⠳                    d          r ed           n)# e$ r!Z eܐde ej                   Y dZ[ndZ[ww xY w	 ddl)mZ  e             n)# e$ r!Z eܐde ej                   Y dZ[ndZ[ww xY w	 ddl)mZ  e             n)# e$ r!Z eܐde ej                   Y dZ[ndZ[ww xY wde
j        d<   de
j        d<   ddlmZmZ e
j                            dd          Zereev r eee
j                            dd           e
j        d           e
j        dĐd                                          dv  eA ej                                        Zee
j                            dd           n
ee
j        d<   ddlmZmZmZmZmZmZmZ ddlmZmZmZmZmZmZmZ ddlmZ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 dd!lmZmZmZmZ dd"lmZmZmZ  e	j        eަ          Zej        d#ej        d$ej        d%ej        d&ej         d'iZ!deeA         fd(Z" e#            Z$deQfd)Z%deAdeQfd*Z&deeA         fd+Z'deQdz  fd,Z(d-ewdeAfd.Z)d-ewde9fd/Z*d-ewde9fd0Z+d-ewde9fd1Z,deAfd2Z-d3eAd4eAd5eAdeAfd6Z.d7eWdeAfd8Z/d9eAdeeA         fd:Z0d;eAde
dz  fd<Z1d=Z2d>Z3d?Z4d@Z5dAZ6dBZ7 e7e2                                e3                                e4                                e5                                e6                                e7                                h          Z8d8eeA         de9fdCZ9dDede]eAdz  eAdz  f         fdEZ:dFeAdeAdz  fdGZ;ddHdeAfdIZ<de9fdJZ=defdKZ>deQfdLZ?deQfdMZ@ddNeQdz  deAfdOZAdddPdQeAdReeA         dSeeA         deeA         fdTZBdddPdNededQeAdReeA         dSeeA         dee         fdUZCdeeeA                  fdVZDd;eAddWfdXZEdYeQdd1fdZZFdd\ZGddlHZId] aJeIjK        e^d^<   dd_d`eQdaeAdbewdeAfdcZLd`eQde9fddZMdeeQdfeQdeQfdgZNddjZO G dk dleee          ZPdmdndoejQ        d*ejR        dpeWddfdqZSddoejQ        dsewfdtZTddoejQ        dsewfduZUdvZVdwZW	 ddyeejX                 deWdzeWde9fd{ZYddNee         d|e9d}eew         de9fd~ZZd Z[dewd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)CallableDictOptionalAnyListUnion)fetch_account_usagerender_account_usage_lines)safe_schedule_threadsafe)t)cfg_get)get_fallback_chain         @      >@      @i   z'(?<![\w:/])/([A-Za-z0-9][A-Za-z0-9_-]*)uI  (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|compacting\s+context\s+[—-]\s+summarizing\s+earlier\s+conversation|preflight\s+compression|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)>   localwebhook
api_servermsgraph_webhookplatformreturnc                 .    t          |           t          v S )zBTrue only for programmatic/local surfaces that must keep raw text.)_gateway_platform_value_GATEWAY_RAW_TEXT_PLATFORMSr   s    1/home/rurouni/.hermes/hermes-agent/gateway/run.py _gateway_surface_passes_raw_textr#   h   s    "8,,0KKK    z(api\s+(?:call\s+)?failed|provider\s+authentication\s+failed|non-retryable\s+error|rate\s+limited\s+after\s+\d+\s+retries|error\s+code\s*:|\bhttp\s*\d{3}\b|incorrect\s+api\s+key|invalid\s+api\s+key)z(cybersecurity\s+risk|security\s+policy|safety\s+policy|policy\s+violation|violat(?:e|es|ed|ion)|blocked\s+(?:because|by|under)|request\s+(?:was\s+)?(?:blocked|rejected)|disallowed|moderation)zV(provider\s+authentication\s+failed|incorrect\s+api\s+key|invalid\s+api\s+key|\b401\b)z7(rate\s+limit|rate-limited|\b429\b|quota|usage\s+limit)z%\bsk-[A-Za-z0-9][A-Za-z0-9_\-]{12,}\bz\bgh[pousr]_[A-Za-z0-9_]{20,}\bz\bxapp-\d+-[A-Za-z0-9\-]{20,}\bz!\bxox[baprs]-[A-Za-z0-9\-]{20,}\bz\bhf_[A-Za-z0-9]{20,}\bz\bglpat-[A-Za-z0-9_\-]{20,}\bz'(?i)\b(Bearer\s+)[A-Za-z0-9._\-]{20,}\bc                     t           j        dk    rdS t          t                                                    j        j        } g }t          j                            d          r2|	                    t          t          j        d                              |	                    | dz             t                      }|D ]}	 |                                }n# t          $ r |}Y nw xY wt          |                                          }||v rQ|                    |           |dz  dz  }|                                st          |           }t          |          }|t           j        vr t           j                            d|           t%          j        |           |t           j        v rt           j                            |           t           j        rt           j        d         |k    rdnd}	t           j                            |	|           t          |          t          j        d<   ||g}
t          j                            d	          r%|
	                    t          j        d	                    t          j                            t.                              |
                    t          j        d	<    dS dS )
a  Make detached Windows gateway runs see the Hermes venv packages.

    Some Windows restart paths run the gateway under uv's base ``pythonw.exe``
    to avoid the venv launcher respawning a visible console interpreter.  That
    mode can import the source tree via cwd/PYTHONPATH but still miss optional
    packages installed only in ``venv/Lib/site-packages`` (notably the MCP SDK).
    Patch the live process before MCP discovery so tool injection does not
    depend on every launcher preserving PYTHONPATH perfectly.
    win32NVIRTUAL_ENVvenvLibsite-packagesr      
PYTHONPATH)sysr   r   __file__resolveparentosenvirongetappendsetOSErrorstrloweraddexistspathinsertsite
addsitedirremovepathsepjoindict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_importsrO      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 )r7   getattrstripr8   r!   s    r"   r   r      s9    wx(339r::@@BBHHJJJr$   r!   metadatac                \    t          |          dk    r| S t          | pi           }d|d<   |S )zEMark Discord lifecycle/status sends without changing other platforms.discordTnon_conversational)r   rB   )rU   r   mergeds      r"   _non_conversational_metadatarZ      s=     x((I55(.b!!F#'F Mr$   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   r+   TF)r5   idr9   type__name__	__cause____context__)r[   rF   curdepthtransient_class_namesidentnames          r"   _is_transient_network_errorru      s     UUD#&CE   /ebjj3D==
Cyy!(((4m.s /ebjj 5r$   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taskrR   get_namez9Gateway swallowed transient network error from %s: %s: %sz<unknown task>exc_info)r3   ru   hasattrr}   repr	Exceptionloggerwarningrl   rm   __traceback__default_exception_handler)rv   rw   r[   rz   r|   	task_names         r"   _gateway_loop_exception_handlerr     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.
    rR   r   redact_sensitive_textTforcec                 D    | j         r|                     d          nddz   S )Nr+   rR   z
[REDACTED])	lastindexgroup)ms    r"   <lambda>z5_redact_gateway_user_facing_secrets.<locals>.<lambda>O  s     *K!''!***|)[ r$   )r7   agent.redactr   r   _GATEWAY_SECRET_PATTERNSsub)r   redactedr   patterns       r"   #_redact_gateway_user_facing_secretsr   6  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   rR   Tr   )r   r   r7   )r   r   s     r"   _redact_approval_commandr   S  s6     322222  SYBt<<<<r$   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   c  s}    $$T** 
<	
 	
 #))$// 
S	
 	
 $$T** jii	; r$   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  
   )r7   rT   len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==>>>r$   c                     |s|S t          |           r|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#   r   r7   r   r   )r   r   r   s      r"    _sanitize_gateway_final_responser     s\      '11 23t99==H)(33 7,X666Or$   
event_typerz   c                    t          |pd                                          }|sdS t          |           r|S t          |          }t                              |          r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.
    rR   N)r7   rT   r#   r   _TELEGRAM_NOISY_STATUS_REr   r   r   )r   r   rz   r   s       r"   _prepare_gateway_status_messager     s     w}"##%%D t'11 .t44D ''-- t)$// 3,T222Kr$   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   rR   )r7   rS   rT   )notices    r"   render_notice_liner     s/     wvvr**0b1177999r$   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rU   )rS   callablesend)adapterchat_id
status_keycontentrU   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Br$   source_thread_idevent_message_idc                     t          | d|           }t          |pd                                          }|rt          |          S |dv r|rt          |          S dS )zAReturn thread/root ID that progress/status bubbles should target.rQ   rR   >   slack
mattermostN)rS   r7   r8   )r   r   r   platform_valueplatform_keys        r"   _resolve_progress_thread_idr     sn    Xw99N~+,,2244L %#$$$...3C.#$$$4r$   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
isinstancerB   r3   )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Er$   Fdefaultr   require_platform_override_forr   r   c                   t          |p|          }d |pt                      D             }||v rt          | ||          sdS ddlm}  || |||          }	t          |	t                    r|	S t          |	t                    r(|	                                	                                dv S |	t          |          S t          |	          S )aj  Resolve a boolean display setting with optional platform-only opt-in.

    Some display features expose assistant scratch text rather than deliberate
    user-facing output.  For high-noise threaded chat surfaces such as
    Mattermost, a global opt-in is too broad: they must be enabled with an
    explicit display.platforms.<platform>.<setting> override.
    c                 ,    h | ]}t          |          S  r   ).0	candidates     r"   	<setcomp>z0_resolve_gateway_display_bool.<locals>.<setcomp>
  s0        	 	**  r$   Fr   resolve_display_setting>   1onyestrue)
r   r5   r   gateway.display_configr   r   r   r7   rT   r8   )
r   r   r   r   r   r   current_platformplatform_onlyr   rQ   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}};;r$   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.
    rQ   telegramr   )_sanitize_telegram_namematchr   c                 x     |                      d                    }|rd| n|                      d          S )Nr+   /r   )r   )r   	sanitizedr   s     r"   _replacez/_telegramize_command_mentions.<locals>._replace-  s<    ++EKKNN;;	"+?9Q?r$   )rS   hermes_cli.commandsr   reMatchr7   _TELEGRAM_COMMAND_MENTION_REr   )r   r   r   r   r   s       @r"   _telegramize_command_mentionsr      s     Xw99N##;;;;;;@ @# @ @ @ @ @ @ (++Hd;;;r$     rQ   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floatr7   rT   
ValueErrorfromisoformatreplace)rQ   r   numerics      r"   _coerce_gateway_timestampr   I  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.sessionr  r   s    r"   _auto_continue_freshness_windowr  k  s%     ?>>>>>))+++r$   rt   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.
    NrR   )r1   r2   r3   r   	TypeErrorr   )rt   r   raws      r"   
_float_envr  }  ss     *..

C
{cRiiW~~Szzz"   W~~s   A  A*)A*)nowwindow_secsr  r	  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)r   %_AUTO_CONTINUE_FRESHNESS_SECS_DEFAULTr   time)rQ   r  r	  windowr   currents         r"   _is_fresh_gateway_interruptionr    sv    " " 	k899 
 {{t)%00It [dikkkcGY&((r$   )	reasoningreasoning_contentreasoning_detailscodex_reasoning_itemscodex_message_itemsfinish_reason._ASSISTANT_REPLAY_FIELDSroler   msgc                     | |d}| dk    r6t           D ].}||vr|                    |          }|dk    r|%n|s)|||<   /|S )aW  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.

    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   	assistantr  )r  r3   )r  r   r  entry_rkey_rvals         r"   _build_replay_entryr    s|    " &*g>>E{- 
	! 
	!ECGGENNE+++= !  E%LLLr$   zobserved Telegram group contextz>[Observed Telegram group context - context only, not requests]zh[Current addressed message - answer only this unless it explicitly asks you to use the observed context]channel_promptc                 2    t          | ot          | v           S )a  Return True for Telegram group turns that may include observed chatter.

    Telegram's observe-unmentioned mode persists skipped group chatter so a
    later @mention can see it. Those rows must not replay as ordinary user
    turns: a weak wake word like ``@bot cambio`` should not make the model treat
    old unmentioned chatter as pending work. The Telegram adapter marks these
    turns with a channel prompt; this helper keeps the run-path check explicit
    and unit-testable.
    )r   (_TELEGRAM_OBSERVED_CONTEXT_PROMPT_MARKER)r   s    r"   %_uses_telegram_observed_group_contextr#    s     ]#K~#]^^^r$   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   rB   r3   r   )r   gwmts      r"   _message_timestamps_enabledr*    s     k4(( u		#	#Bb$ u	$	%	%B"d .BFF9e,,---88Or$   r   inject_timestampshistoryr,  c                   ddl m} ddlm}  |            }g }g }t	          |          }| pg D ]}	|	                    d          }
|
s|
dv r |
dk    r'|	                    d          }|r<|
dk    r6t          |t                    r! |||	                    d	          |
          }|rR|	                    d          r=|
dk    r7|r5|                    t          |          	                                           d|	v }d|	v }|
dk    }|s|s|r5d |	
                                D             }|                    |           |rr|
dk    rt          |          }|s2|	                    d          r|	                    dd          }d| d| }t          |
||	          }|                    |           t          |          }t          |          }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   userr   tzobserved
tool_callstool_call_idtoolc                 "    i | ]\  }}|d v	||S )>   r7  r   r   r   kvs      r"   
<dictcomp>z0_build_gateway_agent_history.<locals>.<dictcomp>P  s)    \\\$!QB[9[9[A9[9[9[r$   mirrormirror_sourcezanother sessionz[Delivered from ] r   N)hermes_timer0  gateway.message_timestampsr1  r#  r3   r   r7   r4   rT   items_strip_auto_continue_noiser  _strip_interrupted_tool_tails_strip_dangling_tool_call_tailrA   )r-  r   r,  _get_msg_tz_render_msg_ts_msg_tzagent_historyobserved_group_contextseparate_observed_contextr  r  r   has_tool_callshas_tool_call_idis_tool_message	clean_msg
mirror_srcr  observed_contexts                      r"   _build_gateway_agent_historyrU    s   & 877777      kmmG*,M(* En U U}" -( -(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'gs;;E  ''' 2-@@M 3=AAMyy!788>>@@HD***r$   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   listr   )rV  rW  s     r"   _select_cached_agent_historyrZ  r  sE    " ,%% "#l*;*;cBS>T>T*T*TL!!!r$   rT  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   

c                 Z    g | ](}t          |t                    rt          |          n|)S r   )r   rB   r   parts     r"   
<listcomp>z?_wrap_current_message_with_observed_context.<locals>.<listcomp>  s1    VVVdD$!7!7A4:::TVVVr$   rl   r   rR   )rl   r   )_OBSERVED_GROUP_CONTEXT_HEADER!_CURRENT_ADDRESSED_MESSAGE_HEADERr   r7   rY  rB   r3   rstrip)rz   rT  prefixwrappedr_  s        r"   +_wrap_current_message_with_observed_contextrf    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Nr$   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  >   r3  r2  r   )reversedr   rB   r3   )r-  r  r  tss       r"   _last_transcript_timestamprj    s      t    #t$$ 	wwv 	t999WW[!!>III tt4r$   >   image_generatetext_to_speechtext_to_speech_tool)is_interrupted_tool_resultstrip_interrupted_tool_tailsstrip_dangling_tool_call_tailz [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   r7   
startswith_AUTO_CONTINUE_NOTE_PREFIX_AUTO_CONTINUE_FALLBACK_PREFIX)r   s    r"   _is_auto_continue_noiseru    sI     gs## u566 	><==r$   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.
    ]r   rR   r+   N)ru  r7   findlstrip)r   r   ends      r"   rF  rF    s     #7++ w<<D
!$
'
' (iinn772C!GII%%''	 "$
'
' (
 Kr$   )
host_imageimageagent_visible_imagezMEDIA:((?:[A-Za-z]:[/\\]|/|~\/)\S+\.(?:png|jpe?g|gif|webp|mp4|mov|avi|mkv|webm|ogg|opus|mp3|wav|m4a|flac|epub|pdf|zip|rar|7z|docx?|xlsx?|pptx?|txt|csv|apk|ipa))messageshistory_offsethistory_media_pathsc                    |pt                      }|rt          |           |k    r| |d         }n| }i }|D ]}|                    d          dk    r|                    d          pg D ]}|                    d          p|                    d          }|                    d          pi }t          |                    d          p|                    d          pd	          }	|r|	r|	|t          |          <   g }
d
}|D ]}|                    d          dvrt          |                    d          p|                    d          pd	          }|                    |          t          vrqt          |                    d          pd	          }|                    |          }|dk    rd|vr	 t          j        |          }n# t          $ r d}Y nw xY wt          |t                    r|                    d          rot          D ]g}|                    |          }t          |t                    r;t                              d|           r||vr|
                    d|             nhwd|vr}t                              |          D ]Z}|                    d                                                              d          }|r||vr|
                    d|            [d|v rd}|
|fS )a9  Collect real media tags from current-turn producer-tool results only.

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

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

    Mid-run context compression can rewrite/shrink the message list below the
    original history length. When that happens the slice boundary is no longer
    trustworthy, so fall back to scanning every message and rely on
    ``history_media_paths`` for dedup, preserving the compression-safe behaviour
    of #160. The producer-tool allowlist still applies on the fallback path.
    Nr  r  r8  rk   call_idfunctionrt   rR   F)r:  r  r9  r   rk  MEDIA:successr+   ",}[[audio_as_voice]]T)r5   r   r3   r7   _AUTO_APPEND_MEDIA_TOOL_NAMESjsonloadsr   r   rB   _JSON_MEDIA_TOOL_PATH_FIELDS_TOOL_MEDIA_RE	fullmatchr4   finditerr   rT   rc  )r~  r  r  new_messagestool_name_by_call_idr  callr  fnrt   
media_tagshas_voice_directiver   	tool_namepayloadfieldr;   r   s                     r"   _collect_auto_append_media_tagsr    s^   . .6   #h-->990+- : :776??k))GGL))/R 	: 	:Dhhtnn;(;(;G*%%+Brvvf~~?&)9)9?R@@D :4 :59$S\\2	: J  '  '776??"666cggn--I1C1CIrJJ##G,,4QQQcggi((.B//(,,W55	 (((XW-D-D*W--   '4(( W[[-C-C 9  E";;u--D"4--  . 8 8$ I I $,? ? ?"))/4//:::7""#,,W55 	3 	3E;;q>>''))0077D 3$777!!/4//2227**"&***s   9GGGrL  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  r  r8  rk   r  r  rt   rR   >   r:  r  r   r  r+   r  r9  rk  Nr  )r5   r3   r7   r  r  r   rT   rc  r9   r  r  r   r   rB   r  )rL  pathsr  r  r  cidr  rt   r   r   pr  r  jps                 r"   _collect_history_media_pathsr  Y  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)r1   r2   r3   r;   r:   logging	getLoggerrm   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2r$   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====r$   c                  :    t           dz                                  S )zIReturn True when a /restart completion marker is waiting to be delivered..restart_notify.json)_hermes_homer:   r   r$   r"   _restart_notification_pendingr    s    1199;;;r$   c                      t           dz  S )Nz.restart_pending.json)r  r   r$   r"   "_planned_restart_notification_pathr    s    111r$   c                  B    t                                                      S )zHReturn True when a non-chat planned restart should notify home channels.)r  r:   r   r$   r"   %_planned_restart_notification_pendingr    s    -//66888r$   c                  J    t                                          d           d S )NT
missing_ok)r  unlinkr   r$   r"   #_clear_planned_restart_notificationr    s%    &((//4/@@@@@r$   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.envr+   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_activeNr+   r  r  )	agent.secret_scoper  _bridge_max_turns_from_configr  r  r   r.   r/   parentsr  s    r"   /_reload_runtime_env_preserving_config_authorityr    s     766666  	&l333 NN**,,4Q7&@    ",/////r$   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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)r:   yamlopen	safe_loadhermes_cli.configr  
hermes_clir  apply_managed_overlayr   r3   r   rB   r7   r1   r2   )r  config_path_yamlfcfgr  r  	agent_cfgs           r"   r  r    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
*+++J J'?'?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.r  90Z   )r  r   r1   getenvr  r   r   r$   r"   _current_max_iterationsr  5  sU    3555294d;;<<<z"   rrs   !2 AA)contextmanager>   smsfeishur   r   bluebubbleswecom_callbackr   c                       e Zd ZdZdS )MultiplexConfigErrora   A profile multiplexer config is invalid (fail-fast at startup).

    Distinct from a transient adapter-connect failure: a transient error is
    logged and the gateway stays alive to retry, but a config error means the
    operator must fix config.yaml, so it aborts startup cleanly.
    N)rm   
__module____qualname____doc__r   r$   r"   r  r  S  s           r$   r  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_constantsr  r  r  r  r  r  r7   r   )r   r  r  r  r  r  
home_tokensecret_tokens           r"   _profile_runtime_scoper
  \  s      & VUUUUUUU          *)#l*;*;<<J##$>$>tL?Q?Q$R$RSSL/<((("":..... 	<((("":....s   A+ +Bz=^(?P<host>.+):(?P<container>/[^:]+?)(?::(?P<options>[^:]+))?$z/outputz/outputsr  r  r  r  r  terminalbackendTERMINAL_ENVrR   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  auto.)_is_ssh_remote_tilde_cwd	auxiliary>   visionapprovalweb_extract)get_plugin_auxiliary_taskskeyprovidermodelbase_urlapi_keyrD  
AUXILIARY_	_PROVIDER_MODEL	_BASE_URL_API_KEYr  r  r  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_FRESHNESSr   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 Nr7   r   r  s     r"   	<genexpr>ru  @  s.      5W5WUV5Wc!ff5W5W5W5W5W5Wr$   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_ipv4Tr   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)ChannelOverridePlatform_BUILTIN_PLATFORM_VALUESGatewayConfigHomeChannelPlatformConfigload_gateway_config)SessionStoreSessionSourceSessionContextbuild_session_contextbuild_session_context_promptbuild_session_keyis_shared_multi_user_session)DeliveryRouter#looks_like_telegram_private_chat_id)GatewayAuthorizationMixin)GatewayKanbanWatchersMixin)GatewaySlashCommandsMixin)BasePlatformAdapterEphemeralReplyMessageEventMessageType_reply_anchor_for_eventmerge_pending_message_event)%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'  FextraN	dm_policypairinggroup_policyr  GATEWAY_ALLOW_ALL_USERSrR   >   r   r   r   z&: open policy without allow-all opt-in)
rS   rE  _OWN_POLICY_OPEN_ENVr3   r7   r1   r  rT   r8   rQ   )configr   platform_configopen_envdm_env	group_envallow_all_envr  r  r  gateway_allow_allplatform_opted_ins               r"   "_own_policy_open_startup_violationr    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4r$   c            
      ^   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          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_tokensrP  rO  rM  api_modecommandargscredential_poolrP  rO  rM  r  r  r  r  r  )hermes_cli.runtime_providerr  r  r  hermes_cli.authr  r  r   r   _try_resolve_fallback_providerRuntimeErrorr   r1   r2   r3   r   r   r  r   rB   rY  )r  r  r  r  r  runtimeauth_exc	fb_configr[   	model_cfgr  _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
++;;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	          t          |                    d
          pg           |                    d          dS )zQResolve runtime credentials for a specific provider (e.g. from channel override).r   )r  r  )	requestedNrP  rO  rM  r  r  r  r  )rP  rO  rM  r  r  r  r  )r  r  r  r   r  r3   rY  )rM  r  r  r  r[   s        r"   *_resolve_runtime_agent_kwargs_for_providerr  H  s          H**X>>> H H H88==>>CGH ;;y))KK
++KK
++KK
++;;y))W[[((.B//";;'899  s    
?:?c                 ,   | r!t          |                                           sdS 	 t          t          |                                                                         d          S # t          $ r! t
                              d| d           Y dS w xY w)zJReturn the live credential pool for a provider id (e.g. ``custom:hyper``).Nr  z1Failed to resolve credential pool for provider=%sTr~   )r7   rT   r  r3   r   r   debug)rM  s    r"   _credential_pool_for_providerr  ]  s     3x==..00 t
9#h--:M:M:O:OPPTT
 
 	
    ? 	 	
 	
 	

 tts   A A( ('BBc                  V   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          }|svt          |                    d          p|                    d	          pd
          
                                }|r)t          j        |d
          
                                pd} | |                    d          |                    d          |          }	t                              d|                    d          p|	                    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   )r  Nr  r  r  rP  key_envapi_key_envrR   rM  rO  )r  explicit_base_urlexplicit_api_keyz'Fallback provider resolved: %s model=%srN  r  r  r  r  )rP  rO  rM  r  r  r  r  rN  zFallback entry %s failed: %s)r  r  r  r  r:   r  r  r   r3   r7   rT   r1   r  r   inforY  r   r  )r  _ycfg_path_fr  fb_listr  r  r  r  fb_excs              r"   r  r  n  s   DDDDDD/-/   	4(W--- 	),,r""(bC	) 	) 	) 	) 	) 	) 	) 	) 	) 	) 	) 	) 	) 	) 	)$S)) 	4 #	 #	E"#(99Y#7#7 ' R!		),,N		-0H0HNB egg   R+-9Wb+A+A+G+G+I+I+QT(22#ii
33&+ii
&;&;%5   =IIj))DW[[-D-DIIg&&    '{{955 'J 7 7 'J 7 7 'J 7 7&{{955 V!4!4!:;;'.{{3D'E'E"YYw//	 	 	 	 	    ;UYYz=R=RTZ[[[C#	H    4sj   "J J A!J !A%%J (A%)J ?J G	IJ 
J/J
J JJ 
J&%J&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_typesNrR   )rS   r   )eventr  r  s      r"   _event_media_type_atr    s<     %55;K!&[)9)9!9!9;urAr$   c                     t          | |          }|r|                    d          S t          | dd          t          j        k    S )a  True if the attachment at *index* is an image.

    Trust the per-attachment MIME when present. Only fall back to the
    message-level ``PHOTO`` type when this attachment's MIME is unknown --
    otherwise a document (or any non-image) uploaded alongside an image in
    the same message gets mis-routed as an image, base64'd into a vision
    content part, and the provider 400s ("Could not process image").
    image/message_typeN)r  rr  rS   r  PHOTOr  r  mtypes      r"   _event_media_is_imager    sI     !..E *)))5.$//;3DDDr$   c                     t          | |          }|r|                    d          S t          | dd          t          j        t          j        hv S )zGTrue if the attachment at *index* is audio (per-attachment MIME first).audio/r  N)r  rr  rS   r  VOICEAUDIOr  s      r"   _event_media_is_audior    sO     ..E *)))5.$//K4E{GX3YYYr$   c                     t          | |          }|r|                    d          S t          | dd          t          j        k    S )zGTrue if the attachment at *index* is video (per-attachment MIME first).video/r  N)r  rr  rS   r  VIDEOr  s      r"   _event_media_is_videor
    sG     ..E *)))5.$//;3DDDr$   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: rw  z[User sent audio: z[User sent a video: z[User sent a file: r   )rS   	enumerater  r4   r  r
  rA   )r  partsr  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r$   display_name
agent_pathr   c                 P    |                     d          r	d|  d| dS d|  d| dS )uf  Context note prepended to a user turn when they attach a document.

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

    Binary documents (PDF, DOCX, XLSX, …) cannot be inlined as text. The note
    must tell the agent to *extract* the text itself before answering — earlier
    wording ("Ask the user what they'd like you to do with it") steered the
    model into punting back to the user, which is why attached PDFs/DOCX looked
    "unreadable" to the agent even though it has the tools to read them.
    ztext/z![The user sent a text document: 'zC'. Its content has been included below. The file is also saved at: rw  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.])rr  )r  r  r   s      r"   _build_document_context_noter    si        
8 8 8*48 8 8	
	6| 	6 	6
 	6 	6 	6r$   secondsc                     t          t          |                     }|dk     rd}t          |d          \  }}t          |d          \  }}|r| d|dd|dS | d|dS )Nr   r   <   :02d)r   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""""""r$   r;   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.r+   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   rbr+   )waver  
getnframesgetframerater   )r'  wfframesrater;   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/  r   r  length)r/  r;   s    r"   _ogg_durationz,_probe_audio_duration.<locals>._ogg_duration  s1    333333WWT]]/6777r$   ffprobe-verrorz-show_entrieszformat=durationz-ofz"default=noprint_wrappers=1:nokey=1)stdoutstderrr   r  r   )r1   r;   splitextr8   r   asyncio	to_threadr#  r   create_subprocess_exec
subprocessPIPEwait_forcommunicate
returncodedecoderT   )r;   extr-  r"  r2  procr6  _s   `       r"   _probe_audio_durationrF  	  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   rG  s     r"   _dequeue_pending_eventrJ  3  s     &&{333r$   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.F )rA   r7   rT   splitr8   _CONTROL_INTERRUPT_MESSAGES)rz   
normalizeds     r"   _is_control_interrupt_messagerP  P  sV     u#g,,,,..446677==??J444r$   skill_mdc                 l   	 |                      dd          }n# t          $ r Y dS w xY w|                    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.
    r  r   )r  errorsNNz---z
---   r   Nzname:r  r+      >   "'rL  -rE  z
[^a-z0-9-]rR   z-{2,})	read_textr   rr  rx  
splitlinesrT   rM  r   r8   r   r   r   )rQ  r   rz  declared_nameliner  slug_res           r"   _skill_slug_from_frontmatterra  X  s   &$$gi$HH   zz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.
    rE  rZ  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 `N)r8   r   tools.skills_toolrd  agent.skill_utilsre  rf  r:   rglobra  r  rh  r   r.   r/   r0   relative_torY  r  rA   r   )rb  rO  rd  re  rf  disabled
skills_dirrQ  r_  r]  rh  	repo_rootoptional_dir	_declaredrelr  install_paths                    r"   _check_unavailable_skillru    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)r  c                 4    | t           j        k    rdn| j        S )uN   Map a Platform enum to its config.yaml key (LOCAL→"cli", rest→enum value).cli)r  LOCALrQ   r!   s    r"   _platform_config_keyry    s    ..55HNBr$   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)_load_gateway_configr   r   rY  )r  r'  s     r"   _teams_pipeline_plugin_enabledr    sP    !##FfiB???Ggt$$ uw&E*:g*EEr$   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~~r$   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.
    r  Fr   )get_config_pathread_raw_configTNrr  r  z%Could not load gateway config from %sr  )_normalize_root_model_keys)r  r  r  r  r   r:   r  r  r  r   r  r  r  r  r   rB   r  )
config_homer  r  used_canonicalr  r  r  r  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          | 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   rB   r  r  )r  r  expandeds      r"   _load_gateway_runtime_configr  	  sh     
 
 Cc4    	222222$$H!(D11988r9r$   r  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.
    NrN  r   rR   )r~  r3   r   r7   rB   )r  r  r  s      r"   _resolve_gateway_modelr  2	  s     &&&,@,B,BC$$I)S!! H	It	$	$ H}}Y''G9==+A+AGRG2r$   	thread_id	parent_idr   r  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).
    )r5   r7   r9   r4   )r   r  r  keysrF   rL  sks          r"   _channel_override_lookup_keysr  B	  so     DUUDI.   	XX::BKr$   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  )rS   r3   channel_overridesr  )
r  r   r   r  r  r   r  	overridesrL  ovs
             r"   _get_channel_overrider  Z	  s     T22I tmmH--O /"C t1I,9	     ]]3>III 4r$   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hermesr  z-mzhermes_cli.main)shutilwhichimportlib.utilutil	find_specr-   
executabler   )r  
hermes_bin	importlibs      r"   _resolve_hermes_binr  w	  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  r+   mainrV  rU  r   )r   	chat_typer   >   dmthreadr  N)rM  r   )rG  r  results      r"   _parse_session_keyr  	  s     c""E
5zzQ58w..58v3E3EaqQx
 

 u::>>eAh*:::"'(F;4r$   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.rl   
completion
session_idunknownr  watch_disabledz[IMPORTANT: rz   rR   rw  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)r3   tools.process_registryr  )	r  evt_type_sid_cmd_pat_out_supr   r  s	            r"   $_format_gateway_process_notificationr  	  sL   wwv|,,H77<++D779i((D###7cggi447777=  wwy#&&wwx$$ww|Q'''d ' '#' '' ' !%' ' 	  	PO$OOOOD%%%FFFFFF**3///4r$   
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.
    rl   r  >   r  r  r  )empty
get_nowaitr   r3   r4   put)completion_queuewatch_eventsrequeuer  r  s        r"   _drain_gateway_watch_eventsr  	  s      "LG$$&& 	 	"--//CC 	 	 	E	776<00888$$$$+++NN3 $$&& 	   " "S!!!!s   / 
<<c                      d S rr  r   r   r$   r"   r   r   	  s    D r$   _gateway_runner_refhistory_lenagent_resultresponser  c                   |r|S |                      d          r||                      dd          }t          |                                          t          fddD                       p	dv o|dk    }|r	 dS d	t          |          d
d          dS t	          |                      dd          pd          }|dk    r^|                      d          sI|                      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)
    failedr5  unknown errorc              3       K   | ]}|v V  	d S rr  r   )r   r  	error_strs     r"   ru  z2_normalize_empty_agent_response.<locals>.<genexpr>
  s;       !
 !
 N!
 !
 !
 !
 !
 !
r$   )rw   tokenz	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   interruptedpartialzprocessing incompleteu   ⚠️ Processing stopped:    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.)r3   r7   r8   anyr   )r  r  r  error_detailis_context_failurer  errr  s          @r"   _normalize_empty_agent_responser  	  s   $  !! 
#''AA%%++--	  !
 !
 !
 !
W!
 !
 !
 
 
 7 y 5[2%5 	  	) @3|#4#4TcT#: @ @ @	

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

 Or$   c                    t          | t                    sdS |                     d          rdS |                     d          s*|                     d          s|                     d          rdS |                     d          du rdS dS )a  Return True only when a gateway turn really completed successfully.

    Restart recovery uses ``resume_pending`` as a durable marker for sessions
    interrupted during gateway drain.  A soft interrupt can still bubble out as
    a syntactically normal agent result with an empty final response; clearing
    the marker in that case loses the recovery signal and startup auto-resume
    has nothing to schedule.
    Fr  r  r  r5  	completedTr   )r  s    r"   '_should_clear_resume_pending_after_turnr  3
  s     lD)) u&& u!! \%5%5i%@%@ LDTDTU\D]D] u$$--u4r$   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   rB   r3   r   )r  r  current_offsetfollowup_offsetrY   s        r"   (_preserve_queued_followup_history_offsetr  G
  s     ot,, nd++ #''(899N%))*:;;Onc** /3'' O~,M,M/""F-FMr$   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 %rrt   Tr~   )
disconnectr   r   r  rS   rl   rm   r   s    r"   _dispose_unused_adapterr  g
  s      : 
  """"""""""" 
 
 
 	:GVT']]%;<< 	 	
 	
 	
 	
 	
 	

s   $ AA0/A0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<   i Zeeeeef         f         ed<   i Zeeeee f         f         ed<   d	Z!eed<   ddee"         fdZ#ddZ$ddZ%defdZ&e'dz  Z(de)dedefd Z*deeef         fd!Z+dd"Z,ded#eddfd$Z-ded%eddfd&Z.dd'Z/dd(Z0dd)d*ee         ddfd+Z1defd,Z2defd-Z3d	d.d/edefd0Z4e5defd1            Z6e5defd2            Z7e5dee         fd3            Z8e5dee         fd4            Z9d5edefd6Z:d5edefd7Z; e<d8d9h          Z=d5edefd:Z>d5edefd;Z?d<Z@d5edefd=ZAdefd>ZBdefd?ZCd5edee         fd@ZDd5eddfdAZEd5edBeddfdCZFd5edee         fdDZGd5edefdEZHddddFd5ee         dGee         dHeeI         deJeeIf         fdIZKdJedKedLeIdeIfdMZLdNedOe ddfdPZMdQeNddfdRZOdBeddfdSZPdefdTZQdefdUZRdefdVZSdeJfdWZTdefdXZUddYZVdefdZZWdd[ZXd\ ZYdd]eddfd^ZZdefd_Z[defd`Z\defdaZ]dGedbdcdQe ddfddZ^dGedQe deedc         dedc         fdfZ_ddgdGedQe defdhZ`eadie defdj            ZbdGedQe defdkZcdNedefdlZdddmee         dnee         ddfdoZeddpZfddqZgddrZhdd]eddfdtZiddddudedvee         dwee         dxee         ddf
dyZjd8dzdBeddfd{Zkdefd|Zleademeee f                  fd}            Zneadefd~            Zoddddde)dedHeeI         dee         dee         defdZpdddde)dedee         dee         def
dZqeadeIdz  fd            ZreadedeJeef         fd            Zsdddd5ee         dGee         deIdz  fdZtdGedeeI         ddfdZueadedz  fd            Zveadefd            Zweadefd            Zxeadefd            Zyeadefd            Zzeadefd            Z{eadeIfd            Z|eade}dz  fd            Z~deee f         fdZdee         fdZdGedee         fdZdGed5edeJe ee         f         fdZeade defd            ZdGedefdZdZdGededdfdZdedGedefdZdedeJeee f         ef         fdZdBeddfdZddZdeee f         ddfdZdGee         dOe dee          defdZd<Zd8ddOe deddfdZdOe ddfdZdZdZdeddfdZdefdZdGeddfdZddZddZd	d	ddededefdZ e<h d          ZdQeNdedGeddfdZdeddfdZdefdZddZddefdZdefdZ	 	 ddQeeN         dee)         defdZdefdZdd]eddfdZdeee f         ddfdÄZdd]efdń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eJef         defdӄZdefdԄZeadQe dee         fdՄ            Zde)de deeN         fdքZde)deeee         ee         gef         fdׄZdeddfdلZdedee         fdڄZddcdeddfd܄Zddݜded5edemeee f                  dGee         dee         f
d߄ZdGedeme         fdZdGeddfdZdGefdZdedefdZdefdZd5ededee         fdZd5edede}fdZdedefdZdedefdZdefdZdefdZddZd5e deddfdZd5e deddfdZde d5e deddfdZeadedee         fd            ZdedefdZdedefdZdeddfdZdedededefdZdededefdZ	 ddeded e}dedef
dZdefdZdededdfdZdededdfdZ	 	 	 dded5dd	ed
ee         deeme                  deeme                  ddfdZd5edeIfdZd5eddfdZd5eddfdZѐdedefdZd5edNededdfdZd5edefdZd5edNededdfdZՐdZd5edefdZdefdZd5edefdZd5edefdZdededefdZdedefdZdededededeed df         f
d!Zdededededee         f
d"Zdeee f         fd#Z	 dd$ee         deeee f                  fd%Zdddd&dee)         dee         dee         d'ee         d$ee         dQee          deeee f                  fd(Zeaddd)dee)         dee         dee         d'ee         dQee          defd*            Zeadedee         fd+            ZdZ e<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        e)j        h          Zdd,Z	 	 	 dd/ed0ededdfd1Zdefd2ZdeeJeeee         f                  fd3Zdd4d5eeeJeeee         f                           deeJeeee         f                  fd6Zdede}fd7Zd8e}ddfd9Zd: Zdej         j        fd;Zdd<Zdddddd=d5ee         dGee         dHeeI         d>ee         dKee         defd?Zd@edAeme         defdBZd@edCeme         deJeeme         f         fdDZdGededz  fdEZdFeIfdGZdHedFeIddfdIZ	dFeIddfdJZ
dd]eddfdKZdLeIddfdMZdZdNZeJedO<   dPZi ZeIeJeedz  f         eIee f         f         edQ<   edeIee f         fdR            ZedeIee f         fdS            ZedHeIdz  deIfdT            Zea	 	 	 ddKedUeIdVe}dWedXeIdz  dedz  dYedz  defdZ            ZdGeddfd[ZdGedKedLeIdeJfd\ZdGed]edefd^Zdd_dGedee         defd`ZdGeddfdaZdGedefdbZd8dzdGedBedefdcZdGeddedefdeZdQe dGeddedz  ddfdfZdgdhdGed5ediedjedkeddfdlZdGedNee         ddfdmZ dGeddfdnZ!eadOe doeddfdp            Z"dOe dqeddfdrZ#dOe dqeddfdsZ$dOe ddfdtZ%dduZ&defdvZ'dee         fdwZ(	 	 	 ddedxedemeee f                  d5ddNedGedee         d
ee         deee f         fdyZ)	 	 	 	 	 	 	 	 ddedxedemeee f                  d5edNedGedee         d{ed
ee         d|ee         d}eeI         d~ee         dee         deee f         fdZ*d5eddfdZ+	 	 	 	 	 	 	 	 ddedxedemeee f                  d5edNedGedee         d{ed
ee         d|ee         d}eeI         d~ee         dee         deee f         fdZ,d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_session_model_overrides_session_reasoning_overrides_startup_restore_in_progressr  c                    |p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                  | _*        d| _+        d | _,        t[          j.                    | _/        d| _0        d| _1        d | _2        d | _3        d| _4        d| _5        d| _6        d| _7        d| _8        d| _9        d| _:        d| _;        d | _<        t{          j=                    | _>        d| _?        d | _@        d | _A        t          jC                    | _D        d | _E        d| _F        i | _G        i | _H        i | _I        i | _J        i | _K        i | _L        i | _M        i | _N        i | _O        d| _P        g | _Q        g | _R        t                      | _T        d| _U        dd lB}t                      | _V        |C                                | _W        i | _X        i | _Y        | Z                                | _[        d | _\        d | _]        i | _^        i | __        i | _`        dd la}|b                    d          | _c        	 ddldme}  |d           n# t          $ r Y nw xY w	 ddlfmg}  |            }t          t          |ddd          pd          j                                k                                }	t	          t          |ddd                    }
t          |ddd           }|	dk    r|
s|st          l                    d           n,# t          $ r t                              dd           Y nw xY wd | _m        	 ddlnmo}mp}  | |                      | _m        n2# t          $ r%}t          l                    d|           Y d }~nd }~ww xY w| jm        	 ddlfmg}  |            q                    d          pi }|q                    d d          r| jm        jr        s                    t          |q                    d!d"                    t          |q                    d#d
                    t	          |q                    d$d                    | j        j'        %           n2# t          $ r%}t                              d&|           Y d }~nd }~ww xY w	 ddlfmg}  |            q                    d'          pi }|q                    d d          rdd(lumv}  |t          |q                    d!d)                    t          |q                    d#d
                    t	          |q                    d*d                    t          |q                    d+d,                    -           n2# t          $ r%}t                              d.|           Y d }~nd }~ww xY wdd/lwmx}  |            | _y        dd0lzm{}  |            | _|        | }                                | _~        i | _        t                      | _        t{          j=                    | _        d1| _        d S )2Nr   )set_multiplex_activemultiplex_profilesFz#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)rL  _bg_max_age_secondsr  s    r"   r   z(GatewayRunner.__init__.<locals>.<lambda>
  s$    0@0W0W$7 1X 1 1 r$   )has_active_processes_fn   r+   )ensure_installed)log_failuresload_config	approvalsmodemanualr|  rj  tirith_enabledrG  rI  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: %ssessions
auto_pruneretention_daysr  min_interval_hoursvacuum_after_prune)r"  r#  vacuumsessions_dirz%state.db auto-maintenance skipped: %scheckpoints)maybe_auto_prune_checkpoints   delete_orphansmax_total_size_mb  )r"  r#  r*  r+  z'checkpoint auto-maintenance skipped: %s)PairingStore)HookRegistry        )r  r  r  r
  r   rS   r   r   r  adapters_profile_adapters'_warn_if_docker_media_delivery_is_risky_weakrefrefr  _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  delivery_router_running_gateway_loopr:  Event_shutdown_event_exit_cleanly_exit_with_failure_exit_reasonr  r  r  r  _signal_initiated_shutdownr  r   r  r  r  r  _startup_time_booted_from_restartr  r  	threadingLock_executor_lock	_executor_executor_closing_running_agentsr  _active_session_leases_pending_messages_last_resolved_model_queued_events&_pending_native_image_paths_by_session_busy_ack_ts_session_run_generationr  _startup_restore_queue_startup_restore_tasksr   _session_sources_session_sources_max_agent_cache_agent_cache_lockr  r  _active_profile_name_kanban_notifier_profile_teams_pipeline_runtime_teams_pipeline_runtime_error_pending_approvals_failed_platforms_update_prompt_pending	itertoolsr   _slash_confirm_countertools.tirith_securityr  r  r  r7   r   rT   r8   r   _session_dbhermes_stater  r  r3   _dbmaybe_auto_prune_and_vacuumr   tools.checkpoint_managerr(  gateway.pairingr-  pairing_storegateway.hooksr.  hooks_load_voice_modes_voice_mode_recent_voice_transcriptsr5   _background_tasks_last_inbound_at_scale_to_zero_cooldown_until)selfr  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	   5 3 5 5
	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% % % % %
 
 
  .dk::BF&}""'+/)- ',#"' +0'%*"!&$)!05-@D$ %)IKK +0!2659'n..JN "' 024668#13 57! >@LN3.079$
 -2):<#:<# DO==$'! 	'&&&7B}}!+!2!2 DF% HJ)(,(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)\^^ 	/.....!\^^
 ,0+A+A+C+C Z\& '*ee (,y{{ 58***s   2A &A54A56P	 	
PPB-S &S10S1< T 
U'UUCX# #
Y-YYC\+ +
]5]]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)r  MSGRAPH_WEBHOOKr0  r  r   r  plugins.teams_pipeline.runtimer  r   r   r  ri  )r  r  r[   bounds       r"   _wire_teams_pipeline_runtimez*GatewayRunner._wire_teams_pipeline_runtime  sS    #4=88F-// 	LLUVVVF	KKKKKKK 	 	 	NNEsKKKFFFFF		((..EE 	 	 	NNEsKKKFFFFF	  	KKQRRRRR/ 	NN82    	 	s0   A 
A8A33A8<B 
B8B33B8c                    t          j        dd                                                                          dk    rdS | j                                        }d |D             }|sdS t          j        dd                                          }g }|rc	 t          j        |          }t          |t                    rd |D             }n,# t          $ r t                              dd	
           Y nw xY wd}|D ]A}t                              |          }|s|                    d          }	|	t           v rd	} nB|rdS t                              d           dS )a  Warn when Docker-backed gateways lack an explicit export mount.

        MEDIA delivery happens in the gateway process, so paths emitted by the model
        must be readable from the host. A plain container-local path like
        `/workspace/report.txt` or `/output/report.txt` often exists only inside
        Docker, so users commonly need a dedicated export mount such as
        `host-dir:/output`.
        r  rR   dockerNc                 \    g | ])}|t           j        t           j        t           j        hv'|*S r   )r  rx  
API_SERVERWEBHOOKrt  s     r"   r`  zIGatewayRunner._warn_if_docker_media_delivery_is_risky.<locals>.<listcomp>  s3    xxxQqQYQdfnfv@w7w7wq7w7w7wr$   r/  c                 V    g | ]&}t          |t                    t          |          'S r   )r   r7   r   r>  s     r"   r`  zIGatewayRunner._warn_if_docker_media_delivery_is_risky.<locals>.<listcomp>)  s-    LLL!As9K9KLs1vvLLLr$   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/...'.)r1   r  rT   r8   r  get_connected_platformsr  r  r   rY  r   r   r  _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"   r2  z5GatewayRunner._warn_if_docker_media_delivery_is_risky  s    9^R((..006688HDDFK7799	xx)xxx" 	Fi 92>>DDFF 	qqK00fd++ MLLvLLLG q q q`kopppppq %*! 	 	D*0066E "[[55N!EEE,0) F % 	FP	
 	
 	
 	
 	
s   5C &C43C4c                 L    	 ddl m}  |d          duS # t          $ r Y dS w xY w)z3Check if the hermes-agent-setup skill is installed.r   )_find_skillzhermes-agent-setupNF)tools.skill_manager_toolr  r   )r  r  s     r"   _has_setup_skillzGatewayRunner._has_setup_skillE  sQ    	<<<<<<;344D@@ 	 	 	55	s    
##zgateway_voice_mode.jsonr   r   c                     |j          d| S )z6Return a platform-namespaced key for voice mode state.r  rQ   )r  r   r   s      r"   
_voice_keyzGatewayRunner._voice_keyQ  s    .,,7,,,r$   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JSONDecodeErrorr6   r   rB   rE  r7   r   r   )r  datavalid_modesr  r   r  rL  s          r"   ry  zGatewayRunner._load_voice_modesU  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r  exist_okrV  indentzFailed to save voice modes: %s)
r  r0   mkdir
write_textr  dumpsrz  r6   r   r   )r  r  s     r"   _save_voice_modeszGatewayRunner._save_voice_modeso  s    	@!(..td.KKK!,,
4+A666      	@ 	@ 	@NN;Q?????????	@s   AA 
B"BBrn  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rS   r   r5   r9   discard)r  r   r   rn  disabled_chatsenabled_chatss         r"   _set_adapter_auto_tts_disabledz,GatewayRunner._set_adapter_auto_tts_disabledx  s     *DdKK.#.. 	F 	,w'''#G-FMMM--- /%%g...../ / ""7+++++r$   r'  c                 ,   t          |dd          }t          |t                    sdS |rT|                    |           t          |dd          }t          |t                    r|                    |           dS dS |                    |           dS )zUpdate an adapter's per-chat auto-TTS opt-in set if present.

        Used for ``/voice on``/``/voice tts`` where the user explicitly wants
        auto-TTS even when ``voice.auto_tts`` is False globally.
        r  Nr  r  )r  r   r   r'  r  r  s         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 !!'*****r$   c                 v   t          |dd          }t          |t                    sdS t          |dd          }t          |dd          }t          |t                    st          |t                    sdS 	 ddlm}  |            }t          |                    d          pi                     dd	                    }n# t          $ r d	}Y nw xY wt          |d
          r||_
        |j         dt          |t                    rL|                                 |                    fd| j                                        D                        t          |t                    rN|                                 |                    fd| j                                        D                        dS dS )ae  Restore persisted /voice state into a live platform adapter.

        Populates three fields from config + ``self._voice_mode``:
          - ``_auto_tts_default``: global default from ``voice.auto_tts``
          - ``_auto_tts_enabled_chats``: chats with mode ``voice_only``/``all``
          - ``_auto_tts_disabled_chats``: chats with mode ``off``
        r   Nr  r  r   r  voiceauto_ttsF_auto_tts_defaultr  c              3      K   | ]9\  }}|d k    |                                |t                    d         V  :dS )r  Nrr  r   r   rL  r  rd  s      r"   ru  zBGatewayRunner._sync_voice_mode_state_to_adapter.<locals>.<genexpr>  sX       " "&/c45==S^^F%;%;= CKKLL! ===" "r$   c              3   ~   K   | ]7\  }}|d v 	|                               |t                    d         V  8dS )>   r  r  Nr  r  s      r"   ru  zBGatewayRunner._sync_voice_mode_state_to_adapter.<locals>.<genexpr>  s_       ! !&/c4000S^^F5K5K0 CKKLL!0000! !r$   )rS   r   r  r5   r  r  r   r3   r   r   r  rQ   clearupdaterz  rE  )	r  r   r   r  r  r  	_full_cfgr  rd  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c                   K   |                                  }	 |dk    r|                                 d{V  dS t          j        |                                |           d{V  dS # t          j        $ r) t
                              d|||j        nd           Y 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.
        r   Nr8  zITimed out after %.1fs while disconnecting %s adapter; continuing shutdownr   z7Defensive %s disconnect after failed connect raised: %s)
 _adapter_disconnect_timeout_secsr  r:  r?  TimeoutErrorr   r   rQ   r   r  )r  r   r   r  r  s        r"   _safe_adapter_disconnectz&GatewayRunner._safe_adapter_disconnect  sB      7799	!||((***********&w'9'9';';WMMMMMMMMMMMM# 	 	 	NN["*"6I     
  	 	 	LLI"*"6I        	s"    A* .A* *4C!	C*%CCprofiler  c                  K   |                                  }|rd| dnd}t          j                    }	 |dk    r|                                 d{V  n.t	          j        |                                |           d{V  nk# t          j        $ r% t                              d|j	        ||           Y n8t          $ r,}t                              d|j	        ||           Y d}~nd}~ww xY w	 |dk    r|                                 d{V  n.t	          j        |                                |           d{V  t                              d	|j	        t          j                    |z
  |           dS # t          j        $ r& t                              d
|j	        ||           Y 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 is wrapped in the existing per-adapter timeout budget
        (``HERMES_GATEWAY_ADAPTER_DISCONNECT_TIMEOUT``). On timeout we log
        and force forward progress; the loop never hangs regardless of any
        adapter's internal behavior. Never raises.
        z (profile: )rR   r   Nr8  uH   ✗ %s background-task cancel timed out after %.1fs - forcing continue%su)   ✗ %s background-task cancel error%s: %su   ✓ %s disconnected (%.2fs)%su<   ✗ %s disconnect timed out after %.1fs - forcing continue%su)   ✗ %s disconnect error after %.2fs%s: %s)r  r  	monotoniccancel_background_tasksr:  r?  r  r   r   rQ   r   r  r  r  r5  )r  r   r   r  r  suffix
started_atr  s           r"   _bounded_adapter_teardownz'GatewayRunner._bounded_adapter_teardown  s     " 7799-4<)w))))"^%%
	a!||557777777777&3355w          # 	 	 	NNZ      	a 	a 	aLLDhnV\^_````````	a	!||((**********&w'9'9';';WMMMMMMMMMMKK/ 0 0: =v     # 	 	 	NNN       	 	 	LL; 0 0: =vq        	s=   AB 1C-8	C-"C((C-1BE8 81G7,	G757G22G7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_TIMEOUTrR   r/  z=Ignoring invalid HERMES_GATEWAY_ADAPTER_DISCONNECT_TIMEOUT=%r)	r1   r  rT   r   maxr   r   r   (_ADAPTER_DISCONNECT_TIMEOUT_SECS_DEFAULTr  r  r  s      r"   r  z.GatewayRunner._adapter_disconnect_timeout_secs  s    iCRHHNNPP 		))** 3(((    S     87   A
 
%A21A2c                     t          j        dd                                          }|rK	 t          |          }t	          d|          S # t
          $ r t                              d|           Y nw xY wt          S )zBReturn the per-platform connect timeout used during startup/retry.r|  rR   r/  z;Ignoring invalid HERMES_GATEWAY_PLATFORM_CONNECT_TIMEOUT=%r)	r1   r  rT   r   r  r   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  Nr8  z connect timed out after gs)r  connectr:  r?  r  rQ   )r  r   r   r  r  r[   s         r"   _connect_adapter_with_timeoutz+GatewayRunner._connect_adapter_with_timeout6  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                     | j         S rr  )rM  r  s    r"   should_exit_cleanlyz!GatewayRunner.should_exit_cleanlyM  s    !!r$   c                     | j         S rr  )rN  r  s    r"   should_exit_with_failurez&GatewayRunner.should_exit_with_failureQ  s    &&r$   c                     | j         S rr  )rO  r  s    r"   exit_reasonzGatewayRunner.exit_reasonU  s      r$   c                     | j         S rr  )r  r  s    r"   	exit_codezGatewayRunner.exit_codeY  s
    r$   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.rG  Nr  r  Fr   get_active_profile_namer   group_sessions_per_userTthread_sessions_per_user)r  r  r  )r   rG  _generate_session_keyr   r7   r   rS   r  hermes_cli.profilesr  r  )r  r  rG  r  _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  Frp  Nrr  r   user_idz(Failed to read Telegram topic mode stateTr~   )r   r  TELEGRAMr  rS   is_telegram_topic_mode_enabledr7   r   r  r   r   r  )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rR   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  FrR   r   r  r  r  r
  r7   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6r$   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  FrR   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tr$   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_tsrR   Tr   Nr/  F)r   r  r7   r   r  r  r3   #_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tr$   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_message  s    *	
 	
r$   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_message  s    W	
 	
r$   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	
 	
r$   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.rp  Nrr  rR   )r   r  r  rG  r  )rS   r   r  bind_telegram_topicr7   r  rG  r  )r  r  session_entryr	  s       r"   _record_telegram_topic_bindingz,GatewayRunner._record_telegram_topic_binding  s     T=$77
V^6;KFZ
;;
&&''&*++,"--%1$/ 	' 	
 	
 	
 	
 	
r$   reasonc                    |                      |          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#  r   r   r  )r  r  r"  r$  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  NrR   rp  rr  r   ztopic-recover: read failedTr~   r  r  )r   r  r  r  r   r  r
  r7   r  r  rS   %list_telegram_topic_bindings_for_chatr   r   r  r3   )	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/  r   dataclassesr   )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  rG  r   rG  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).
        NrN  rM  rP  rO  r  r  r  )rM  rP  rO  r  r  r  zZSession model override (fast): session=%s config_model=%s -> override_model=%s provider=%srR   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 -> %sr  r  parent_chat_idr  r   )get_default_model_for_provideru8   No model configured — defaulting to %s for provider %sr[  *u{   Empty model resolved for session=%s — recovering last-known-good model %s (config read likely returned empty; see #35314))r  r   r  !_rehydrate_session_model_overrider  r3   r  r   r  rY  r  r  r  r  rS   r   r7   r  r6  r  r   rN  rM  r  _apply_session_model_overridehermes_cli.modelsr7  r   )r  r  rG  r   resolved_session_keyrN  r  override_modeloverride_runtimeruntime_kwargsruntime_modelr  r   r  r  chch_runtime_modelr7  
_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_messagerN  r?  c                 p   ddl m} |                    d          |                    d          |                    d          |                    d          |                    d          t          |                    d          pg           |                    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_overridesrP  rO  rM  r  r  r  r  r  r  )rN  r  	signaturer<  Nrequest_overridesrN  )r;  rH  r3   rY  tuplerS   r   )	r  rF  rN  r?  rH  r  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&**:66%)))44++F339r::-112CDD(,,\::	
 	
 
#
#
#	"gfo&&
 
 t_d;; 	)+E%&L	33E'NCCII 	 	 	III	%._"!"s   D D,+D,r  r  c           
        
 |r	|| j         dS t          |dd          }|sdS t          |dd          t          |dd          t          |dd          t          t          |dd                    d}d	 |                                D             }	 | j         j        }|                    |          }|sdS |                    d          }|                    d
          }	 |rt          j        |          ni }	n# t          $ r i }	Y nw xY wt          |	t                    si }	t          |	                    d          pi           
||k    r/t          
fd|                                D                       rdS ||	d<   |                    |t          j        |	          |           dS # t          $ r  t                              dd           Y dS w xY w)uf  Persist the runtime model/provider actually used by a gateway turn.

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

        Called from the ``run_sync`` closure, which executes off the event loop
        in the executor thread — so the synchronous ``SessionDB`` (``_db``) is
        used directly rather than awaiting the AsyncSessionDB forwarder.
        NrN  rM  rO  r  _fallback_activatedF)rM  rO  r  fallback_activec                 "    i | ]\  }}|d v	||S ))NrR   r   r<  s      r"   r?  z@GatewayRunner._sync_session_model_from_agent.<locals>.<dictcomp>3  s(    KKKDAqq
7J7J1a7J7J7Jr$   model_configgateway_runtimec              3   P   K   | ] \  }}                     |          |k    V  !d S rr  r3   )r   r=  r>  rT  s      r"   ru  z?GatewayRunner._sync_session_model_from_agent.<locals>.<genexpr>C  sK       . .041##A&&!+. . . . . .r$   )rN  z-Failed to sync gateway session model metadataTr~   )rp  rS   r   rE  rr  get_sessionr3   r  r  r   r   rB   r  update_session_metar  r   r  )r  r  r  rN  r  dbrowcurrent_model
raw_configr  rT  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r   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 rK| j                             |j        d           | 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 )zReact 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.
        NzDIgnoring stale fatal error from a superseded %s adapter instance: %sr  zFatal %s adapter error (%s): %sr  relay_disabledrn  retryingfatalplatform_state
error_codeerror_messager   r  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.)r0  r3   r   r   r  rQ   fatal_error_coder5  fatal_error_messagefatal_error_retryable_update_platform_runtime_statusr  rH  r  r  r   rk  r  r  r  rO  rN  stopr   r   )r  r   existingrc  r  s        r"   _handle_adapter_fatal_errorz)GatewayRunner._handle_adapter_fatal_errorL  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 )$$&&&&&&&&& ( 	"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*++	    	 	 	 	r$   c                 T    d| _         || _        | j                                         d S NT)rM  rO  rL  r5   )r  r$  s     r"   _request_clean_exitz!GatewayRunner._request_clean_exit  s-    !"  """""r$   c                 *    t          | j                  S rr  )r   rX  r  s    r"   _running_agent_countz"GatewayRunner._running_agent_count  s    4'(((r$   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 rr  )done)r   r   s     r"   ru  zHGatewayRunner._scale_to_zero_has_live_background_work.<locals>.<genexpr>  s,      <<61688|<<<<<<r$   Tr   )active_countz+scale-to-zero async-delegation check failedr~   r  z"scale-to-zero bg-work check failedF)r  r|  tools.async_delegationrx  r   r   r  r  r  has_any_activepending_watchers)r  rx  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_zeror~  r~  r   rB   r3   r   )r  r~  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   rB   r3   r   r   )r  _rlgr  r  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rS   r   r  pcs      r"   r`  z;GatewayRunner._scale_to_zero_should_arm.<locals>.<listcomp>  s.    ___uq"YX]A^A^____r$   N)r'  relay_only_or_absentwake_url)
gateway.relayr  r  r  r  r  r  r   rE  r   )r  r  r  r  r  r   r  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   r  )r  r  Nc                 X    g | ]'\  }}t          |d d          t          |d|          (S )r'  FrQ   r  r  s      r"   r`  zEGatewayRunner._log_scale_to_zero_not_armed_reason.<locals>.<listcomp>3  sJ       !Ar"2y%887A..  r$   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.noner5   MISSINGz.scale-to-zero: not-armed reason logging failedTr~   )r  r  r  r  r  r  r   rE  r   r   r  r  )r  r  r  r  r'  active
relay_onlyr  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)r  r  rt  r  r}  r  r|  )r  r  s     r"   _scale_to_zero_is_idlez$GatewayRunner._scale_to_zero_is_idleM  sk    111111w $ 9 9 ; ;'+y{{T5J'J!%!I!I!K!K%)%Q%Q%S%S	
 
 
 	
r$   c                     t          j                     | _        t          | dd          dk    rL	 |                     d           n,# t          $ r t
                              dd           Y nw xY wd| _        dS dS )	a  Stamp real inbound and restore lifecycle after a dormant wake.

        The watcher marks runtime status `draining` as it quiesces the relay, but
        dormancy is not the stop/restart drain path: the process remains alive and
        should present as running once real traffic wakes it and re-enters the
        gateway. Internal completion/replay events intentionally do not call this
        helper, so they do not keep an otherwise idle gateway awake.
        r~  r/  r   runningz$scale-to-zero: status restore failedTr~   N)r  r}  rS   _update_runtime_statusr   r   r  r~  r  s    r"    _scale_to_zero_note_real_inboundz.GatewayRunner._scale_to_zero_note_real_inboundW  s     !%	48#>>BBT++I6666 T T TCdSSSSST14D... CBs   A &A.-A.c                 r    	 ddl m} n# t          $ r Y dS w xY w| j                            |j                  S )zHReturn the connected RELAY adapter, if any (the one go_dormant targets).r   r  N)gateway.platforms.baser  r   r0  r3   RELAY)r  r  s     r"   _relay_adapter_for_dormancyz)GatewayRunner._relay_adapter_for_dormancyh  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:  sleepminrI  r  r~  r  r  rS   r   r   r  r  r  r   r  iscoroutiner  CancelledError)r  r  r   r  r  s        r"   _scale_to_zero_watcherz$GatewayRunner._scale_to_zero_watcherp  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Cr$   c                     | j         rdndS )N
restartingshutting downr  r  s    r"   _status_action_gerundz#GatewayRunner._status_action_gerund  s    #6K||OKr$   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Vr$   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.NrZ  r\  )rS   r\  
setdefaultr4   )r  rG  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%%%r$   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.
        r\  Nr   rZ  )rS   r3   r  r   rZ  r  r<   )r  rG  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r$   r  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.r\  NrZ  r+   )rS   r   r3   )r  rG  r   r  rq   s        r"   _queue_depthzGatewayRunner._queue_depth  sb    &6==CM%%k26677;''CVXZ2[2[#[#[QJEr$   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   rR   z,[Continuing toward your standing goal]
Goal:)rS   r7   rr  )r  r   s     r"   _is_goal_continuation_eventz)GatewayRunner._is_goal_continuation_event  s5     }fm<<B4yy##$STTTr$   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   NrZ  r+   r\  )rS   r   rB   r3   r  r  r4   )
r  rG  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r$   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r  z2goal continuation: active-state recheck failed: %sN)hermes_cli.goalsr  	is_activer   r   r  )r  r  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  rt  r   )r  r  r  r  s       r"   r  z$GatewayRunner._update_runtime_status0  s|    		;;;;;;  +'"&"9"7799	       	 	 	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  rt  r   )r  r  s     r"   _persist_active_agentsz$GatewayRunner._persist_active_agents<  sa     	;;;;;;  t/H/H/J/JKKKKKK 	 	 	DD	s   $( 
66c                     | j         rdS d| _         t                              d|                                            |                     d           dS )u)  Begin external drain: stop accepting new turns, flip state.

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

        Idempotent. Only reverts to ``running`` when we are actually mid-drain
        AND not also shutting down (a real shutdown ``_draining`` must win —
        never resurrect a stopping gateway to ``running``).
        NFug   External drain marker cleared during shutdown — not reverting to running (shutdown takes precedence).uk   External drain RELEASED (.drain_request.json removed) — re-accepting new turns; gateway_state -> running.r  )r  r  rI  r   r  r  r  s    r"   _exit_external_drainz"GatewayRunner._exit_external_drainp  s     * 	F&+#> 	 	 KK:   F@	
 	
 	
 	##I.....r$         ?c                 Z  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  rI  r  r  r:  r  r   r   r  r  )r  r  r  r[   s       r"   _drain_control_watcherz$GatewayRunner._drain_control_watcher  s      	:99999m 
	*Y"?$$ 0..0000--///)    Y Y YCSSWXXXXXXXXY-))))))))) m 
	* 
	* 
	* 
	* 
	*s   3A BB  Brb  rc  rd  re  c                T    	 ddl m}  |||||           d S # t          $ r Y d S w xY w)Nr   r  )r   rc  rd  re  )r  r  r   )r  r   rc  rd  re  r  s         r"   rl  z-GatewayRunner._update_platform_runtime_status  sm    		;;;;;;  !-%+	       	 	 	DD	s    
''r$  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.
        rk  NpausedTz#auto-paused after repeated failurespause_reasoninfrh  rb  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.rg  r   )rS   r3   r   rl  rQ   r   r   r   )r  r   r$  r  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).
        rk  NFr  r  r   rg  rh  r`  rb  u,   %s resumed — retrying on next watcher tickT)
rS   r3   r  r  r  rl  rQ   r   r   r  )r  r   r  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_FILErR   prefill_messages_filer  r|  z#Prefill messages file not found: %sr  r  r  Nz3Prefill messages file must contain a JSON array: %sz+Failed to load prefill messages from %s: %s)r1   r  r  r7   r3   r   r   
expanduseris_absoluter  r:   r   r   r  r  loadr   rY  r   )	file_pathr  r;   r  r  r  s         r"   r5  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_PROMPTrR   r  system_promptr|  )r1   r  r  r7   r   rT   )promptr  s     r"   r7  z+GatewayRunner._load_ephemeral_system_prompt  s^     ;R@@ 	M*,,73"EEEKLLRRTTTr$   )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.r  Nr  )rS   r  rN  r  )r  r   r   r   r  r  r  r  s           r"   _resolve_model_for_channelz(GatewayRunner._resolve_model_for_channel+  si     x.. 		&,##  H  &HN &~%%k222r$   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.
        r  Nr  rR   r8  )rS   r  r	  rT   )r  r   r   r  r  r  r  s          r"   _get_system_prompt_for_channelz,GatewayRunner._get_system_prompt_for_channelB  s     x.. 		>,##  H  >H2 > .4";;===t7>>D"Dr$   c                      ddl m}  t                      }t          |ddd          } | |          }|r>t	          |                                          r|t                              d|           |S )	zLoad reasoning effort from config.yaml.

        Reads agent.reasoning_effort from config.yaml. Valid: "none",
        "minimal", "low", "medium", "high", "xhigh". Returns None to use
        default (medium).
        r   )parse_reasoning_effortr  reasoning_effortrR   r|  Nz5Unknown reasoning_effort '%s', using default (medium))r  r  r  r   r7   rT   r   r   )r  r  effortr  s       r"   r9  z$GatewayRunner._load_reasoning_config^  s     	<;;;;;*,, g'92FFF''// 	\c&kk'')) 	\fnNNRTZ[[[r$   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   NrR   u   —z--)rR   FFz--globalTrL  )	shlexr7   rT   r   rM  r   r4   rA   r8   )r  r  r   tokenspersist_globalvalue_tokensr  s          r"   _parse_reasoning_command_argsz+GatewayRunner._parse_reasoning_command_argsq  s     	8>r""((**225$?? 	9	" U[&&FF 	" 	" 	"ZZ\\FFF	"  	+ 	+E
""!%##E****xx%%++--3355~EEs   A A32A3r  rG  c                    |}|s+|)	 |                      |          }n# t          $ r d}Y nw xY wt          | di           pi }|r||v r||         S |                                 S )zCResolve reasoning effort for a session, honoring session overrides.Nr  )r  r   rS   r9  )r  r  rG  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**,,,s    --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  rB   )r  rG  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:::r$   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  rM  rR   r|  >   r  r  normalr   standardN>   r   fastpriorityr$  z#Unknown service_tier '%s', ignoring)r  r7   r   rT   r8   r   r   )r  r  rQ   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tr$   c                  ^    t                      } t          t          | dd          d          S )z<Load show_reasoning toggle from config.yaml display section.r   show_reasoningFr|  )r  r  r   )r  s    r"   r=  z"GatewayRunner._load_show_reasoning  s9     +,,C$455
 
 
 	
r$   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.ra  rR   r   r`  r|  r  r  r  )r1   r  rT   r8   r  r7   r   )r  r  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{r$   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).
        rc  rR   r   rb  r|  r  r  )	r1   r  rT   r8   r  r7   r   r  r?  )legacyr  
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[@r$   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]  rR   r  r\  r|  z7Invalid restart_drain_timeout '%s', using default %.0fs)r1   r  rT   r  r7   r   r  r  r   r  r   r   r   )r  r  rQ   s      r"   rA  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_NOTIFICATIONSrR   r    background_process_notificationsFr  >   NrR   r  >   r  r  r5  r  zBUnknown background_process_notifications '%s', defaulting to 'all')	r1   r  r  r   r7   rT   r8   r   r   )r  r  r  valids       r"   #_load_background_notifications_modez1GatewayRunner._load_background_notifications_mode  s     y:B?? 	 .00C#y*LMMCe||J&&3xx$$&&,,..111uNNT   5r$   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   Nr  r  r  provider_routing)r  r  r:   r  r  r3   r   )r  r  r  r  s       r"   rB  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   Nr  r  r  )r  r  r:   r  r  r   r   )r  r  r  r  fbs        r"   rD  z"GatewayRunner._load_fallback_model+  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                 H    d | j                                         D             S )Nc                 ,    i | ]\  }}|t           u||S r   )_AGENT_PENDING_SENTINEL)r   rG  r  s      r"   r?  z:GatewayRunner._snapshot_running_agents.<locals>.<dictcomp>A  s4     
 
 
"U333 333r$   )rX  rE  r  s    r"   _snapshot_running_agentsz&GatewayRunner._snapshot_running_agents@  s2    
 
&*&:&@&@&B&B
 
 
 	
r$   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_sessionsr  N)hermes_cli.active_sessionsr:  rS   r   )r  r:  s     r"   _get_max_concurrent_sessionsz*GatewayRunner._get_max_concurrent_sessionsG  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.NrX  z'Hermes is at the active session limit (r   z+). Try again when another session finishes.)r<  rS   r   )r  rG  max_sessionsrx  s       r"   _active_session_limit_messagez+GatewayRunner._active_session_limit_messageP  s    88::4'$(92>>>>474):B??@@,&&47l 7 7\ 7 7 7	
r$   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.rX  rT  Nr   )try_acquire_active_sessionr%  zgateway:r  r   rR   r  )r   r   r  )r  surfacer  rU   z'Failed to claim active session slot: %s)	rS   r?  r;  rA  r   rQ   r   r   r   )r  rG  r  local_limit_messagerA  r   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)r7  rS   r   rY  rK  r5   r   r   )rE  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                    t          | dd          }|r|dS 	 |j        5  |                                 |j                            |          }ddd           n# 1 swxY w Y   |t          |dd          nd}|sdS n# t
          $ r Y dS w xY wt          | dd          }|dS t          |d|          }	 t          |                    t          |                              S # t
          $ r Y dS w xY w)a  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.
        rG  NFr  rp  rr  )	rS   _lock_ensure_loaded_locked_entriesr3   r   r   get_compression_lock_holderr7   )r  rG  rG  r  r  r	  rY  s          r"   "_session_has_compression_in_flightz0GatewayRunner._session_has_compression_in_flight  s     ot<< 	m35	$ @ @33555%.22;??@ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @E?Pd;;;VZJ u 	 	 	55	T=$77
5Z
33	66s:GGHHH 	 	 	55	sF   B  /AB  AB  "A#B   
BB8.C' '
C54C5    r  c                    |                      |j                  }|sd S t          |dd           }t          |t                    r|                    |          nd }|t          |dd           t          j        k    sQ|j        t          j        k    s<t          t          |dd                     st          t          |dd                     r-t          |j        |||j        t          j        k               d S |                     ||          | j        k    r#t                              d|| j                   d S |                     |||           d S )NrZ  r  r  
merge_textr  uJ   Dropping busy-mode follow-up for session %s — pending queue at cap (%d).)_adapter_for_sourcer  rS   r   rB   r3   r  r  r  r   r  rZ  TEXTr  _BUSY_QUEUE_MAX_PENDINGr   r   r  )r  rG  r  r   r  rn  s         r"   _queue_or_replace_pending_eventz-GatewayRunner._queue_or_replace_pending_event  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7r$   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}  ||          rY|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                            |j        j                  }|rs|rq|                     |          \  }}|rW| 
                    |          }|                    |j        j        |||                     |j        |          	           d {V  dS n-# tB          $ r  t                              d|d           Y nw xY w| 	                    |j                  }|sdS tE          |dd          rdS | j#                            |          }| j$        }tE          | dd          }|j%        tL          j'        k    r|dk    r|dk    rdS |dk    o| (                    |          }|rt                              d |           d}|dk    o| )                    |          }|rt                              d!|           d}d}|dk    r|j        pd                                }|o|d uo|tT          uotW          |d          }|rY	 tY          |-                    |                    }n5# tB          $ r(}t                              d"||           d}Y d }~nd }~ww xY w|sd}|s|                     ||           |dk    }|dk    }|dk    r7|r5|tT          ur,	 |.                    |j                   n# tB          $ r Y nw xY wt^          j0                            d#d$                                          d$k    }|st          1                    d%|           dS d&} te          j2                    }!| j3                            |d
          }"|!|"z
  | k     rdS d
d'l4m5}# tm          |j        j                  }$|rt^          j0                            d(          }%|%)|%                                                                d)v }&n'tY           |#to                      |$d*d                    }&|&st          1                    d+|           dS |!| j3        |<   g }'tY           |#to                      tm          |j        j                  d,d                    }(|(r|r|tT          ur	 |8                                })|)                    d-d
          }*|)                    d.d
          }+|)                    d/          },| j9                            |d
          }-|-r3tu          |!|-z
  d0z            }.|.d
k    r|';                    |. d1           |+r|';                    d2|* d|+            |,r|';                    d3|,            n# tB          $ r Y nw xY w|'rd4d5<                    |'           d6nd}/|rd7|/ d8}n%|r	|rd9|/ d:}n|r	|rd;|/ d:}n|rd<|/ d=}nd>|/ d?}	 d
d@l=m>}0m?}1m@}2mA}3 to                      }4 |2|4|0          s0|rd}5n|rd}5nd}5| dA |1|5           } |3t          dBz  |0           n2# tB          $ r%}6t          1                    dC|6           Y d }6~6nd }6~6w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# tB          $ r%}7t          1                    dD|7           Y d }7~7nd }7~7ww xY wdS )ENz`Dropping message from unauthorized user in active session: user=%s (%s), platform=%s, session=%sr  T   ⏳ Gateway 2    — queued for the next turn after it comes back.   ⏳ Gateway is - and is not accepting another turn right now.r  r   r   reply_torU   r   has_blocking_approvalrR   >      👍yokr   okayapproveconfirm>      👎nnodenycancelreject>   approve alwaysalwaysalways approverp  >   approve sessionsession approvesessionrt  rg  rl  r   rL  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: %sre  r   z"Busy ack suppressed for session %s   r   rg  >   r   r   r   r   rf  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  u   ⏩ Steered into current runz0. Your message arrives after the next tool call.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\  r  z.Failed to apply busy-input onboarding hint: %szFailed to send busy-ack: %s)C_is_user_authorizedr  r   r   r  	user_namer   rQ   r  rV  r  _thread_metadata_for_sourcer  rY  r  _send_with_retryr   r  r  r  r  
message_idtools.approvalrb  r   rT   r8   _handle_approve_command_handle_deny_commandr  r0  r3   _unwrap_ephemeralr   rS   rX  r  r  r  rW  rK  rQ  r7  r   r   r  r  r1   r2   r  r  r^  r   r   ry  r~  get_activity_summaryr  r   r4   rA   agent.onboardingr~  r  r  r  r  )8r  r  rG  r   reply_anchorthread_metarz   rb  	_raw_text_approve_words_deny_words_approval_handler_normalized_args_verb_synth_reply_adapter_text_eph_ttl_anchorrE  effective_moderb  demoted_for_subagentsdemoted_for_compressionsteered
steer_text	can_steerr[   is_queue_modeis_steer_moderd  _BUSY_ACK_COOLDOWNr  last_ackr   r   steer_ack_envsteer_ack_enabledstatus_partsbusy_ack_detail_enabledsummary	iterationmax_iterrz  start_tselapsed_minstatus_detailr~  r  r  r  	_user_cfg
_hint_mode_onb_errr  s8                                                           r"   #_handle_active_session_busy_messagez1GatewayRunner._handle_active_session_busy_message  s-      ''55 		NN8$&/4|/DS%++)   4 > 	..u|<<G t77>>L::5<VVK//11 x44[%HHHy)C)C)E)EyyywD,F,F,H,Hwww**, |,0AAA.$66. 7 !L #(,"78;L"L"LQVQ]Qg"L$$mrm}$ +          4.4	<<<<<<$$[11 , "Z-24466<<>>	!Y!Y!YMMM$(!#% ..(,(D%%+--(,(A%%"PPP(,(D%'/$$"SSS(,(D%'0$$0 *;d>Z)Z)ZII`fE([[F' @$*!?!?-=!?!?!'EJ#4#4U#;#;;;;;;;FKKV#U,<    $}001FGGH 	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) E77DD 	  # 	%KKD  
 %NW$$**1133J 4!-4!)@@4 M733	   $$"=#6#6z#B#BCCGG  $ $ $NN#Lk[^___#GGGGGG$  )!("  	E00eDDD&'1&'1
 [((](}Tk?k?k''
3333    :>>*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  	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!,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 'MM"R+ +
S5SST5 5
UUC^; ;
__Aa. .
b8bbBe   
f*f

fr  c                 ~   K                                     }                                 dd
dt          dd f fd} j        s |d           |dfS  |d           |dk    r|dfS t	          j                                                    |z   } j        r}t	          j                                                    |k     rT |             t	          j        d	           d {V   j        r)t	          j                                                    |k     Tt           j                  } |d           ||fS )Nr/  Fr   r   c                     t          j                                                    }                                }| s|k    s	|z
  dk    r                    d           ||d S d S )Nr  r  )r:  get_running_loopr  rt  r  )r   r  rx  last_active_countlast_status_atr  s      r"   _maybe_update_statusz@GatewayRunner._drain_active_agents.<locals>._maybe_update_statust  s}    *,,1133C4466L %(999cN>RWZ=Z=Z++J777$0!!$ >[=Zr$   Tr   r   皙?F)r8  rt  r   rX  r:  r  r  r  )r  r  snapshotr  deadline	timed_outr  r  s   `     @@r"   _drain_active_agentsz"GatewayRunner._drain_active_agentso  s     0022 5577	% 	% 	% 	% 	% 	% 	% 	% 	% 	% 	% # 	#  t,,,,U?"4((((a<<T>!+--2244w>" 	%w'?'A'A'F'F'H'H8'S'S  """-$$$$$$$$$ " 	%w'?'A'A'F'F'H'H8'S'S -..	4((((""r$   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)rY  rX  rE  r7  r  r   r  r   )r  r$  rG  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          M| j                                         | 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,	 t'          |          }| j                            |          }|sZ| j        j                            |          }|$|j        st                              d|           |t	          |dd          nd}|k|i	 |j        j        }t          |j                  }|j        rt          |j                  nd}|||f|k    rt	          |dd          }n# t          $ r Y nw xY w|                     ||||t	          |dd          nd||          }|                    |||           d{V }|At	          |dd          du r.t                              d||t	          |dd                     |                    |           t                              d||           # t          $ r(}
t                              d|||
           Y d}
~
d}
~
ww xY w| j        r|t                              d           dS 	 ddlm}  |            rt                              d           dS n2# t          $ r%}
t                              d|
           Y d}
~
nd}
~
ww xY wt=          | j                                                  D ]\  }}| j                             |          }|r|j        s*| j        j                            |          }|(|j        s!t                              d|j                   s|j        t          |j                  |j        rt          |j                  ndf}||v r	 |                     ||j        |j        |           }|r1|                    t          |j                  ||           d{V }n.|                    t          |j                  |           d{V }|Kt	          |dd          du r8t                              d!|j        |j        t	          |dd                     |                    |           t                              d"|j        |j                   # t          $ r2}
t                              d!|j        |j        |
           Y d}
~
d}
~
ww xY wdS )#u4  Send shutdown/restart notifications to active chats and home channels.

        Called at the very start of stop() — adapters are still connected so
        messages can be delivered. Best-effort: individual send failures are
        logged and swallowed so they never block the shutdown sequence.
        Nr  r  zpYour current task will be interrupted. Send any message after restart and I'll try to resume where you left off.z&Your current task will be interrupted.u   ⚠️ Gateway     — rG  originz>Failed to load session origin for shutdown notification %s: %sr   r   r  z^Shutdown notification suppressed for active session: %s has gateway_restart_notification=falser  r  r  reply_to_message_idr   r   r  TFz1Failed to send shutdown notification to %s:%s: %sr5  send returned success=Falsez/Sent shutdown notification to active chat %s:%sz@Skipping home-channel shutdown notifications for in-chat restartr   )drain_notification_suppressedzWHome-channel shutdown broadcast suppressed by drain marker (suppress_notification=true)z.drain_notification_suppressed check failed: %sz\Shutdown notification suppressed for home channel: %s has gateway_restart_notification=falser  z>Failed to send shutdown notification to home channel %s:%s: %sz0Sent shutdown notification to home channel %s:%s)!r8  r  r  r5   rS   rG  _ensure_loadedrO  r3   r   r   r  _get_cached_session_sourcer   rQ   r7   r   r  r  r  r0  r  r   gateway_restart_notificationr  _thread_metadata_for_targetr   r9   r  r  rY  rE  get_home_channel)r  r  restart_sourceactionhintr  notifiedrG  r  r  r  platform_strr   r  _parsed	dedup_keyr   r   r   r  restart_platformrestart_chat_idrestart_thread_idrU   r  r  r  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&55777 .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B::
C*C%%C*+L8/AL84L8AI&%L8&
I30L82I33BL81L88
M*M%%M**O   
O/
O**O/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_finalizer  r%  r  r  r   r$  zshutdown finalizerw   )valuesrS   r   r   rY  r   r   r  hermes_cli.pluginsr  !_cleanup_agent_resources_off_loop)r  r  r  _flushr  _strip_e_invoke_hooks           r"   _finalize_shutdown_agentsz'GatewayRunner._finalize_shutdown_agents^  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)rw  rX  r3   )r  rG  r  r  s       r"   &_should_emit_long_running_notificationz4GatewayRunner._should_emit_long_running_notification  sW     =5$););)=)=$5 	4/33K@@MM5tr$   r  rw   c                  K   |dS |                     d          r	 d|_        n# t          $ r Y nw xY w	 t          j        |                     | j        |          | j                   d{V  dS # t          j        $ r- t          
                    d|rd| dnd| j                   Y dS t          $ r/}t          
                    d	|rd| dnd|           Y d}~dS d}~ww xY w)
u  Run _cleanup_agent_resources in a worker thread with a bounded wait.

        Safe to await from coroutines on the gateway event loop: a slow or
        wedged teardown (memory provider IO, subprocess close) can no longer
        block message processing. On timeout the await is cancelled and the
        worker thread is left to finish (or leak) on its own — the caller
        proceeds regardless, exactly as the /new reset path does (#35994).
        Nr  Fr8  zAgent resource cleanup%s exceeded %ss; proceeding without blocking the event loop (the worker thread is left to finish on its own). (#53175)r|  r  rR   z,Agent resource cleanup%s failed: %s (#53175))rr  _end_session_on_closer   r:  r?  _run_in_executor_with_context_cleanup_agent_resources_CLEANUP_TIMEOUT_Sr  r   r   )r  r  rw   cleanup_excs       r"   r  z/GatewayRunner._cleanup_agent_resources_off_loop  s      =Fj)) 	.3++   	"2215  /	            # 	 	 	NN( $+2W'       	 	 	NN>#*2W        	s)   % 
22:A2 28C%-	C%6$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   rS   r   rY  r  r   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rU  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   Nr+   r  )	r  r  _STUCK_LOOP_FILEr:   r  r[  r   r3   r  )r  r  r  r;   counts
new_countsrL  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>4  s*    VVVDAqa4;U6U6Ua6U6U6Ur$   Tr+   u_   Auto-suspended stuck session %s (active across %d consecutive restarts — likely a stuck loop)r  )r  r  r  r:   r  r[  r   rE  rG  rO  r3   	suspendedr   r   _saver  )r  r  r;   r  r  
stuck_keysrG  r  s   `       r"   _suspend_stuck_loop_sessionsz*GatewayRunner._suspend_stuck_loop_sessions!  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   Nr  Tr  )	r  r  r  r:   r  r[  r  r  r   )r  rG  r  r;   r  s        r"   _clear_restart_failure_countz*GatewayRunner._clear_restart_failure_countR  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    r
dd l}ddlm} g |d	d
}|                    d                                          }	t          j                                        }
|
                    dd            t+          t,                                                    j        j        }t          j        }	 ddlm}  |t          j                  \  }}}n# t8          $ r t          j        }Y nw xY wt+          |
                    d          p|dz            }|dz  dz  }|                                rt?          |          |
d<   t?          |          t?          |          g}|
                    d          r|                     |
d                    t          j!        "                    tF          $                    |                    |
d<    |j%        |d|	t?          |          t?          |          g|f|j&        |j&        |
d |             d S d"                    d |D                       }dtO          |           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   r&   )windows_detach_popen_kwargsr%  r  u  
                import os, subprocess, sys, time
                from hermes_cli._subprocess_compat import windows_detach_flags_without_breakaway
                pid = int(sys.argv[1])
                restart_after_s = float(sys.argv[2])
                cmd = sys.argv[3:]
                deadline = time.monotonic() + restart_after_s

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

                while time.monotonic() < deadline:
                    if not _alive(pid):
                        break
                    time.sleep(0.2)
                subprocess.Popen(
                    cmd,
                    stdout=subprocess.DEVNULL,
                    stderr=subprocess.DEVNULL,
                    creationflags=windows_detach_flags_without_breakaway(),
                )
                r  )_resolve_detached_pythonr'   r(   r)   r*   r,   -cr6  r7  envrL  c              3   >   K   | ]}t          j        |          V  d S rr  )r  quoter^  s     r"   ru  zAGatewayRunner._launch_detached_restart_command.<locals>.<genexpr>  s,      @@Tu{4((@@@@@@r$   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)r6  r7  r  start_new_session))r  r=  r  r   r5  r  r1   getpidr  r   rS   r-   r   textwraphermes_cli._subprocess_compatr  dedentrT   r2   copyr  r   r.   r/   r0   r  hermes_cli.gateway_windowsr	  r   r3   r:   r7   r4   r@   rA   rB   rC   PopenDEVNULLr   r  )r  r  r=  
hermes_cmdcurrent_pidrestart_after_sr  r  cmd_argvwatcherwatcher_envrD   watcher_pythonr	  _watcher_venv_dir_watcher_site_packagesrG   rJ   rN   r   	shell_cmd
setsid_bins                         r"    _launch_detached_restart_commandz.GatewayRunner._launch_detached_restart_commandg  s     (**
 	LLOPPPF0 	F04-ikkeGD2JC$P$P$WTWXX[^^`cdd <7""OOOQQQQQQ::Y:	:Hoo-/ /^ egg_ ` *//++K OO-t444>>1133:AL ^N0
 POOOOO -,S^<< J 13I3I  0 0 0!$0KOOM::SlV>STTH$u,>M##%% W-0]]M*!,//]1C1CD
??<00 A%%k,&?@@@,.JOODMM*<U<U,V,VL)JwK0@0@#oBVBVbYab!)!)	 
 .-//   Fhh@@Z@@@@@%#o*>*> % %(% %% % % 	 joo'')4000\\(++
 	VUI6!)!)"&       	*!)!)"&      s   E& &E?>E?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--valueTrV  )capture_outputr   r  rR   )runr6  rT   r   )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-rE  rZ  z	--collectz--unitz/bin/shr  T)r6  r7  r  zALaunched systemd planned-restart helper for %s (pid=%s, scope=%s)r4  r3  z3Failed to launch systemd planned-restart helper: %s)r-   r   r1   r2   r3   r  r=  r  hermes_cli.gatewayr+  r   r  r7   r  r  r   r  r  r   r  r  )r  r  systemd_runr+  r  r4  
system_piduser_pidr1  systemctl_scopeservice_argr$  	unit_namer  r3  r=  r*  s                 @@@r"    _launch_systemd_restart_shortcutz.GatewayRunner._launch_systemd_restart_shortcut  s    <7"""*..*I*I"FP	SMMM ,,}55K[11I i 0??????//11 0 0 0/0 )++K	 	 	 	 	 	 	 $BJ!z8*--H;:-- "-[!!X--'j"4
 +l33K; ; ;"; ;2=; ;"; ;-8; ; 
 (GG+GGOOPSUXYYI	 	  	 		
 	 	 	 	 ")!)"&     KKS%38	      	S 	S 	SLLNPQRRRRRRRRR	SsC   6F /B  ?F  BF BA%F 6BF 
F;F66F;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r  detached_restartservice_restart)r&  r   r   r5  r:  r  rm  )r  r?  r  r@  s    r"   _run_restartz3GatewayRunner.request_restart.<locals>._run_restartZ  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   N)r  r  r   r  r:  create_taskr  )r  r?  r@  rG  s   ``` r"   request_restartzGatewayRunner.request_restartR  s    % 	5"&!)$/!%)"	b 	b 	b 	b 	b 	b 	b 	b* %0@@tr$   >   restart_timeoutshutdown_timeout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_messagerS   r   rB   r3   r:  shieldrX  r7  _release_running_agent_state)r  r   r  rG  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=%sr  )
rS   r`  r4   r  r   r  r   rQ   r   r   )r  r  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          }|| j                            |j                  nd}|:t
                              dt          t          |dd          dd                     	 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 %sr   rQ   _hermes_startup_restore_replayTr+   )
rS   r  r0  r3   r   r   r  setattrr   rP  )r  drainedr  r  r  r   s         r"   _drain_startup_restore_queuez*GatewayRunner._drain_startup_restore_queue  s*     6===1 	IIaLLEUHd33F<B<Ndm''888TXGYGFJ==wMM   ?FFFF   ((/////////qLG#  	$ s   "B4 4
C C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.ra  return_exceptionsTNzstartup auto-resume task failedr~   Fz;Drained %d inbound message(s) queued during startup restore)rY  rS   r:  gatherr   r   r   r  rl   r   ra  r[  r  r  )r  tasksresultsr  rZ  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^_____	` 	`r$   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        } j                            |j                  }|;t                              d|
j        t3          |j        d|j                             	                      |          s!t                              d	|
j                   n9# t          $ r,}t                              d
|
j        |           Y d}~
d}~ww xY wt6           j        |
j        <   t9          j                     j        |
j        <                                     t?          dt@          j!        |d          }tE          j#         $                    |||
j                            } j%        &                    |           |'                     j%        j(                   t3           dd          r1t3           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 rr  )resume_pendingr  r  resume_reason_AUTO_RESUME_REASONSr   )r   r  r   r  s     r"   r`  zCGatewayRunner._schedule_resume_pending_sessions.<locals>.<listcomp>  sm       #+ "O 0+t/HHH!)U\-Bh-N-N 
 .O-N-Nr$   Nz/Failed to enumerate resume-pending sessions: %sr   r  z$Restart-loop guard check skipped: %sz5Skipping auto-resume for %s: adapter not ready for %srQ   z^Skipping auto-resume for %s: session owner is no longer authorized under the current allowlistz;Skipping auto-resume for %s: authorization check failed: %srR   T)r   r  r  ru  r  Fra  r+   z;Scheduled auto-resume for %d restart-interrupted session(s)),r  rG  rM  rN  rO  r  r   r   r   r%  r  r  check_and_recordr  r   r  last_resume_marked_at
updated_attotal_secondsrG  rX  r  r0  r3   r   rS   r  r7  r  r  r  r  r  rW  r:  rI  rT  r|  r9   add_done_callbackr  ra  r4   r  )r  r   r  rE   r[   r  _max_restarts_windowr  	scheduledr  markerr  r   r  r|   r_  s   ``               r"   !_schedule_resume_pending_sessionsz/GatewayRunner._schedule_resume_pending_sessions  sN   . 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m''88G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5H		
H?!H::H?c                 P    | j         p| j        p| j                                        S rr  )r  r  rL  is_setr  s    r"   _startup_should_abortz#GatewayRunner._startup_should_abort^  s.    # -~-#**,,	
r$   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: %srD  T)rs  r  r   r   r  rQ   r  r  r:  current_taskrL  rr  rm  r  r   r  )r  r   r   r  	stop_taskru  s         r"   $_abort_startup_if_shutdown_requestedz2GatewayRunner._abort_startup_if_shutdown_requestede  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           
      '  K   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                                 nz# t          $ r Y nnw xY w	 | j:        ;                                }%|%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 }*| j        j@        #                                D ]V\  }}+|                                  d{V r d S |+jA        s+|(d/z  }(| B                    ||+          },|,sk|j$        }-dG t          jD        E                                D             }.|-|.vrt                               dH|-           nt                               dI|-           |,F                    | jG                   |,H                    | jI                   |,J                    | j:                   |,K                    | jL                   |,M                    | jN                   |,O                    | P                    |,jQ                             | jR        |,_R        t                               dJ|j$                   | S                    |j$        dKddL           	 | T                    |,|           d{V }/|                     |,|           d{V r d S |/rd|,| jU        |<   | V                    |,           |'d/z  }'| S                    |j$        dMddL           t                               dN|j$                   n*t                               dO|j$                   | W                    |,|           d{V  |,jX        r| S                    |j$        |,jY        rdPndQ|,jZ        |,j[        L           |,jY        r|*n|)}0|0\                    |j$         dR|,j[                    |,jY        r"|+d/t          j^                    dSz   dT| j_        |<   n]| S                    |j$        dPddUL           |*\                    |j$         dV           |+d/t          j^                    dSz   dT| j_        |<   n# t          $ r}#t           %                    dW|j$        |#           | W                    |,|           d{V  | S                    |j$        dPdt          |#          L           |*\                    |j$         dR|#            |+d/t          j^                    dSz   dT| j_        |<   Y d}#~#nd}#~#ww xY w|                                  d{V r d S X	 | a                                 d{V }1|'|1z  }'n# t          $ r}#t          |#          }t           %                    dX|           	 ddlm}	  |	d3|           n# t          $ r Y nw xY wt          | _d        | &                    |           d;| _=        Y d}#~#d S d}#~#wt          $ r'}#t           %                    dY|#d !           Y d}#~#nd}#~#ww xY w|'dk    rA|)rdZe                    |)          }t           %                    d[|           	 ddlm}	  |	d3|           n# t          $ r Y nw xY wt          | _d        | &                    |           d;| _=        d S |(dk    r|*rhdZe                    |*          }t                               d\t          | j_                  |           	 ddlm}	  |	d]d           n# t          $ r Y nw xY wt                               d^|(           n4t                               d_           t                               d`           |                                  d{V rd S | jU        | jg        _U        | h                                 d | _i        | j                    da           t          | j2        jk                  }2|2rt                               db|2           | j2        l                    dcddde | jU        m                                D             i           d{V  |'dk    rt                               df|'           	 ddglnmo}3  |3| jU                   d{V }4t          dh |4                    ddi           E                                D                       }5t                               di|5           n2# t          $ r%}#t                               dj|#           Y d}#~#nd}#~#ww xY w| q                                 d{V }6|6s?t?          dk tn          dlz  tn          dmz  fD                       r| r                                 |'dk    rt          js        dn           d{V  t                      }7t                      s|7rd | _v        | w                                 d{V  |7r?	 | x                    do           d{V  t                       n# t                       w xY w| z                                 | {                                 d{V  	 dd>l4m5}! |!j|        }8g |!_|        t          |8          D ]}\  }9}:t          j~        |                     |:                     t                               dp|:                    dq                     |9drz  dsk    rt          js        d           d{V  ~n2# t          $ r%}#t           %                    dt|#           Y d}#~#nd}#~#ww xY wt          j~        |                                            t          j~        |                                            t          j~        |                                            | j_        rPt                               dut          | j_                  dve                    dw | j_        D                                  t          j~        |                                            t          j~        |                                            t          j~        |                                            	 |                                 rTt                               dx|                                            t          j~        |                                            n|                                  n,# t          $ r t                               dyd !           Y nw xY wt          j~        |                                            t                               dz           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: %sr  r  zuAgent budget: max_iterations=%d (agent.max_turns from config.yaml, or HERMES_MAX_ITERATIONS from .env, or default 90)rl  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 rr  )allowed_users_envr   r  s     r"   ru  z&GatewayRunner.start.<locals>.<genexpr>  sB       ) )()&)#) ) ) ) ) )r$   c              3   2   K   | ]}|j         	|j         V  d S rr  )r  r  s     r"   ru  z&GatewayRunner.start.<locals>.<genexpr>  s@       + +$%?++ + + + + +r$   c              3   >   K   | ]}t          j        |          V  d S rr  )r1   r  r  s     r"   ru  z&GatewayRunner.start.<locals>.<genexpr>  s;       
 
BIaLL
 
 
 
 
 
r$   r  rR   >   r   r   r   c              3   h   K   | ]-}t          j        |d                                           dv V  .dS )rR   >   r   r   r   N)r1   r  r8   r  s     r"   ru  z&GatewayRunner.start.<locals>.<genexpr>"  s\       e
 e
 Ia""$$(<<e
 e
 e
 e
 e
 e
r$   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  r+   rV  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: %sc                     h | ]	}|j         
S r   r  r   r   s     r"   r   z&GatewayRunner.start.<locals>.<setcomp>  s    !Q!Q!Qa!'!Q!Q!Qr$   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 %szConnecting to %s...
connectingrb  r  u   ✓ %s connectedu   ✗ %s failed to connectr`  ra  r}  rv  rf  zfailed to connectz: failed to connectu   ✗ %s error: %sz$Gateway multiplexer config error: %sz,Secondary-profile adapter startup failed: %sr5  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.r  z%s hook(s) loadedzgateway:startupr   c                     g | ]	}|j         
S r   r  rt  s     r"   r`  z'GatewayRunner.start.<locals>.<listcomp>  s    @@@a!'@@@r$   z#Gateway running with %s platform(s)build_channel_directoryc              3   4   K   | ]}t          |          V  d S rr  )r   )r   chss     r"   ru  z&GatewayRunner.start.<locals>.<genexpr>  s(      WW3s88WWWWWWr$   z%Channel directory built: %d target(s)z"Channel directory build failed: %sc              3   >   K   | ]}|                                 V  d S rr  )r:   )r   r;   s     r"   ru  z&GatewayRunner.start.<locals>.<genexpr>  s>        
  
 KKMM 
  
  
  
  
  
r$   .update_pending.json.update_pending.claimed.jsonr  skip_targetsz(Resumed watcher for recovered process %sr  d   c   z!Recovered watcher setup error: %sz;Starting reconnection watcher for %d failed platform(s): %sr}  c              3   $   K   | ]}|j         V  d S rr  r  rt  s     r"   ru  z&GatewayRunner.start.<locals>.<genexpr>  s$      BBa!'BBBBBBr$   u?   scale-to-zero: armed (idle timeout %.0fs) — watching for idlez*scale-to-zero: arm check failed at startupzPress Ctrl+C to stop)r   r  r:  r  rJ  r  r  r&  gateway.shutdown_forensicsry  r  r3   r   r   r  r   r1   r  r8   r  r  r  r  hermes_cli.security_advisoriesr  r  rw  gateway.platform_registryr  rK  plugin_entriesr  r  rM  r  rE  rQ   r5  rr  r  r  r  r  r  r  r  r  r  agent.shell_hooksr  rx  discover_and_loadr  r  recover_from_checkpointr  r:   r  rG  suspend_recently_activer  r  r`  ra  r   r'  _create_adapterr  __members__r  set_message_handler_handle_messageset_fatal_error_handlerro  set_session_storeset_busy_session_handlerr  set_topic_recovery_fnr/  set_authorization_check_make_adapter_auth_checkr   r  rl  r  r0  r  r  has_fatal_errorrk  ri  rj  r4   r  r  rk  r7   !_start_secondary_profile_adaptersr  r  r  rA   r   rH  r  rI  r  loaded_hooksemitr  gateway.channel_directoryr  sum_send_update_notification#_schedule_update_notification_watchr  r  r  rR  _send_restart_notification(_send_home_channel_startup_notificationsr  rp  ra  r{  r  rI  _run_process_watcher_session_expiry_watcher_kanban_notifier_watcher_kanban_dispatcher_watcher_platform_reconnect_watcher_handoff_watcher_async_delegation_watcherr  r  r  r  r  );r  ry  
_alignmentr  _effective_max_iter_redact_raw
_redact_onr  r  r  r  r  	_adv_hits_adv_msg_builtin_allowed_vars_builtin_allow_all_vars_plugin_allowed_vars_plugin_allow_all_varsr  _any_allowlist
_allow_allr$  r   r  r   r  r  r  r  r  r  r  r  r  r.  r  _clean_markerr  stuckconnected_countenabled_platform_countstartup_nonretryable_errorsstartup_retryable_errorsr  r   _pval_builtin_namesr  target_secondary_connected
hook_countr  	directorych_countr  $planned_restart_notification_pendingwatchersr  r  s;                                                              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 .FFHH	 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  *.)>)D)D)F)F {	 {	%Ho>>@@@@@@@@ tt"* "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))$*PQQQ++D,I,I'JZ,[,[\\\&*&:G# KK-x~>>>00+"	 1   R $ B B7H U UUUUUUU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-44444 	[ 	[ 	[LLGUYLZZZZZZZZ	[ 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... 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-$$$$$$$$$ 0U/V/V, )** 	-.R 	-(,D%--///////// 0 	66CC!% D          4555535555 	..000**,,,,,,,,,	A??????
 (8H02- (11 + +
7#D$=$=g$F$FGGGFT`HaHabbbs7b==!-*********	+
  	A 	A 	ALL<a@@@@@@@@	A 	D88::;;;
 	D99;;<<< 	D;;==>>> ! 	KKMD*++		BB4+ABBBBB  
 	D<<>>??? 	D1133444 	D::<<===	V--// 
;U<<>>   #D$?$?$A$ABBBB
 88::: 	V 	V 	VLLEPTLUUUUU	V 	D7799:::*+++ts)  7 A
A4A1C& &
D0DD=E 
E$#E$(A#G 
GG3H 
HH"H6 6
IIAJ &KK-AM
 

MM Q4 4
R RR- -&SSAT( (&UU!U7 7&V V =7W5 5
X$?XX$ Y5 5
ZZ6Z= =
[,[''[,01\" "
],]]<8l7Fl
oB)o  o(p 
s*r=qr
qrq+rsr>>s t 
t! t!v. .
v;:v;A6}> >
~-~((~-A-AB BAB(CB!AE< E<
AF+FAF&F&AF+K*A<AM' M'&ANNAN       @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  Nrk   z!Handoff for session %s failed: %sTr~   zHandoff watcher tick error: %s)r:  r  rI  rp  list_pending_handoffsr3   claim_handoff_process_handoffcomplete_handoffr   r   r   fail_handoffr7   r  r  )r  r  pendingrZ  r  r[   s         r"   r  zGatewayRunner._handoff_watcher6  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rZ  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                            |           | j                            ||          }|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   r  )r  r  )r  rk   handoff_platformrR   zhandoff_platform is emptyzunknown platform 'rY  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)r   r   	chat_namer  r  r  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  ru  ub   Handoff: dispatching synthetic turn for CLI session %s → %s (home=%s, thread=%s, session_key=%s)r  r   r   rU   zadapter.send failed: r  r5  r  )%gateway.configr  r  r  r  r  r  r3   rT   r8   r  r   KeyErrorr0  r  r  r   create_handoff_threadr7   r   r   r  r  r  r  rt   r   r  rG  get_or_create_sessionswitch_session_evict_cached_agentrR  r  r  r   rS   )r  rZ  r  r  r  r  cli_session_idr  r   r   r  	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   r  rG  switchedsynthetic_textsynthetic_eventresponse_textsend_metadatar  r  s                                  r"   r  zGatewayRunner._process_handoffh  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
 
 
 	00=== %44[.QQ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9NNr  c           	        K   t          j        d           d{V  i }d}| j        r	 | j                                         g }t          | j        j                                                  D ]?\  }}|j        r| j        	                    |          s(|
                    ||f           @|ri }|D ]S\  }}	|                    d          }
t          |
          dk    r|
d         nd}|                    |d          dz   ||<   Td	                    d
 t          |                                          D                       }t                               dt          |          |           |D ]?\  }}	 	 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                            |          }t1          |t2                    r|d         n|r|nd}ddd           n# 1 swxY w Y   || j                            |          }|r&|t6          ur|                     |d           d{V  |                     |           | j                            |d           |                      |d           tC          | d          r| j"                            |d           t-          | dd          }||                    |d           t-          | dd          }t1          |tF                    r|                    |d           t-          | dd          }t1          |tF                    r|                    |d           | j        $                    |           t           %                    d|j                   |                    |j        d           ~# t*          $ r}|                    |j        d          dz   }|||j        <   ||k    rZt           &                    d||j        |           | j        $                    |d           |                    |j        d           n#t           %                    d|||j        |           Y d}~9d}~ww xY w|retO          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$}tS          j)                    |z
  |k    r	 tU          t-          | j+        d%d          pd          }|dk    r7| j        ,                    |          }|rt                               d&|           n2# t*          $ r%}	t           %                    d'|	           Y d}	~	nd}	~	ww xY wtS          j)                    | _-        n2# t*          $ r%}t           %                    d(|           Y d}~nd}~ww xY wt]          |          D ]%}| j        s nt          j        d           d{V  &| j        dS dS ))a  Background task that finalizes expired sessions.

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

q

. . . . . .r$   z,Session expiry: %d sessions to finalize (%s)r  rR   r  session_expiredr  re  zsession expiryr  _pending_model_notesr[  rj  rl  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 )r+   N)expiry_finalized)r   rE  r  s      r"   ru  z8GatewayRunner._session_expiry_watcher.<locals>.<genexpr>  sB          "a!:L            r$   z3Session expiry done: %d finalized, %d pending retryz!Session expiry done: %d finalizedz+Agent cache idle sweep: evicted %d agent(s)zIdle agent sweep failed: %s_last_session_store_prune_tsr/  r   session_store_max_age_daysz,SessionStore prune: dropped %d stale entrieszSessionStore prune failed: %sz Session expiry watcher error: %s)/r:  r  rI  rG  r  rY  rO  rE  r3  _is_session_expiredr4   rM  r   r3   rA   sortedr   r  r  r  r  r   rS   rd  r   rK  rX  r7  r  r  r  r  r  r   r0  rB   set_expiry_finalizedr  r   r  _sweep_idle_cached_agentsr  r   r  prune_old_entriesr4  range)r  r  _finalize_failures_MAX_FINALIZE_RETRIES_expired_entriesrL  r  
_platforms_kr  _parts_plat_plat_summaryr  	_platform_cached_agent_cache_lock_cached_lrmrj  rl  r  failures_done_failed_idle_evicted_last_prune_ts_prune_interval_max_age_prunedrE  s                                  r"   r  z%GatewayRunner._session_expiry_watcher  s      mB-/ !m o	'iD"11333#% "&t'9'B'H'H'J'J"K"K : :JC- ! -AA%HH ! $++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 W WJCV!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 599#tDDD<<S$GGG"4)?@@ E 599#tDDD
  't-CTJJ+ HHS$///-4T;OQU-V-V*%&8$?? >.223===18?WY]1^1^.%&<dCC B266sDAAA
 *??FFF=!,   +..u/?FFFF$   #5#9#9%:JA#N#NQR#R?G*5+;<#'<<<"NN!W (%*:A  
 !.CC %E D    /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<<&*&8&J&J8&T&TG& " &$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&&&&&&&&&&_ m o	' o	' o	' o	' o	's   EY ;AGO1
GO1GO1/>H9-O19H=	=O1 H=	F.O1/Y 1
R1;B+R,&Y ,R11A*Y 1U Y 
U=U83Y 8U==0Y .A"X Y 
Y X;6Y ;Y  Y 
Z&ZZc                 J    	 ddl m}  |            pdS # t          $ r Y dS w xY w)z0Return the profile name this gateway represents.r   r  r   )r  r  r   )r  r  s     r"   rf  z"GatewayRunner._active_profile_name  sO    	CCCCCC**,,9	9 	 	 	99	s    
""c           
      ^
  K   d}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 ]D}| j        s dS | j        |         }|	                    d          r0||d         k     r=|d         }|d	         dz   }t                              d
|j        |           d}	 |                     ||          }|s)t                              d|j                   | j        |= |                    | j                   |                    | j                   |                    | j                   |                    | 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# tH          $ r Y nw xY w	 | %                    |           nD# tH          $ r& t          &                    d|j        d           Y nw xY w|j'        rs|j(        sl| !                    |j        d|j)        |j*                   t                              d|j        |j*                   tW          |           d{V  | j        |= n| !                    |j        d|j)        |j*        pd           tY          dd|dz
  z  z  |          }||d	<   t          j                    |z   |d<   t                              d|j        |           tW          |           d{V  # tH          $ r}|tW          |           d{V  | !                    |j        ddt[          |                     tY          dd|dz
  z  z  |          }||d	<   t          j                    |z   |d<   t                              d|j        ||           Y d}~>d}~ww xY wt	          d          D ]&}| j        s dS t          j        d           d{V  '| j        dS dS )u7  Background task that periodically retries connecting failed platforms.

        Uses exponential backoff: 30s → 60s → 120s → 240s → 300s (cap).
        Retryable failures (network/DNS blips) keep retrying at the backoff
        cap indefinitely — they self-heal once connectivity returns, so a
        transient outage never requires manual intervention. Non-retryable
        failures (bad auth, etc.) drop out of the queue immediately. The
        circuit breaker (``_pause_failed_platform`` / ``/platform pause``)
        remains available for manual operator control via ``/platform list``
        and ``/platform resume <name>``, but is no longer triggered
        automatically — auto-pausing a recovered platform was the cause of
        bots silently staying dead after a transient DNS failure.
        r  
   Nrv  r+   r  rh  r  rg  zReconnecting %s (attempt %d)...zGReconnect %s: adapter creation returned None, removing from retry queueTr  r  rb  u   ✓ %s reconnected successfullyr   r  r!   z3resume-pending reschedule after %s reconnect failedr~   ra  zAReconnect %s: non-retryable error (%s), removing from retry queuer`  zfailed to reconnectrV  z&Reconnect %s failed, next retry in %dsz)Reconnect %s error: %s, next retry in %ds).r:  r  rI  rk  r;  r  r  rY  r  r3   r   r  rQ   r  r   r  r  r  ro  r  rG  r  r  r  r/  r  r  r   r  r  r0  r  rH  rl  r  r  r   rp  r  r  rk  ri  rj  r  r  r7   )r  _BACKOFF_CAPrE  r  r   r  r  attemptr   r  r  backoffr  s                r"   r  z)GatewayRunner._platform_reconnect_watcher  s      mBm k	') r + +A= - !-**********.""C !7!<!<!>!>?? V V} FF-h7 88H%% l+++"&x.z*Q.5NG  
 C"228_MMG" !e$N   !28< //0DEEE33D4TUUU--d.@AAA44T5]^^^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^	 =    #&bA'A+,>&?"N"N+2Z(-1^-=-=-G\*D$NG   6g>>>>>>>>> !   * 6g>>>>>>>>>88 '1#'&)!ff	 9    ""gk(:";\JJG'.D$)-)9)9G)CD&NNC 7       %6 2YY ' '} FFmA&&&&&&&&&&W m k	' k	' k	' k	' k	'sj   A P:EP:.K
P:
KP:KP:K42P:4,L$ P:#L$$DP::
S*BS%%S*rD  r  rE  rF  c                    K   |rd _         | _        | _         j         j         d{V  dS 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                              dj        rdnd           t	          j                    dt          ffd}d_        d	_        	                                 d {V  t                              d
 |                       j
        }g }t          j                                                  D ]|\  }}|t          u r	 j                            |j        rdnd           |                    |           J# t$          $ r&}t                              d||           Y d }~ud }~ww xY wt	          j                    }                    |           d {V \  }}	t                              d |            t	          j                    |z
  |	t+          |                                                     |	s]|D ]Z}|j        vrO	 j                            |           '# t$          $ r&}t                              d||           Y d }~Rd }~ww xY w[|	rt                              d|                                           j        rdnd}
t          j                                                  D ]^\  }}|t          u r	 j                            ||
           ,# t$          $ r&}t                              d||           Y d }~Wd }~ww xY w                    j        rt4          nt6                     t9          j                                                    dz   }j        rt9          j                                                    |k     r_                    d           t9          j        d           d {V  j        r)t9          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  tI          dd           }tI          dd           }|||5  t          |%                                          }|&                                 d d d            n# 1 swxY w Y   |D ]>}tO          |tP                    r|d         n|})                    |d           d {V  ?t          j*                                                  D ]!\  }}+                    ||           d {V  "t          tI          di                                                     D ]^\  }}t          |                                          D ]#\  }}+                    |||           d {V  $|&                                 _tY          d          rj-        &                                 t                              d |                       t          j.                  D ]*}|j/        u r|j0        u r|1                                 +j.        &                                 j*        &                                 t          j                  D ]}2                    |           j        &                                 j3        &                                 tY          d           rj4        &                                 j5        &                                 j6        &                                 tY          d!          rj7        &                                 j8        9                                  | d"           t                              d# |                       	 dd$l:m;}  |             n2# t$          $ r%}t                              d%|           Y d }~nd }~ww xY wtI          d&d           }tI          |d'|          }|tI          tI          d(d           d'd           fD ]\}|tY          |d)          s	 |<                                 +# t$          $ r%}t                              d*|           Y d }~Ud }~ww xY wtz          >                               t                              d+ |                       dd,l?m@}mA}  |              |             |	s.	 t          d-z  C                                 n*# t$          $ r Y nw xY wt                              d.           |r4D                    ts          |E                                                     j        rjF        	 t          t                      t	          j                    t          jJ                  t          j                   d/d 0           n2# t$          $ r%}t                              d1|           Y d }~nd }~ww xY wj        r5jJ        r.K                                 t          _M        jN        pd2_N        d_        tI          d3d          r=j        s6t                              d4                               d5jN                   n                    d6jN                   t                              d7 |                       d S )8N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
| |           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)interrupt_allzgateway shutdown (r  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   r  r   r  ry  r[  tools.terminal_toolr\  tools.browser_toolr]  )rY  r  _killedr  _interrupt_async_async_nr\  r]  s           r"   _kill_tool_subprocesseszGGatewayRunner.stop.<locals>._stop_impl.<locals>._kill_tool_subprocesses  s4   	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	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s]   8; 
A+A&&A+/4B$ $
C.CCC) )
D3DDD/ /
E 9EE zStopping gateway%s...z for restartrR   c                  0    t          j                     z
  S rr  )r  r  )_stop_started_ats   r"   _phase_elapsedz>GatewayRunner.stop.<locals>._stop_impl.<locals>._phase_elapsed  s    ~''*:::r$   FTz5Shutdown phase: notify_active_sessions done at +%.2fsrK  rL  z/pre-drain mark_resume_pending failed for %s: %szhShutdown phase: drain done at +%.2fs (drain took %.2fs, timed_out=%s, active_at_start=%d, active_now=%d)z2clear_resume_pending after drain failed for %s: %szYGateway drain timed out after %.1fs with %d active agent(s); interrupting remaining work.z%mark_resume_pending failed for %s: %sr   r  r  zpost-interruptz7Shutdown phase: post-interrupt tool kill done at +%.2fsz-Failed to launch detached gateway restart: %sre  rd  r   zshutdown idle-cacher  r1  r  z3Shutdown phase: all adapters disconnected at +%.2fsrY  r^  zfinal-cleanupz6Shutdown phase: final-cleanup tool kill done at +%.2fs)shutdown_cached_clientsz!shutdown_cached_clients error: %srp  rr  rG  r  zSessionDB close error: %sz.Shutdown phase: SessionDB close done at +%.2fsremove_pid_filerelease_gateway_runtime_lockr  u   Skipping .clean_shutdown marker — drain timed out with interrupted agents; next startup will suspend recently active sessions.)requested_atr@  r?  r  z7Failed to write planned restart notification marker: %szGateway restart requestedrP  u   Gateway stopped by an unexpected signal — persisting gateway_state=running so container_boot auto-starts on the next boot (issue #42675)r  stoppedz&Gateway stopped (total teardown %.2fs))Or7   r   r  r  r  r  r   rI  r  r  r  rY  rX  rE  r7  rG  mark_resume_pendingr4   r   r  r  r   rt  clear_resume_pendingr   r  !_INTERRUPT_REASON_GATEWAY_RESTART"_INTERRUPT_REASON_GATEWAY_SHUTDOWNr:  r  r  r  r   r&  r5  r  rS   r  r  r   rK  r  r0  r  r   r1  r|  r  r  rm  rR  r  rY  rZ  rj  r^  rL  r5   r  rh  r  r  _shutdown_executorr  rj  rk  r  touchr  r  r  r  r  r   r  r=  r  r  rO  )rd  rg  r  _pre_drain_keys_sk_agentr  _drain_started_atr  r  _resume_reasoninterrupt_deadliner  rF  _cache_idle_agents_entryr   r   _prof_amap_task_session_keyrh  _self_dbrr  rj  rk  rf  r  s                               @r"   
_stop_implz&GatewayRunner.stop.<locals>._stop_impl  s     *Ss *St *S *S *S *SX KK'"&"9Ar    $~//;E ; ; ; ; ; ; "DM!DN ::<<<<<<<<<KKG    
 1G *,O#D$8$>$>$@$@AA 
] 
]V444]&::-1-D\))J\   $**3////  ] ] ]LL!RTWY[\\\\\\\\] !% 0 0-1-F-Fw-O-O'O'O'O'O'O'O$M9KKC    #44M""))++     +  C$"666 .CCCHHHH(   "LL T #R        7  <o--//  6 *.)@X%%FX  $((<(B(B(D(D#E#E 	 	KC!888 *>>sNSSSS$   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    9D
E
$EE
(H
H3H..H3)K
K5K00K5P/ /
Q9QQ$6S&&S*-S*0` 
`0`++`0b""
c,cc0e 
ee<Ah 
ih>>irH  )r  r   r  r  r:  rI  )r  r  rE  rF  r  s   `    r"   rm  zGatewayRunner.stop  s        	8&*D#%5D"(7D%?&/!!!!!!!FH	T H	T H	T H	T H	T H	TT "-jjll;;or$   c                 H   K   | j                                          d{V  dS )zWait for shutdown signal.N)rL  waitr  s    r"   wait_for_shutdownzGatewayRunner.wait_for_shutdownA   s3      "'')))))))))))r$   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 ]l\  }	}
|	|k    r	 || 	                    |	|
|           d{V z  }.# t          $ r  t
          $ r(}t                              d	|	|d
           Y d}~ed}~ww xY w	 ddlm} |gt          | j                                                  z   } ||           n,# t
          $ r t                              dd
           Y nw xY w|S )u8  Bring up adapters for every non-active profile this gateway serves.

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

        Each profile's adapters are created and connected under that profile's
        HERMES_HOME + secret scope (``_profile_runtime_scope``), stored in
        ``self._profile_adapters[profile]``, and given a message handler that
        stamps ``source.profile`` before delegating to the shared
        ``_handle_message`` — so the agent turn resolves that profile's config,
        skills, and credentials. Same-platform credential collisions (two
        profiles polling the same bot token) are detected and refused here, the
        only point that sees every profile's resolved credentials together.
        r  Fr   )profiles_to_server  r   NT)	multiplexz-Failed to start adapters for profile '%s': %sr~   r  )served_profilesz could not record served_profiles)rS   r  r  r  r  r   r0  rE  _adapter_credential_fingerprint_start_one_profile_adaptersr  r   r5  r  r  r7  r1  r  r  )r  r  r  r  r  claimedrB  _adfpprofile_namer   r  r  serveds                 r"   r  z/GatewayRunner._start_secondary_profile_adaptersE   sS      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 ,$ $       		 (       C !d         	L;;;;;;Xt'='B'B'D'D E EEF  88888 	L 	L 	LLL;dLKKKKK	L s6   % 
33 B==C9C44C9=<D: :&E#"E#r  r   r   r  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          | j                            |i           }d}|j                                        D ]\  }	}
|
j	        s|	j
        t          v r)t	          d| d|	j
         d| d	|	j
         d
| d          t          |          5  |                     |	|
          }ddd           n# 1 swxY w Y   |s|                     |          }|e|                    |	|f          }|Et                              d|||	j
        |	j
                   |                     ||	           d{V  |||	|f<   |                    |                     |                     |                    | j                   |                    | j                   |                    | j                   |                    | j                   |                    |                     |j                             | j        |_        	 t          |          5  |                      ||	           d{V }ddd           n# 1 swxY w Y   |r,|||	<   |dz  }t          !                    d|	j
        |           n=t          "                    d|	j
        |           |                     ||	           d{V  {# tF          $ rI}t                              d|	j
        ||           |                     ||	           d{V  Y d}~d}~ww xY w|S )z>Create+connect one profile's adapters under its runtime scope.r   )r  Nz	Profile 'z
' enables z. Enable GATEWAY_ALLOW_ALL_USERS or the platform allow-all flag for that profile, or change dm_policy/group_policy away from 'open'.z%' enables the port-binding platform 'z', but gateway.multiplex_profiles is on. The default profile owns the single shared HTTP listener and serves every profile through the /p/uP   / URL prefix — a secondary profile cannot bind its own port. Remove platforms.z from profile 'z:'s config.yaml (configure it only on the default profile).u   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.r+   u   ✓ %s connected (profile: %s)u&   ✗ %s failed to connect (profile: %s)u   ✗ %s error (profile: %s): %s)$r  r  r
  r  r  r1  r  r   rE  r'  rQ   _PORT_BINDING_PLATFORM_VALUESr  r  r3   r   r5  r  r  _make_profile_message_handlerr  ro  r  rG  r  r  r  r/  r  r  r   r  r  r  r   r   )r  r  r   r  r  profile_cfg	violationprofile_mapr  r   r  r   r  ownerr  r  s                   r"   r  z)GatewayRunner._start_one_profile_adapters   s5      	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      ,77bII	)4)>)D)D)F)F ?	G ?	G%Ho"* 
 ~!>>>*) ) ) ) ) <H) )
 )1) ) %) ) )	 	 	 (55 J J..xIIJ J J J J J J J J J J J J J J  55g>>B~XrN33$LL- |X^X^   77JJJJJJJJJ*62' ''22<@@   ++D,LMMM%%d&8999,,T-UVVV))$*PQQQ++D,I,I'JZ,[,[\\\&*&:G#G+L99 Z Z$($F$FwPX$Y$YYYYYYYGZ Z Z Z Z Z Z Z Z Z Z Z Z Z Z 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+DD	D	"L1JLJ	L!J	"A.L
M%>M  M%c                       fd}|S )zCReturn a message handler that stamps source.profile then delegates.c                    K   	 t          | dd           | j        j        s| j        _        n# t          $ r Y nw xY w                    |            d {V S )Nr  )rS   r  r  r   r  )r  r  r  s    r"   _handlerz=GatewayRunner._make_profile_message_handler.<locals>._handler   sy      5(D11=elFZ=+7EL(   --e444444444s   )/ 
<<r   )r  r  r  s   `` r"   r  z+GatewayRunner._make_profile_message_handler   s)    	5 	5 	5 	5 	5 	5 r$   c                 J   d}dD ]R}t          | |d          }t          |t                    r*|                                r|                                } nS|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)r  	bot_token_token	api_token
_bot_tokenr   zhermes-mux:r     )rS   r   r7   rT   hashlibsha256encode	hexdigest)r   r  attrvalr  s        r"   r  z-GatewayRunner._adapter_credential_fingerprint   s     O 	 	D'4..C#s## 		 		 	4~~}u4<<WEEFFPPRRSVTVSVWWr$   c                    t          |d          rnt          |j        t                    rT|j                            d| j        j                   |j                            dt          | j        dd                     	 ddlm	} |
                    |j                  rX|                    |j        |          }|t          |d          r| |_        |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    r9d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"}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.}m/}  |            st                              d           dS  ||          S |t$          j0        k    r9ddl1m2}m3}  |            st                              d           dS  ||          S |t$          j4        k    r1ddl5m6}m7} |st                              d           dS  ||          S dS )zCreate the appropriate adapter for a platform.

        Checks the platform_registry first (plugin adapters), then falls
        through to the built-in if/elif chain for core platforms.
        r  r  r  Fr   r  Ngateway_runnerzWPlatform '%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_requirementsz8Signal: 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)8r   r   r  rB   r  r  r  rS   r  r  is_registeredrQ   create_adapterr  r   r5  r   r  r  WHATSAPP_CLOUD gateway.platforms.whatsapp_cloudr  r  r   SIGNALgateway.platforms.signalr  r  WEIXINgateway.platforms.weixinr  r  r  gateway.platforms.api_serverr  r  r  gateway.platforms.webhookr  r  r  !gateway.platforms.msgraph_webhookr  r  BLUEBUBBLESgateway.platforms.bluebubblesr  r  QQBOTgateway.platforms.qqbotr  r  YUANBAOgateway.platforms.yuanbaor  r  )r  r   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   s    67## 	
6<(F(F 	L##)3   L##*%?GG  	\CCCCCC ..x~>> +::8>6RR&
 w(899 615."N 6N  
 t#$  	\ 	\ 	\LLGYZ[[[[[[[[	\ x...        5466 V   t''///((YYYYYYYY,,.. 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##F+++)))\\\\\\\\--// ?@@@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C9  C9 9
D.!D))D.c           	           	 	 ddt           dt          t                    dt          t                    dt          f fd}|S )ud  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.
        Nr  r  r   r   c                 d    | sdS t          |pd|pd|           }                    |          S )NFrR   r   )r   r   r  r  )r  r  )r  r  r   r  r   r  s       r"   checkz5GatewayRunner._make_adapter_auth_check.<locals>.check!  sQ    
  u"!2#.w	  F ++F333r$   rT  )r7   r
   r   )r  r   r  s   `` r"   r  z&GatewayRunner._make_adapter_auth_checko!  sg    $ (,%)	4 	4	4}	4 c]	4 		4 	4 	4 	4 	4 	4 	4 r$   r   c           	      `  K   | j                             |j                  }|sdS t          | dd          }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.Nr  publicget_notice_deliveryprivater  r   r  Fz7[%s] send_private_notice failed, falling back to publicr   r  Tr~   )r0  r3   r   rS   r   r  r  send_private_noticer   r  r   r   r  r   )r  r  r   r   r  notice_deliveryrU   r  s           r"   _deliver_platform_noticez&GatewayRunner._deliver_platform_notice!  s     -##FO44 	Fx.." 	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   :C 6DDc                 [   K   j         }	 ddlm}  |             n,# t          $ r t                              dd           Y nw xY wt           dd          r9t          dd          s(t          d	d          s                                d
S t          t          dd                    }|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          |
t*                    rt-          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|}|rtV          d)z  }tV          d*z  }	 |,                    d+          }|-                    |           |                    |           |.                    d,           n7# t^          $ r*}t                              d-|           d.| cY d
}~S d
}~ww xY w|0                    |d
           tc          |          d/k    r|n|d
d/         d0z   }d1| d2S |rtV          d)z  }tV          d*z  }	 |,                    d+          }|-                    d           |                    |           |.                    d,           t                              d3||           n2# t^          $ r%}t                              d4|           Y d
}~nd
}~ww xY w|0                    |d
           d
}	 dd5l2m3} |4                    |d6          }n# t          $ r d
}Y nw xY w|o|mj%        pd&                                }|rP|5                    d7          s;|6                    ||          }|r#t                              d8||j7                   dS dd9l2m8} |9                    |          } d}!	 dd:l:m;}"  |"|          }!n# t          $ r d}!Y nw xY w| r|!s̉j%        pd&                                }#|#<                    d;          =                                }$'                                }%d
}&|%d<v rd=}&n"|%d>v rd?}&n|%d@v rdA}&n|$dBv rd=}&n|$dCv rd?}&n|$dDv rdA}&|&4|>                    ||                     dE          |&           d
{V }|pdS |?                    |           t          dFdG          }' jA                            |d          }(| jB        v rz|(rwt          jC                    |(z
  }) jB                            |          }*t          dH          }+d},|*rt          |*dI          r	 |*F                                }-|-                    dJt          dH                    }+dK|-                    dLd           dM|+dNdO|-                    dPd           d7|-                    dQd           },n# t          $ r Y nw xY w|'dk    rt          |'dRz  dS          nt          dH          }.|*t          uo|'dk    r|+|'k    p|)|.k    }/|/rKt                              dT||)|+|'|,            I                    |dUV            J                    |           | jB        v r'                                dWk    r K                               d
{V S ddXl(mL}0m)}1 '                                }2|2r |1|2          nd
}3|2r!|3 M                    ||3j*                  }4|4|4S |3r(|3j*        dYk    rt                              dZ|           dS |3r&|3j*        d[k    r N                               d
{V S |3rf|3j*        d\k    r[ O                    ||t          d]^           d
{V  t                              d_|           t          t          d`                    S |3rJ|3j*        dak    r? O                    ||t          db^           d
{V   T                               d
{V S '                                dcv rU                                &                                }5t          t          ddd
                    }6|5s|6sdeS  jV                            |j                  }|rt          d+i d|5df|6rjX        nt          jZ        dgj         dhj[        dij\        ddt          t          ddg           pg           djt          t          djg           pg           dkj^        dlj_        dmj`        dnja        dojb        dpjc        dqjd        dje        drjf        }7 g                    ||7|            h                    | jV                            |j                  s          }8|8dtk    rduS dv|8 dwS |3r|3j*        dxk    rU                                &                                }9|9sdyS  jB                            |          }:|:t          u rZ jV                            |j                  }|r7t          |9t          jZ        j         j\        jd        z          }7|7|ji        |<   d{S |:rt          |:dx          r{	 |:j                    |9          };n8# t          $ r+}<t                              d|||<           d}|< cY d
}<~<S d
}<~<ww xY w|;r(|9d
d~         tc          |9          d~k    rdndz   }=d|= dS dS  jV                            |j                  }|r7t          |9t          jZ        j         j\        jd        z          }7|7|ji        |<   dS |3r|3j*        dk    rdS |3r|3j*        dk    rdS |3rJ|3j*        dv rA|3j*        dk    r k                               d
{V S  l                               d
{V S |3r&|3j*        dk    r m                               d
{V S |3r&|3j*        dk    r n                               d
{V S |3r&|3j*        dk    r o                               d
{V S |3r|3j*        dk    rU                                pd&                                =                                }>|>r|>p                    d
dt          d         nd}?|> p	|>dv p|?dk    }@|@r q                               d
{V S dS |3r|3j*        dk    rdS |3r&|3j*        dk    r r                               d
{V S |3r{|3j*        dv rr|3j*        dk    r s                               d
{V S |3j*        dk    r t                               d
{V S |3j*        dk    r u                               d
{V S |3r|3j*        |0v r|3j*        dk    r v                               d
{V S |3j*        dk    r w                               d
{V S |3j*        dk    r x                               d
{V S |3j*        dk    r y                               d
{V S |3j*        dk    r z                               d
{V S |3rd|3j*         dS jX        t          j{        k    rTt                              d|            jV                            |j                  }|rt          |ji        |           d
S t          t          j~        dd                    }A jA                            |d          }B|j        t          j        k    rŉjX        t          jZ        k    r|Adk    r|Brt          jC                    |Bz
  |Ak    rt                              dt          jC                    |Bz
  |            jV                            |j                  }|r; j        dk    r g                    ||           nt          |ji        |d           d
S  jB                            |          }:|:t          u r'                                d\k    r? J                    |           t                              d|           t          d          S  jV                            |j                  }|rt          |ji        |d           d
S  j        rn                                 r                     |                                            rd                                  dnd                                  dS  j        dk    r3t                              d|                                |           d
S  j        dxk    rډj%        pd&                                }9d}C|9rit          |:dx          rY	 t          |:j                    |9                    }Cn5# t          $ r(}<t                              d||<           d}CY d
}<~<nd
}<~<ww xY w|Crt                              d|           d
S t                              d|                                |           d
S                      |:          r3t                              d|                                |           d
S t                              d|           |:                    j%                   d
S '                                }Dddl(m}Em}Fm)}G |Dr |G|D          nd
}|r|j*        n|D}H|Drd|at           j        t                    r j                            di           pi }Int           j        di           pi }It          |It                    r|D|Iv r|I|D         }J|J                    d          dk    r|J                    dd          &                                }K|Kr|K5                    d7          r|Knd7|K }K|K<                    d7          }LU                                &                                }M|K d |M &                                _%        |Lr|Lp                                d         n|L}D|Dr |G|D          nd
}|r|j*        n|D}H|Dr'|Hr% |F|H          r M                    ||H          }4|4|4S |Drg |F|H          r[U                                &                                }N|j        r|j        j        nd|j        |H|D|N|Nd}O	  j                            d|H |O           d
{V }Pn5# t          $ r(}Qt                              d|H|Q           g }PY d
}Q~Qnd
}Q~Qww xY w|PD ]}Rt          |Rt                    st+          |R                    dd                    &                                =                                }S|Sr|Sdk    ri|Sdk    r8|R                    d          }Tt          |Tt*                    r|Tr|Tc S d|D dc S |Sdk    r2|R                    d          }Tt          |Tt*                    r|Tr|Tnd
c S |Sdk    rt+          |R                    dd                    &                                <                    d7          }U|Us1t+          |R                    dd                    &                                }Vd7|U d |V &                                _%        '                                }D|Dr |G|D          nd
}|r|j*        n|D}H n|Hdak    r[t          j         j        |           d
{V r                                 S  fd}W                     dadd|WĦ           d
{V S |Hdk    r                                d
{V S |Hdk    r v                               d
{V S |HdYk    rt                              d|           dS |Hdk    r w                               d
{V S |Hdk    r x                               d
{V S |Hdk    r                                d
{V S |HdWk    r K                               d
{V S |Hdk    r m                               d
{V S |Hdk    r                                d
{V S |Hd[k    r N                               d
{V S |Hd\k    r                                d
{V S |Hdk    r                                d
{V S |Hdk    r                                d
{V S |Hdk    r                                d
{V S |Hdk    rddlm}X U                                &                                }Y|Yrdnd}Z	  jV                            |j                  }|rE                     |          }[|"                    t+          |j                  |Z|[Ц           d
{V  n,# t          $ r t                              dd           Y nw xY w	  |X|Y          _%        n# t          $ r Y dS w xY w|Hdk    r                                d
{V S |Hdk    r t                               d
{V S |Hdk    r u                               d
{V S |Hdk    r s                               d
{V S |Hdk    r                                d
{V S |Hdk    r                                d
{V S |Hdk    r                                d
{V S |Hdk    r o                               d
{V S |Hdk    r                                d
{V S |Hdk    r                                d
{V }\t          |\dd
          }]|]rt          |\dd          pd}Z|Zr	  jV                            |j                  }|rE                     |          }[|"                    t+          |j                  |Z|[Ц           d
{V  n,# t          $ r t                              dd           Y nw xY w	 |]_%        n6# t          $ r t          |\dd          pd
cY S w xY wt          |\dd          pd
S |Hdk    r                                d
{V S |Hdk    r fdۄ}^dt}_U                                &                                }`|`rS	 t          dttG          |`p                                d                             }_n# tH          tJ          f$ r dt}_Y nw xY w|_dtk    rdnd|_ dޝ}a                     dd|a|^Ħ           d
{V S |Hdk    r                                d
{V S |Hdk    r                                d
{V S |Hdk    r                                d
{V S |Hdk    r                                d
{V S |Hdk    r                                d
{V S |Hdk    r                                d
{V S |Hdk    r                                d
{V S |Hdk    r                                d
{V S |Hdk    r k                               d
{V S |Hdk    r l                               d
{V S |Hdk    r y                               d
{V S |Hdk    r z                               d
{V S |Hdk    r                                d
{V S |Hdk    r                                d
{V S |Hdk    r                                d
{V S |Hdk    r                                d
{V S |Hdk    r                                d
{V S |Hdk    r                                d
{V S |Hdk    r n                               d
{V S |Hdxk    rCU                                &                                }b|bsdS 	 |b_%        n# t          $ r Y nw xY w|Hdk    r q                               d
{V S |Hdk    r	ddlm}cm}d ddlm}e U                                &                                }f|fs
 |c            S 	  |e            }g |dt          |gt                    r|g                    d          ni           }hn# t          $ r  |di           }hY nw xY w|hd         }i	 |f_%         j                            |          _        d|idddd j        |<                        |           d_        n# t          $ r Y dS w xY w|Hdk    r r                               d
{V S |Hdk    r                                d
{V S  j        rd                                  dS |Drt           j        t                    r j                            di           pi }Int           j        di           pi }It          |It                    si }I|D|Iv rU M                    ||D          }4|4|4S |I|D         }J|J                    d          dk    r2|J                    dd          }j|jr	 ddlm}k  |kt          j                                                  }lt          j        |jt          j        j        t          j        j        |l           d
{V }mt          j        |m                                d           d
{V \  }n}o|np|o                                &                                }p|prddlm}q  |q|p          }p|pr|pnd S # t          j        $ r Y dS t          $ r}d| cY d
}~S d
}~ww xY wd|D dS |J                    d          dk    r|J                    dd          &                                }K|Kr|K5                    d7          r|Knd7|K }K|K<                    d7          }LU                                &                                }M|K d |M &                                _%        |Lr|Lp                                d         n|L}Dnd|D dS d|D dS |Dr	 ddl
m}r  |r|D                    dd	                    }s|sraU                                &                                }M |s|M          }tt          j        |t          r|t d
{V }t|trt+          |t          nd
S n3# t          $ r&}t                              d
|           Y d
}~nd
}~ww xY w|Drd}u	 ddlm}vm}w  |w|D          }x|xU                                &                                }y|j        r|j        j        nd
}z |v|x|y||z          }{|{rB|{\  }|}}}~||_%        d}u|~r1t                              d|xd                    |~                     n3# t          $ r&}<t                              d|<           Y d
}<~<nd
}<~<ww xY w|Dr"t                                          dd          s	 ddlm}m}m}  |             ||D          }|>|                             dd          }|j        r|j        j        nd
}|r$|r"ddlm} | ||          v rd| d| dS U                                &                                }y	 ddlm}m}  ||y          \  }}n# t          $ r	 d
}g |y}}Y nw xY w|rH|rFddlm}  ||          fd|D             }|r dd                    |           d| dS |r,|* ||g|||          }|r|\  }|}}}||_%        nd|D dS  |||y|          }|||r||_%        ngt          |D          }|r|S |D                    dd	          |Evr9t                              d|D|j        r|j        j        nd            d!|D 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                              d$|           	 d%S                      ||          \  }}|t                              d&|           |S |"t           d'          si  _        | j        |<   t           jB        |<   t          jC                     jA        |<                                                          |          }	                      |||           d
{V }	 d}t          |t                    r&t+          |                    d(          pd          }nt          |t*                    r|}|&                                rO	  j                            |          }n# t          $ r d
}Y nw xY w|                     |||)           d
{V  n3# t          $ r&}t                              d*|           Y d
}~nd
}~ww xY w|                     |            J                    |           S #                      |            J                    |           w xY w(,  a  
        Handle an incoming message from any platform.
        
        This is the core message processing pipeline:
        1. Check user authorization
        2. Check for commands (/new, /reset, etc.)
        3. Check for running agent and interrupt if needed
        4. Get or create session
        5. Build context for agent
        6. Run agent conversation
        7. Return response
        r   )reset_session_varsz*reset_session_vars failed at handler entryTr~   r  Fru  rX  Nr  pre_gateway_dispatch)r  r%  rG  z*pre_gateway_dispatch invocation failed: %sr  skipz8pre_gateway_dispatch skip: reason=%s platform=%s chat=%sr$  r  rewriter   r   allowz(Ignoring message with no user_id from %sz Unauthorized user: %s (%s) on %sr  r  pairrR   z;Hi~ I don't recognize you yet!

Here's your pairing code: `z5`

Ask the bot owner to run:
`hermes pairing approve rL  ri  z<Too many pairing requests right now~ Please try again later!rl  >   r   rg  rd  >   rk  rl  rj  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)slash_confirmra  z!/>   re  r   rg  rh  once>   rp  rememberrp  >   rk  rl  rm  	nevermindrm  >   approve oncer  rg  >   rp  rq  >   rk  rm  r  
confirm_idrW    r  r  seconds_since_activityz | last_activity=last_activity_descr|  .0fzs ago) | iteration=rx  ry  rS  i   zWEvicting stale _running_agents entry for %s (age: %.0fs, idle: %.0fs, timeout: %.0fs)%sstale_running_agent_evictionr  status)ACTIVE_SESSION_BYPASS_COMMANDSr  r  z3Ignoring /start platform ping for active session %sr  rm  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>r  r  raw_messager  r  r  reply_to_textreply_to_author_idreply_to_author_namereply_to_is_own_message
auto_skillr   r   r  r+   zQueued for the next turn.zQueued for the next turn. (z queued)r  zUsage: /steer <prompt>r   r  r  r  r   u9   Agent still starting — /steer queued for the next turn.zSteer failed for session %s: %su   ⚠️ Steer failed: r  ...u8   ⏩ Steer queued — arrives after the next tool call: 'rY  zSteer rejected (empty payload).u4   No active agent — /steer queued for the next turn.rN  u=   Agent is running — wait or /stop first, then switch models.zcodex-runtimeu>   Agent is running — wait or /stop first, then change runtime.>   rl  rg  rg  agents
backgroundkanbangoal>   rw  rm  r  pauseresumer  unwaitr  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verboser	  r	  footerhelpcommandsr  r  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  rT  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)z!PRIORITY interrupt for session %s)GATEWAY_KNOWN_COMMANDSis_gateway_known_commandr  quick_commandsrl   aliasr  )r   r  r  raw_commandr  r  zcommand:z/command:%s hook dispatch failed (non-fatal): %sdecisionrl  rz   z
Command `/z` was blocked by a hook.handledrb  r  c                  >   K                                    d {V S rr  )_handle_reset_commandr  r  s   r"   	_do_resetz0GatewayRunner._handle_message.<locals>._do_reset$  s-      !77>>>>>>>>>r$   z/newzJThis starts a fresh session and discards the current conversation history.)r  r  r  detailexecutetopicz,Ignoring /start platform ping for session %swhoamir   r  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 rr  )_handle_undo_commandr	  s   r"   _do_undoz/GatewayRunner._handle_message.<locals>._do_undo%  s-      !66u=========r$   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creditsinsightsz
reload-mcpzreload-skillsbundlesr  r  r	  r   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)rM  rN  rO  rP  r  zFailed to prepare MoA turn.r  z) and is not accepting new work right now.execr  )_sanitize_subprocess_envr  rv  r8  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_handlerrE  rZ  z"Plugin command dispatch failed: %s)build_bundle_invocation_messageresolve_bundle_command_key)task_idr   z$Bundle %s skipped missing skills: %sr}  zBundle dispatch failed: %s_bundle_handled)get_skill_commandsbuild_skill_invocation_messageresolve_skill_command_keyrt   )get_disabled_skill_namesr!   rg  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 )rt   rR   rV  )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Vr$   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 /rE  uO   Unrecognized slash command /%s from %s — replying with unknown-command noticer  zUnknown command `/zl`. Type /commands to see what's available, or resend without the leading slash to send as a regular message.z*Skill command check failed (non-fatal): %su;   Refusing new turn for session %s — external drain active.u   ⏳ This agent is draining for a maintenance action and isn't accepting new turns right now. It'll be back in a moment — please resend shortly.z@Rejecting new active session %s: max_concurrent_sessions reachedrY  final_response)r"  r  rK	  z!goal continuation hook failed: %sr   )r  gateway.session_contextr  r   r   r  rS   rV  r   r  r  r  rG  r   r   rB   r3   r  r   rQ   r   r7   r2  r   r  r  r  r  _get_unauthorized_dm_behaviorr  rv  _is_rate_limitedgenerate_coderV  r   _record_rate_limitr  r   rT   get_commandr   r  rt   r  with_suffixr  r  r6   r  r   toolsr  get_pending_for_sessionrr  !resolve_text_response_for_session
clarify_idr  get_pendingr  rb  ry  r8   r/   clear_if_staler  r  rX  r  r   r   r  r  r7  "_invalidate_session_run_generationrR  _handle_status_commandr  _check_slash_access_handle_restart_command_interrupt_and_clear_session_INTERRUPT_REASON_STOPr  r   _INTERRUPT_REASON_RESETr	  get_command_argsr0  r  r  r  rW  r  r  rY  r  r  r  r  r  r  r   ru  r   r  r  rZ  r  r  r  _handle_agents_command_handle_background_command_handle_kanban_commandrM  _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_commandr  r  r1   r  r  r  r  r  r  rY  r  rK  r  r	  r	  r  rx  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_promptr$	  r  _handle_fast_command_handle_model_command_handle_codex_runtime_command_handle_personality_command_handle_suggestions_command_handle_blueprint_command_handle_retry_commandr   r   
IndexError_handle_set_home_command_handle_compress_command_handle_usage_command_handle_credits_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_configr6	  r7	  r  r  r  _moa_restore_overrider  _moa_disable_after_turn_handle_voice_commandtools.environments.localr;	  r2   r  create_subprocess_shellr=  r>  r?  r@  rB  r   r   r  r<	  r  agent.skill_bundlesr=	  r>	  rA   localsagent.skill_commandsrA	  rB	  rC	  rk  rD	  rE	  rF	  ru  r  r  r  rD  rY  r  _begin_session_run_generation_handle_message_with_agentr  _post_turn_goal_continuation_restore_moa_one_shot)r  r  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_slash_confirm_mod_pending_confirm_tool_approval_liverb  
_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  rq   r  rE  acceptedr[   preview	_goal_arg
_goal_verb_is_control_telegram_followup_grace_started_atr  r  r	  r	  _resolve_cmd	canonicalr	  qcmdr  target_command	user_argsr  hook_ctxhook_results	_hook_errhook_resultr	  rz   r  new_argsr	  r$	  
_learn_req_ack	_ack_meta_blueprint_result_blueprint_seedr-	  _undo_n	_undo_raw_undo_detailsteer_payloadr6	  r7	  r  moa_payloadr  moa_cfgpresetexec_cmdr;	  sanitized_envrD  r6  r7  r  r   r<	  plugin_handlerr  r@	  r=	  r>	  
bundle_keyuser_instruction_bundle_platbundle_resultr  _loadedmissingrA	  rB	  rC	  cmd_key_skill_namerB  _get_plat_disabled_build_stackedrF	  
extra_keysstacked_instruction_disabled_extrastacked_result_missing_unavail_msg_active_session_lease_limit_message_run_generation_agent_result_final_textr"  	_goal_excrH	  rI	  s   ``                                                                                                                                                   @@r"   r  zGatewayRunner._handle_message!  s>      	VBBBBBB     	V 	V 	VLLEPTLUUUUU	V D8%@@	E:u55	 E#CUKK	
 --e4444 75*e<<==  	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$?   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-++FO<< 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))*dm>O>OPVP_>`>`)aaA::66DUDDDD  'N."5"@"@"3355;;==
! 433 $ 4 8 8 D D $;;;"m//@@G M'3!+)4)9#(<','7+0+?( ( ( 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<<-++FO<< 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."59L"L"L!&&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-++FO<< ^/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+-  
 -++FO<< 	,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 -++FO<< /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
 ('-"A"A (("&}':'::'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LL<jIII##EJ/// 4 ##%%	
 	
 	
 	
 	
 	
 	
 	
 	
 	
 -4=<<(((%-:HMM7	  	Kx'$+t,, R!%1A2!F!F!L"!(6F!K!K!Qr.$// KG~4M4M%g.88F##w..!XXh3399;;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-++FO<< 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"&-"3"3FO"D"D" ^(,(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:::::::::	!!55e<<<<<<<<<
""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  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!XXh3399;;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0	:"&"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 $$&& 
-(,(:(P(PQW(X(X$ - - -(,-$0"??*7#)+6 @         
  M M M@)LLLLLLLLM  &&uj999 --j9999 &&uj999 --j9999s:    &A	A	C) )
D3DD4P; ;Q
	Q
Q' 'Q65Q6AS- -
T!7TT!T!9A1W+ +
X5XX6Y Y#"Y#5\ \\5Bc8 8
ddv) )
w3 wwwR	"AR, R,
ASR6ASSAS_$A_6 _6
A`(` A`#`#A`(qA&Ar5 r5&AssAss"As3 s3
Att Aty8A&A{ {&A||A||A| |A|4|3A|4~"6A A10A1KBK K
BKKBKM?BN NBNNBNN+ABO> O>
BPPBPT5CBX XBYX)	BYX2BX=X7BYX=BY\7B
B_ _
B_3_B_._.B_3_;B%Bb! b!
Bcb+BccBcc=A:Bk e8&Bk fBf7 f6Bk f7Bg
gBk g	Bg
g
ABk h-Bk i,Bk i2ABk k
Bk6kBk1k1Bk6pBu p>A(Bs6 r'Bs sBs6 sBssBs6 sBss$Bs6 s5Bu s6
Bt&t Bt!tBu t!Bt&t&Bu u-Bv	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	  )rS   r  r  r  r   )r  r  r	  _restores       r"   r	  z#GatewayRunner._restore_moa_one_shotg'  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)rG  r-  c                   K   |pg }|j         pd}t          | j        dd          }t          | j        dd          }|p|                     |          }|                     |           t          |||          }|r|j        rd|j         d| }t          |d	d
          r|j         d| }g }	g }
|j        rg }g }t          |j                  D ]\  }}|t          |j                  k     r|j        |         nd}t          ||          r|                    |           |j        t          j        k    r|	                    |           n^|j        t          j        k    s4|                    d          r4|j        t          j        t          j        hvr|                    |           |                    d          s|s*|j        t          j        k    r|
                    |           |r|                     ||          }|dk    rWt          | dd
          }|	i }|| _        t/          |          ||<   t0                              dt          |                     nEt0                              d|t          |                     |                     ||           d
{V }|r|                     ||           d
{V \  }}|r|                                 r| j                            |j                  }|                      || !                    |                    }|r_|D ]\}	 |"                    |j#        d| d|           d
{V  +# tH          $ r%}t0          %                    d|           Y d
}~Ud
}~ww xY w|	rddl&m'} |	D ]}tP          j)        *                    |          }|+                    dd          }t          |          dk    r|d         n|}tY          j-        dd|          } ||          }d| d| d}| d | }|
rddl&m'} |
D ]}tP          j)        *                    |          }|+                    dd          }t          |          dk    r|d         n|}tY          j-        dd|          } ||          }d!| d| d"}| d | }|j        rndd
l.}ddl&m'}  h d#}!t          |j                  D ]J\  }}t          ||          s t_          ||          sta          ||          r7|t          |j                  k     r|j        |         nd}|d$v r]tP          j)        1                    |          d%         2                                }"|"|!v rd&}n|3                    |          \  }#}$|#r|#}nd'}tP          j)        *                    |          }%|%+                    dd          }&t          |&          dk    r|&d         n|%}'tY          j-        dd|'          }' | |          }(ti          |'|(|          })|) d | }L|Mt          |d(d
          tj          j6        k    r.t          |d)d
          rdd*l7m8}*  |*            rd+|j9         d,| }t          |d-d
          r8|j:        r1|j;        d
d.         }+t          |d/d          r	d0|+ d1| }nd2|+ d1| }d3|v r	 dd4l<m=}, dd5l>m?}- tP          j@                            d6tP          j)        A                    d7                    }.t                      }/d
}0	 t                      }1|1                    d8i           }2t          |2t                    r&|2                    d9          }3|3t          |3          }0n# tH          $ r Y nw xY w |-| jG        | jH        p|/                    d:          pd|/                    d;          pd|0<           d
{V }4 |,||.|4|.=           d
{V }5|5jI        r^| j                            |j                  }6|6r;|6"                    |j#        d>J                    |5jK                  pd?           d
{V  d
S |5jL        r|5jM        }n2# tH          $ r%}7t0          %                    d@|7           Y d
}7~7nd
}7~7ww xY w|S )Aa  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.
        rR   r  Tr  Fr  [rB  channel_contextNz

[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.	   🎙️ "rX  r   &Transcript echo failed (non-fatal): %sr   )to_agent_visible_cache_pathrE  rV  rU  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>   rR   application/octet-streamr+   z
text/plainr
  r   r  )_discord_tools_loadedz[Triggering message id: `uG   ` — use as `message_id` for reply/react/pin via the discord tools.]

r  r,  r  z%[Replying to your previous message: "z"]

z[Replying to: "@)#preprocess_context_references_async)get_model_context_length_asyncr  ~rN  context_lengthrO  rP  )rO  rP  config_context_length)r  r
  allowed_rootr   zContext injection refused.z(@ context reference expansion failed: %s)Nr   rS   r  r  #_consume_pending_native_image_pathsr  r  r
  r  r  r   r  r  r4   r  r  r  r  rr  DOCUMENTr	  _decide_image_input_moder]  rY  r   r  _enrich_message_with_vision"_enrich_message_with_transcription_should_echo_stt_transcriptsr0  r3   r   r  r  r   r   r   r  tools.credential_filesr
  r1   r;   basenamerM  r   r   	mimetypesr  r
  r9  r8   
guess_typer  r  DISCORDr  r
  r  r  r  agent.context_referencesr
  agent.model_metadatar
  r2   r  r  r~  r   rB   r   _model	_base_urlblockedrA   warningsr  rz   )8r  r  r  r-  rG  message_text_group_sessions_per_user_thread_sessions_per_user_is_shared_multi_useraudio_file_pathsvideo_pathsimage_pathsaudio_pathsr  r;   r   	_img_modepending_native_successful_transcripts_echo_adapter
_echo_meta_tx	_echo_exc_to_agent_path_apath	_basenamerA  _display_agent_path_note_vpath
_mimetypesr
  _TEXT_EXTENSIONS_extguessedrE  r!
  r  r  r  context_note_disc_tools_loadedreply_snippetr
  r
  _msg_cwd_msg_runtime_msg_config_ctx_msg_cfg_msg_model_cfg_msg_raw_ctx_msg_ctx_len_ctx_resultr  r[   s8                                                           r"   _prepare_inbound_message_textz+GatewayRunner._prepare_inbound_message_text|'  s     * -Rz'R#*4;8QSW#X#X $+DK9SUZ$[$[! "IT%A%A&%I%I 	00=== <$<%>!
 !
 !

 ! 	BV%5 	BAv/AA<AAL
 5+T22 	W#3VVVVL ')!# K	"KK$U%566 - -401C8I4J4J0J0J)!,,PR )22 -&&t,,, %):::$++D1111';+<<<$$X.. =*;3DkFZ2[[[&&t,,,##H-- -e -@RVaVg@g@g&&t,,,  !99! + :  	 ((%,T3[]a%b%bN%-)+FTC26{2C2CN;/KKmK((   
 KKf!3{#3#3   *.)I)I$#* * $ $ $ $ $ $L
  ">B>e>e ? ? 9 9 9 9 9 955 + "t/P/P/R/R "$(M$5$5fo$F$FM!%!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,'N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    D%C%CK!^Q|/?/?
/K/KQr(,,Y77=2*9	& & &             %H$G  #/!)	% % %       &  #}00AAH &mm"N IIk&:;;[?[          4' 7#.#6L N N NGMMMMMMMMN s]   0'M
N"NN>Aa A]8 7a 8
^a ^Ca a 
b&bbc                 v    t          | dd           }|sg S t          |                    |g           pg           S )Nr]  )rS   rY  r  )r  rG  r4
  s      r"   r
  z1GatewayRunner._consume_pending_native_image_paths(  sE     'OQUVV 	IN&&{B77=2>>>r$   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)	Nrb  z*Failed to cache live session source for %sTr~   rc  r  F)r  )rS   r   rb  r2  r   r   r   r  move_to_endr   popitem)r  rG  r  cached_sourcesmax_sizes        r"   _cache_session_sourcez#GatewayRunner._cache_session_source(  s-    	fnF '94@@!(]]N$2D!	*5*=f*E*EN;'' 	 	 	LLE{]aLbbbFF		&&{333t%;SAAHn%%00&&E&222 n%%000000 	 	 	DD	s$   A 'A32A37A"C 
C+*C+c                     |sd S t          | dd           }|sd S |                    |          }|'	 |                    |           n# t          $ r Y nw xY w|S )Nrb  )rS   r3   rS
  r   )r  rG  rU
  r  s       r"   r  z(GatewayRunner._get_cached_session_source(  s     	4 '94@@ 	4##K00**;7777   s   A 
AAr	  run_generationc                 N  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                            |          }|j        }|                     ||           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|}|r*||j        k    r| j                            ||          }||}|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          }|r| j"        #                    |d           | $                    |d           t          | d          r| j%        #                    |d           t          | dd          }||#                    |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  t[          || j.        |          }| /                    |          }d}d}d}	 ta                      }tc          |                    d          pi                     dd                    }n# t&          $ r Y nw xY wte          ||          }|rt          |d d          pd!}|d"k    rd#}n|d$k    rd%}nd&}|d'z   |z   }	 | j        j.        3                    |j        t          |d(d)          *          }|j        r|j        j        nd}t          |d+d          }|d"k    p|j4        o
|o||j5        v} | r| j6                            |j                  }!|!r|d"k    rd,}"nA|d$k    rd-|j7         d.}"n/|j8        d/z  }#|j8        d/z  }$|$s|# d0n|#r|# d1|$ d2n|$ d2}%d3|% }"d4|" d5}&	 | 9                                }'|'r|& d'|' }&n# t&          $ r Y nw xY w|!:                    |j        |&| ;                    |          6           d{V  n2# t&          $ r%}(t                              d7|(           Y d}(~(nd}(~(ww xY wd|_<        t          |d8d          })|r2|)r/t{          |)t                    r|)gnt}          |)          }*	 d9d:l?m@}+mA}, g }-g }.|*D ]r}/ |+|/|;          }0|0rF|0\  }1}2}3d<|3 d=}4 |,|1|2|4          }5|5r*|-B                    |5           |.B                    |/           Wt          C                    d>|/           s|-rP|-B                    |j                   d'D                    |-          |_        t          	                    d?|.|           n3# t&          $ r&}(t          C                    d@|*|(           Y d}(~(nd}(~(ww xY w| j        E                    |j                  }6|6rt          |6          dAk    rd9dBlGmH}7mI}8 dC}9dD}:d};dE}<d}=d}>d}?d}@i }A	 ta                      }A|Ar|A                    dFi           }Bt{          |Bt                    r|B}9nt{          |Bt                    r|B                    dG          p|B                    dF          p|9}9|B                    dH          }C|C(	 t          |C          }=n# t          t          f$ r Y nw xY w|B                    dI          pd}>|B                    dJ          pd}?|A                    dKi           }Dt{          |Dt                    r~t	          |D                    dLd                    N                                dMv };|D                    dN          }E|E0	 t          |E          }F|Fd9k    r|F}<n# t          t          f$ r Y nw xY w	 | O                    ||t{          |At                    r|AndO          \  }9}G|G                    dI          p|>}>|G                    dJ          p|?}?|G                    dP          p|@}@n# t&          $ r Y nw xY w|=I|?rF	 	 d9dQlPmQ}H  |H|A          }In<# t&          $ r/ |A                    dR          }It{          |It|                    sg }IY nw xY w|ID ]}Jt{          |Jt                    s|J                    dJ          pdR                    dS          }K|Kr|K|?R                    dS          k    r~|J                    dTi           }Lt{          |Lt                    rQ|L                    |9i           }Mt{          |Mt                    r&|M                    dH          }N|Nt          |N          }= nn# t          t          f$ r Y nw xY wn# t&          $ r Y nw xY w|;r |8|9|?pd|@pd|=|>pdU           d{V }Ot          |O|:z            }Pt          |OdVz            }Qt          |6          }R|jS        }S|Sd9k    r|SdW}Tn |7|6          dX}T|<}U|Pk    p|R|Uk    }V|Vrt          	                    dY|RdZ|Tt          |:d[z            |OdZ|PdZ           | ;                    || T                    |                    }W	 d9d\lUmV}X | O                    ||t{          |At                    r|AndO          \  }9}G|G                    dP          rd] |6D             t                    dAk    r |Xdi |G|9dAddd^g|j        t          | j        d_| j                  d`	 d_W        da _X        t          jY                    }Y|YZ                    dfdb           d{V \  }Z}[j        }\|\|j        k    }]tc          t          dcd                    }^|]rC|\|_        | j        [                                 t          j        | j         ||dd           d{V  |]s|^rD| j        \                    |j        |Z           d9|_S        |Z}6t          |Z          }_ |7|Z          }`n$|R}_}`t          C                    de|j                   t          	                    df|R|_dZ|`dZ           |`|Qk    rt          C                    dg|`dZ           t          dhd          }a|at          |adid          rt          |adjd          pdk}bdl|b dm}c	 | j6                            |j                  }d|dr*|j        r#|d:                    |j        |c|W6           d{V  n# t&          $ r%}et          C                    dn|e           Y d}e~end}e~eww xY w|at          |adod          rt          |adod          }ft          |adpd          pdk}gdq|f dr|g ds}h	 | j6                            |j                  }d|dr*|j        r#|d:                    |j        |h|W6           d{V  n2# t&          $ r%}et          C                    dt|e           Y d}e~end}e~eww xY w| &                    |           | ]                    duv           d{V  n7# | &                    |           | ]                    duv           d{V  w xY wn2# t&          $ r%}(t          C                    dw|(           Y d}(~(nd}(~(ww xY w|6s| j        ^                                sdx}i	 d9dyl_m`}jma}kmb}lmc}mmd}n ta                      }o |n|o          dzk    r. |k|o|j          s"| |m            z  } |lt          d{z  |j           n||iz  }n7# t&          $ r*}pt                              d||p           ||iz  }Y d}p~pnd}p~pww xY w|6s|j        r|j        t          jg        k    r|j        t          jh        k    r|j        j        }t          |          }qt          jk        |q          sP|j        t          jl        k    rd}nd~}rd|m                                 d|r d}&| n                    ||&           d{V  |j        t          jo        k    rl| j6                            t          jo                  }!| p                    |          }s|sr1|!r/t          |!d          r|!q                    |s          }t|tr|d'|t z  }| r                    |||6|           d{V }u|udS 	 d9dlsmt}v d9dlumv}wmw}xmx}y  |v            }zt          |dd          }{|urft{          |ut                    rQ |y|u|z          \  }|}}||} |w|{|z          }~|~|~n|}}t          ta                                r |x||||z          }un||}un2# t&          $ r%}t                              d|           Y d}~nd}~ww xY w| z                    | j6                            |j                  ||           	 |j        r|j        j        nd|j        |j        pdt          |dd          rt	          t          |dd                    ndt          |d(d          pd|j        |udd         d}| j+        ,                    d|           d{V  |j        }| {                    |u||6||||| T                    |          |j|        t          |dd          ||           d{V }	 | j6                            |j                  }|r0t          |d          r |}                    |j                   d{V  n# t&          $ r Y nw xY w| ~                    ||          st          	                    d|pd|           | j6                            |j                  }t          t          |          dd          |                    ||           n-|r+t          |d          r|j        #                    |d           	 |                     |           dS |                    d          pd}	 d9dlm}  |||          }n# t&          $ r d}Y nw xY w|dk    r|sd}|                    dg           }t          j                     |z
  }|                    dd9          }t          |          }t          	                    d||j        pd
|||           |rtt          |          rd|                     |           	 | j                            |           n3# t&          $ r&}t                              d||           Y d}~nd}~ww xY w|s6t          ||t          |6                    }t          |j        |          }|                    d          r|d         |j        k    r|j        |k    rk|d         |_        | j        [                                 | j                            |j        ||           t          j        | j         ||d           d{V  n$t          	                    d|pd||j                   	 t          ta                      t          |j                  dtc          t          | dd                    |j        t          j        h          }n8# t&          $ r+ |j        t          j        k    rdnt          | dd          }Y nw xY w|rq|rn|sk|                    d          }|rS|                                                                }t          |          dk    r7dD                    |dd                   }|dt          |          dz
   dz  }n|                                }	 d9dlm}  |ta                      t          |j                  dd          }n# t&          $ r d}Y nw xY w|dk    r:dD                    d |                                D                       }d| d'| }nH|dk    r:dD                    d |                                D                       }d| d'| }nd| d| }d}	 d9dlm}  |ta                      t          |j                  |                    dF          |                    dd9          pd9|                    dH          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  	 d9dlm} |j        }g |_        t1          |          D ]O\  }}t          j        |                     |                     |d[z  dk    rt          j        d9           d{V  Pn2# t&          $ r%}(t                              d|(           Y d}(~(nd}(~(ww xY w	 d9dlm} t;          |j                  }|D ]d}t?          |          }|rP	 |                     ||           d{V  2# t&          $ r%}t                              d|           Y d}~\d}~ww xY wen2# t&          $ r%}(t                              d|(           Y d}(~(nd}(~(ww xY wtc          |                    d                    }t	          |                    dd                    N                                |oTtc          |                    d                    p2tC          fddD                       pdĉv ot          |6          dk    }|r!t          	                    d|j                   n"|r t          	                    d|j                   |                    d          r|r|rt          	                    d|j                   | j                            |          }| &                    |           | j"        #                    |d           | $                    |d           t          | d          r| j%        #                    |d           t          | dd          }||#                    |d           |%|}t          j        | j         ||dɬ           d{V  |pddz   }t          j                     }|rn`|6s^|                    dg           }| j                            |j        d|pg tI                      |j        r|j        j        nd|d͜           |                    d| j        du          }|rn|rd||n|u||n|dМ}|j        rt	          |j                  |d<   |j        o1| j                            |j        t	          |j                            }|r(t          	                    d|j        |j                   ni| j                            |j        ||Ӧ           nE|                    dt          |6                    }t          |          |k    r
||d         ng }|swd||n|u||n|dМ}|j        rt	          |j                  |d<   | j                            |j        ||Ӧ           |r&| j                            |j        d||dМ|Ӧ           nd}|D ]}|                    d֦          dk    ri |d|i}|s=|                    d֦          dk    r$|j        rd|vrt	          |j                  |d<   d}| j                            |j        ||Ӧ           | j                            |j        |                    dd9          ئ           |                     ||j                   d{V  |r"t          	                    d|j                   d}tc          |                    d                    }|                     ||||ڦ          r|                     ||           d{V  |                    d          r|                    d          s|r>| j6                            |j                  }|r|                     |||           d{V  |r	 | j6                            |j                  }|rJ|:                    |j        || ;                    || T                    |                    6           d{V  n2# t&          $ r%}t                              d|           Y d}~nd}~ww xY w	 |                     |           dS ||                     |           S # t&          $ r$}(	 | j6                            |j                  }|r0t          |d          r |}                    |j                   d{V  n# t&          $ r Y nw xY wt                              d|           	 dݐt[                      v r|u|d}	 | j        E                    |j                  }n# t&          $ r g }Y nw xY wt]          |dd                   D ]<}|                    d֦          dk    r!||n|u}|                    dߦ          |k    } n=|sgd||n|u||nt          j                     dМ}t          |dd          rt	          |j                  |d<   | j                            |j        |           n,# t&          $ r t                              dd           Y nw xY wd}t          |(dd          }dt[                      v rt          |6          nd9}|dk    rd}n|dk    rd}n|dk    rt          |(dd          }i }	 |?|                                                    di           }t{          |t                    si }n# t&          $ r Y nw xY w|                    d          dk    rC|                    d          }|r)|d9k    r#d9dl}|                    |dz            }d| d}n=d}n:d}n7|dk    rd}n.|dv r*|dk    r	 Y d}(~(|                     |           dS |dk    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.rQ   rR   NP   r   rL  r  r  zSinbound message: platform=%s user=%s chat=%s msg=%r reply_to_id=%s reply_to_text=%rr  z1telegram topic recovery: chat=%s user=%s %r -> %sr1  r   r  z%Failed to read Telegram topic bindingTr~   r  z$compression-tip lookup failed for %szcompression-tip-walkr  z'Failed to record Telegram topic bindingwas_auto_resetFr0  r[  is_fresh_resetzsession:start)r   r  r  rG  privacy
redact_pii)r`
  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.]zy[System note: The user's previous session expired due to inactivity. This is a fresh conversation with no prior context.]r\  r  r  )r   session_typereset_had_activityz+previous session was stopped or interruptedzdaily schedule at z:00r  hzh r   zinactive for u!   ◐ Session automatically reset (z). Conversation history cleared.
Use /resume to browse and restore a previous session.
Adjust reset timing in config.yaml under session_reset.r   z.Auto-reset notification failed (non-fatal): %sr  r   )_load_skill_payload_build_skill_messagerJ	  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   )estimate_messages_tokens_roughr
  zanthropic/claude-sonnet-4.6g333333?i  rN  r   r
  rM  rO  compressionr'  >   r   r   r   hygiene_hard_message_limitr4  rP  get_compatible_custom_providerscustom_providersr   models)rO  rP  r
  rM  ffffff?actual	estimateduf   Session hygiene: %s messages, ~%s tokens (%s) — auto-compressing (threshold: %s%% of %s = %s tokens),r  AIAgentc                 @    g | ]}|                     d           dv |S )r  >   r:  r4  r  rV  r  s     r"   r`  z<GatewayRunner._handle_message_with_agent.<locals>.<listcomp>*  s8     ) ) )&'#$55==4Q#Q#Q !"#Q#Q#Qr$   r!	  rr  )rN  ry  
quiet_modeskip_memoryenabled_toolsetsr  r	  c                      d S rr  r   )akws     r"   r   z:GatewayRunner._handle_message_with_agent.<locals>.<lambda>*  s    D r$   c                  4                         d           S )NrR   )approx_tokens)_compress_context)_approx_tokens
_hyg_agent	_hyg_msgss   r"   r   z:GatewayRunner._handle_message_with_agent.<locals>.<lambda>*  s%    
0L0L,5r:H 1M 1* 1* r$   _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context_compressor_last_compress_aborted_last_summary_errorr  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 hygiener  z(Session hygiene auto-compress failed: %sz

[System note: This is the user's very first message ever. Briefly introduce yourself and mention that /help shows available commands. Keep the introduction concise -- one or two sentences max.])PROFILE_BUILD_FLAGr  r  profile_build_directiveprofile_build_modeaskr  z@Profile-build onboarding directive failed, using plain intro: %sz/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.get_voice_channel_contextr  r  r-  rG  r/  )coerce_message_timestampr1   strip_leading_message_timestampsr   r5  z2Message timestamp injection failed (non-fatal): %sr  r,  )r   r  r   r  r  r  rz   zagent:start_moa_config)rz   context_promptr-  r  r  rG  rY
  r   r   
moa_configpersist_user_messagepersist_user_timestampstop_typinguK   Discarding stale agent result for %s — generation %d is no longer currentr  pop_post_delivery_callback
generation_post_delivery_callbacksrK	  )#is_intentional_silence_agent_result(empty)u   ⚠️ The model returned no response after processing tool results. This can happen with some models — try again or rephrase your question.r~  r  zMresponse ready: platform=%s chat=%s time=%.1fs api_calls=%d response=%d charsz&clear_resume_pending failed for %s: %sr  zagent-result-compressionz{Skipping agent-result session split sync for %s because the session binding moved from %s to %s before compression finishedr&  r>  r   last_reasoning   z
_... (z more lines)_r   reasoning_styler	  subtextc              3   (   K   | ]}|rd | ndV  dS )z-# z-#Nr   r   lns     r"   ru  z;GatewayRunner._handle_message_with_agent.<locals>.<genexpr>,  sB       , ,;="6J"JJJ$, , , , , ,r$   u   -# 💭 Reasoning

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

)build_footer_linelast_prompt_tokensr  )r   r   rN  context_tokensr
  r  zruntime_footer build failed: %salready_sentz	agent:endr  r  r  zProcess watcher setup error: %s&Watch notification injection error: %szWatch queue drain error: %sr  r5  compression_exhaustedc              3       K   | ]}|v V  	d S rr  r   )r   r  _err_str_for_classifys     r"   ru  z;GatewayRunner._handle_message_with_agent.<locals>.<genexpr>,  s9        aq11      r$   )zcontext lengthzcontext sizezcontext windowzmaximum contextztoken limitztoo many tokenszreduce the lengthzexceeds the limitzrequest entity too largezprompt is too longzpayload too largezinput is too longr  r  zjSkipping transcript persistence for context-overflow failure in session %s to prevent session growth loop.up   Transient agent failure in session %s — persisting user message so conversation context is preserved on retry.z7Auto-resetting session %s after compression exhaustion.z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.rS	  r2  )r  rS	  rN  r   r   agent_persistedr4  )r  r   r   r  z:Skipping duplicate user turn (message_id=%s) in session %s)skip_dbr  r  r  r3  )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  rl   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   )r  r   r   rQ   r7   r   r   rS   r   r  r  r  r   r:  r;  r/  r  r2  r  r   rG  r  rG  rW
  r  rp  get_telegram_topic_bindingr  r3   get_compression_tipr  r  r&  r#  r  r  r  r0  r  r]
  
created_atri  r^
  rx  r  r  r  _set_session_envr~  r   r  get_reset_policynotifynotify_exclude_platformsr0  at_houridle_minutes_format_session_infor   r  ra
  r   rY  r	  rg
  rh
  r4   r   rA   load_transcriptr   r&
  ri
  r
  rB   r   r  r   r8   rE  r  rm
  rc  r
  r  	run_agentru
  r  	_print_fnr  run_in_executorr  rewrite_transcriptr  has_any_sessionsr  r
  r  r  r
  r
  r  r  rx  r  r  r1   r  SLACKr  r  r$
  _get_guild_idr
  rP
  rC  r0  rD  r
  r1  r
  r*  _bind_adapter_run_generation
_run_agentr   r
  _is_session_run_currentrl   r
  r
  _clear_session_envgateway.response_filtersr
  r  r  ro  r  r   _record_gateway_session_peerr   ry  
MATTERMOSTrT   r\  r   r   gateway.runtime_footerr
  r2   r  r  r{  r  rI  r  r  r5  r  r  r  _inject_watch_notificationr  reset_sessionappend_to_transcriptr  r  has_platform_message_idupdate_session"_refresh_agent_cache_message_count_should_send_voice_reply_send_voice_reply_deliver_media_from_responsery   r	  rh  r  mathceil)r  r  r  r	  rY
  _msg_start_time_platform_name_msg_preview	_reply_id
_reply_txtr.  r"  rG  bindingbound_session_idcanonical_session_idr'  _was_auto_resetrH  _is_new_sessionrw   _session_env_tokens_redact_piir
  r
  _pcfgr
  reset_reasonrE
  policyr  had_activityshould_notifyr   reason_textr  minsdurationr   session_infor  _auto_skill_namesrg
  rh
  _combined_parts_loaded_names_snamer	  _loaded_skill
_skill_dir_display_namer?
  _partr-  ri
  r
  
_hyg_model_hyg_threshold_pct_hyg_compression_enabled_hyg_hard_msg_limit_hyg_config_context_length_hyg_provider_hyg_base_url_hyg_api_key	_hyg_data
_model_cfg_raw_ctx	_comp_cfg_raw_hard_limitr  _hyg_runtime_gw_gcp_hyg_custom_providers_cp_cp_url
_cp_models_cp_model_cfg_cp_ctx_hyg_context_length_compress_token_threshold_warn_token_threshold
_msg_count_stored_tokens_token_source_HARD_MSG_LIMIT_needs_compress	_hyg_metaru
  rv   _compressedrE  _hyg_new_sid_hyg_rotated_hyg_in_place
_new_count_new_tokens_comp_err	_warn_msgr  _werr
_aux_model_aux_err_aux_msg_intro_noter
  r  r  r
  r
  _onb_cfg_pb_errenv_keysethome_cmdguild_id
vc_contextr+
  _get_evt_tz_coerce_msg_tsrJ  _strip_msg_ts_evt_tz_evt_ts_clean_message_text_embedded_ts_event_epoch_ts_errr	  _run_start_session_idr  _typing_adapter_stale_adapterr  r
  _intentional_silenceagent_messages_response_time
_api_calls	_resp_lenr  _show_reasoning_effectiver
  linesdisplay_reasoningr   _reasoning_style_quoted_footer_line_bfl_footer_errr  r  r  r  _pr_watch_eventsr  
synth_texte2agent_failed_earlyis_context_overflow_failure	new_entryri  	tool_defsr
  _user_entry_skip_persistr  r  _user_msg_id_attachedr  r  _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_inr
  _hoursr
  r
  r
  r
  s                                                                                                                                                                                                @@@@r"   r	  z(GatewayRunner._handle_message_with_agent(  s5     )++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%    *@@HH#/"";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  $1@@N^__H+(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
 )--k4@@@00dCCCt344 A)--k4@@@
 4!7>>Dd+++ $$[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	 6g+VVV  =	3"=2EtLLVPVL{**  [((  f  [)F2^CN+R+2CC#_!(d!C!C D   :@ P 5 5b&}6JERR !- ; !M M$M%V-LL 
 ! "m//@@G ';66*WKK)W44*Rv~*R*R*RKK$*$72$=E#)#6#;D:>'p%{{{{[`DpuDWDWPTDWDWDWDWimfpfpfpH*D(*D*DKW W W W !+/+D+D+F+FL+ 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 $44]5MNN"  _	s7||q((        7J!%'+$"&)-& M MLIN022	 "%!*w!;!;J!*c22 K%/

#J55 K%/^^I%>%>%g*..QXBYBY%g]g
 $.>>2B#C#C#/%=@]] : :$-z#: % % % $% )3z(B(B(Jd(2z(B(B(Jd
 !*mR @ @I!)T22 %36%MM)T::4 4%''%94:0 +4--8T*U*U*6%*-o*>*>#*Q;;:A$7$-z#: % % % $%
/3/R/R%$/1;It1L1L$VIIRV 0S 0 0,J
 %1$4$4Z$@$@$QMM$0$4$4Z$@$@$QMM#/#3#3I#>#>#N,LL    D .5-5;dddddd4;GI4F4F11( ; ; ;4=MMBT4U4U1#-.CT#J#J ;8: 5; $9 & &C#-c4#8#8 ) ('*wwz':':'@b&H&H&M&MG& &7m6J6J36O6O+O+O-0WWXr-B-B
#-j$#?#? !V4>NN:r4R4RM'1-'F'F %V2?2C2CDT2U2U+2+>ILW,F %%z2       ( x,J,J*0b(.B*D*0b- - - ' ' ' ' ' '# -0'*<<- -) ),,?$,F(G(G% \\
 "/!A!A%%%3N$,MM%C%CG%L%LN$/M* #6"&?? 5!_4  
 # FKK>"~$9$9=.455.22488   !% @ @IeIefkIlIl m mIz555555373V3V#)(35?	45P5P(Z		VZ 4W 4 40
L
 (++I66 m&) )+2) ) )I
  #9~~22-4W 	." 	."&2	."*434/3046>Z/</G/6t7GPTP`/a/a	." 	." 	." 	."
S!& HMJ$D;P;PJ$8+2+C+E+ED;?;O;O(,)* )* )* )* )* )*<& <& 6& 6& 6& 6& 6& 6&NK 4>3HL3?=C[3[L48(/
<WY^(_(_5& 5&M (4 %*CO(@(,(:(@(@(B(B(B.5.?,0,M,2M3H/* /* /* )* )* )* )* )* )* )*  (4 %*} %*(,(:(M(M,9,Dk)* )* )* 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/6u>SUY/Z/Z/m^m-=04-= -= -= )2).7;}7H7H7Y7YH/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;}7H7H7Y7YH/7 -rFN -r6>mmFNT\gpm6q6q0q0q0q0q0q0q0q/8 ). ). ).,2NN0i05-. -. -. -. -. -. -. -.). %)$<$<[$I$I$I*.*P*P(2<M +Q +& +& %& %& %& %& %& %& %& %& %)$<$<[$I$I$I*.*P*P(2<M +Q +& +& %& %& %& %& %& %& %& %& %   F         #	.t1BBDD #	.N .              011&&x00E99#GH.@AA : #&=&=&?&??NIl]:<NOOOO"k1N . . .V   +-.  	D6? 	Dv(./P/PU[UdhphxUxUx"O1M*=99G9W%% D (.88 &%# *}7J7J7L7L * * (* * *  33FFCCCCCCCCC ?h...m''(899G))%00H :G :9T(U(U :$>>xHH
 :"&9Z&9&99N "??#	 @ 
 
 
 
 
 
 
 
 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 	))Mfo..	
 	
 	
l
	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 "&-"3"3FO"D"D" Fw'N'N F)55fnEEEEEEEEE    //
NKK a%#"  
 "&!2!26?!C!C4//1MtTT`"=="#1 >     $ R@Z([([ R";??
DQQQj ##$788888g $''(899?RH-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+>>>&;;KHHHH    LL@#R        ( W: (G   <FOXVV -- ,|2LP]Ph2h2h +/DDD/;L/IM,&,,...&CC%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*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#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$'(8(8"(E(E$F$F$L$L$N$N!
 += 
+\%%&=>>?? J     <     J 22Hs7||b7H ( + L!,   
 $ M!,    788 &] &{ &M!,   !.<<[II	((555-11+tDDD44[$GGG4!788 E-11+tDDD t%;TBB#HH[$///( %.M!+96S          %ND B
 +  (,,Wb99	"77!, .!*b!7!9!9=C_$TFO$9$9RT%' 	 	 	* +../@$BRZ^B^__O + b# ` # 0; -,) 2= /.  # F03E4D0E0EK-
 $ *BB%0#e6F2G2G   ! KK8(-*B    &;;%0# / <     +../?WNN?B>?R?RU`?`?`~kll;;fh $ 2 &  4? 10!-  6A 32!## #K ' J478H4I4IL1&;;%0# / <   
   *??)4%0XTVWW$3 @    -2)+  776??h66$ 83 8R 8 8 59 #6 9 9 % 0 !: ,E 9 925e6F2G2GE,/481*??)4e$3 @     --)#/#3#34H!#L#L .   . 99]5         $ K!,    !!1!1.!A!ABBM,,UHn[h,ii >,,UH========= // 8H8H8R8R  %)]%6%6v%G%GN% "??$e^           
L	L(,(9(9&/(J(J( "/"4"4 & ,)-)I)I&RVRnRnotRuRu)v)v #5 # #       
 % L L L%FKKKKKKKKLV ##$788888S R ##$78888O  d	 d	 d	#}00AA CGL-$H$H C&226>BBBBBBBBB   8+FFF%l!VXX--,2J}Oh).&0-1-?-O-OP]Ph-i-i**$ 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*??)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8Od	N ##$78888s  E 
E$#E$ AH (H;:H;/ J )J<;J<!M& &&NN8AT? ?
UUC&[ :Z [ 
Z%"[ $Z%%9[ 
\)\		\C`+ +
a5aa/Bp e p e+(p *e++B*p h. -p .i?p ip A7j> =p >
kp 
k	p k( 'p (6l!p  l!!C!p p pp pp 
p('p(BAC? -F)AC A~# "AC #
-AC AAC @AAA" A!AC A"
ABA,ABBAC BABBAC B3AC? C4AC;C;AC? C?
AD.D	AD)D)AD.EAAF. F.
AG"F8 AGGAG"L<BAO O
AO?OAO:O:AO?P7C,BN8 T$AAU6 U5BN8 U6
AVV BN8 VAVVB9BN8 YBN8 Y,AY? Y>BN8 Y?AZZBN8 ZAZZB+BN8 \:A] ]BN8 ]
A^]A^ ];BN8 ^ A^^C;BN8 bA!Ac# c"BN8 c#2AddBN8 dAddB(BN8 g3Ag5 g4BN8 g5AhhBN8 hAhhBBN8 jBAl% l$BN8 l%
Aml/AmmBN8 mAmmABN8 n-A4Ap" p!BN8 p"
Aqp,AqqBN8 qAqqBN8 q1As rAr$r#As r$
Asr.Ass	As sAssAs sBN8 s
Ats"Ats=BN8 tAttW#BN8 K+A+BM MBN8 M
BNM!BNM<BN8 NBNNBN8 N!BN8 N8B['OABPPB["P
BP#P B["P"BP#P#B["QBUQBQ:Q9BUQ:BR	RBURBR	R	CBUU
B["U&BU4U1B["U3BU4U4A%B["WABXXB["X
BX)X&B["X(BX)X)A6B["ZB[* Z:B["[B['[B[* ["B['['B[* [*B\c                     ddl m}m} t                      }d}d}d}d}d}d}		 t	                      }	|	r|	                    di           }
t          |
t                    rm|
                    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|`|	r]	 |	                    d	g           }|r2|D ].}t          |t                    s|                    d          pd
}|                    d          pi }|rF||k    r@|                    d          }|)	 t          |          } n# t          t          f$ r Y nw xY wt          |t                    r|                    |          }t          |t                    r|                    d          }n|}|Ft          |t          t          f          r*	 t          |          } n# t          t          f$ r Y *w xY w0n# t          $ r Y nw xY w	 t                      }|p|                    d          }|p|                    d          }|                    d          }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_CONTEXTNrN  r
  rM  rO  rl
  rn
  rR   ro
  rP  )rO  rP  r
  rM  rn
  r  u:   default — set model.context_length in config to overridedetectedi@B z.1fMi  Ku   ◆ Model: `ri  u   ◆ Provider: 
openrouteru   ◆ Context: z	 tokens (r  	localhostz	127.0.0.1z0.0.0.0u   ◆ Endpoint: r   )r&
  r\  r]  r  r~  r3   r   rB   r   r  r   r  rm
  r   r   r  r7   r4   rA   )r  r\  r]  rN  r
  rM  rO  rP  custom_provsr  r  raw_ctxrm
  rn
  cpcp_model	cp_models
raw_cp_ctxmodel_entry	model_ctxr  r
  
ctx_sourcectx_displayr;  s                            r"   r
  z"GatewayRunner._format_session_info.  s    	\[[[[[[[&(( $	'))D @ HHWb11	i.. A'mm,<==G*!47LL11 ):6 ! ! ! D!(}}Z88@DH(}}Z88@DH@QQQQQQ#B#B4#H#HLL  @ @ @#'88,>#?#?LLL@ 	 	 	D	 !(T(#'88,>#C#C # ). ) ))"d33 %$#%66'??#8b$&FF8$4$4$:	# )E(9(9)+0@)A)AJ)5!)<?
OO$9$)E(1:'> !) !) !)$(D!) &i66 )*3--*>*>K)+t<< 8,7OO<L,M,M		,7	(4IPSUZ|9\9\4!)<?	NN$9$)E(1:'> !) !) !)$(D!)   	355G:7;;z#:#:H:7;;z#:#:Hkk),,GG 	 	 	D	 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D 7B D BD B1D C D D>D  DD 
DDBI( F/-I( /G I( GA8I( <II( I"I( !I""I( (
I54I59AK 
KKcanonical_cmdc                    ddl m} |sdS  || j        |          }|j        r|                    |j        |          rdS t                              d||j        r|j        j	        nd|j                   t          |j                  }|rFdd                    d |dd	         D                       z   t          |          d	k    rd
ndz   dz   }nd}d| d| S )u  Return a denial message if ``source`` cannot run ``canonical_cmd``,
        else None. Used by both the cold and running-agent dispatch paths
        in ``_handle_message`` so admin/user gating can't be bypassed by
        an in-flight agent.

        Backward-compat semantics live in
        :func:`gateway.slash_access.policy_for_source` — when the operator
        hasn't set ``allow_admin_from`` for the scope, the policy returns
        ``enabled=False`` and this method always returns None.
        r   )policy_for_sourceNzLSlash command /%s denied for %s:%s (not admin, not in user_allowed_commands)r  zYou can run: r}  c              3       K   | ]	}d | V  
dS )r   Nr   )r   r.  s     r"   ru  z4GatewayRunner._check_slash_access.<locals>.<genexpr>/  s(      BBGGGBBBBBBr$   rj   r  rR   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_accessro  r  r'  can_runr  r   r  r   rQ   r7  user_allowed_commandsrA   r   )r  r  rm  _policy_for_sourcer
  allowed_previewr  s          r"   r[	  z!GatewayRunner._check_slash_access.  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Cr$   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  rR   r  z
agent:main)rS   r   rQ   rA   r7   rY  rX  rE  r7  rr  r4   )r  r  rv  r  r   r   r  rd  matchesrL  r  s              r"   _sibling_thread_run_keysz&GatewayRunner._sibling_thread_run_keys*/  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###r$   c                    ||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 |                    d          }t          |t          t           f          rt          j                    |z
  dk    rdS |j        |k    S )aB  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 AND the marker is recent (< 5 minutes), it's a
        redelivery and should be ignored.

        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.jsonrR  rQ  r/  r  Tr   	update_idrl  r  )r  platform_update_idr   rQ   r   r  r:   rS   r  rR  r  r  r[  r3   r   r   r   )r  r  r   marker_pathr  recorded_uidrl  s          r"   _is_stale_restart_redeliveryz*GatewayRunner._is_stale_restart_redeliveryT/  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 xx//lS%L11 	y{{\)C//u'<77s(   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.
        rR   NrQ   r   r   r  r  r   r   r  r  r   )handle_suggestions_commandr%  r  rB  zsuggestions command failed: %szSuggestions command failed: )r`	  rT   r  rS   r   r7   r   hermes_cli.suggestions_cmdr  r   r  )	r  r  r  r  r  r   r   r  r  s	            r"   r|	  z)GatewayRunner._handle_suggestions_command/  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.
        rR   NrQ   r   r   r  r  r  r   )handle_blueprint_commandr%  r  zblueprint command failed: %s)BlueprintCommandResultzCron blueprint command failed: )r`	  rT   r  rS   r   r7   r   hermes_cli.blueprint_cmdr  r   r  r  )
r  r  r  r  r  r   r   r  r  r  s
             r"   r}	  z'GatewayRunner._handle_blueprint_command/  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  r  r  )	r   r  rB   r3   rS   r  r  r   r   )r  	goals_cfgr  s      r"   _goal_max_turns_from_configz)GatewayRunner._goal_max_turns_from_config/  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                    	 ddl m} n3# t          $ r&}t                              d|           Y d}~dS d}~ww xY w	 | j                            |j                  }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: %sNrT  z'goal manager: session lookup failed: %sr  rR   r  default_max_turns)
r  r  r   r   r  rG  r  r  rS   r  )r  r  r  r[   r"  sidr  s          r"   _get_goal_manager_for_eventz)GatewayRunner._get_goal_manager_for_event/  s   	4444444 	 	 	LL7===:::::		 .DDU\RRMM 	 	 	LLBCHHH:::::	 m\488>B 	:4466	{cYGGGVVs'   	 
949A 
B'BBrz   c                   K   | j                             |j                  }|s,t                              dt          |dd                     dS 	 |                     |          }n# t          $ r d}Y nw xY w|                    |j	        ||           d{V }|=t          |dd          s.t          
                    dt          |dd	                     dS dS dS )
zCSend a /goal judge status line back to the originating chat/thread.$goal continuation: no adapter for %sr   Nr   r  T)goal continuation: status send failed: %sr5  r  )r0  r3   r   r   r  rS   r  r   r   r   r   )r  r  rz   r   rU   r  s         r"   _send_goal_status_noticez&GatewayRunner._send_goal_status_notice0  s     -##FO44 	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' 'A65A6c                 \   K    j                             j                  }|s,t                              dt          dd                     dS d fd}	                                }n# t          $ r d}Y nw xY w|rt          |d          r	 d}t          |di                               |          }|t          |dd          }|	                    |||	           dS # t          $ r%}t                              d
|           Y d}~nd}~ww xY w |             d{V  dS )a  Send a /goal status line after the main response is delivered.

        The gateway message handler returns the agent response to the platform
        adapter, which sends it after this method's caller has returned.  For a
        natural Discord/Telegram reading order, goal status belongs after that
        send.  Platform adapters provide a one-shot post-delivery callback for
        exactly this boundary; when unavailable, fall back to direct awaited
        delivery rather than silently dropping the notice.
        r  r   Nr   c                     K   	                                 d {V  d S # t          $ r(} t                              d| d           Y d } ~ d S d } ~ ww xY w)Nr  Tr~   )r  r   r   r   )r[   rz   r  r  s    r"   _deliverzHGatewayRunner._defer_goal_status_notice_after_delivery.<locals>._deliver30  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: %srH  )
r0  r3   r   r   r  rS   r  r   r   r  )	r  r  rz   r   r  rG  r
  r  r[   s	   ```      r"   (_defer_goal_status_notice_after_deliveryz6GatewayRunner._defer_goal_status_notice_after_delivery$0  s      -##FO44 	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+   A2 2B BAC* *
D4DDr"  rK	  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 	 | j        
                    |j                  }|                     |          }|r9|r9t          |t           j        |dd          }|                     |||           dS dS dS # t          $ r&}t                              d|           Y d}~dS d}~ww xY w)a  Run the goal judge after a gateway turn and, if still active,
        enqueue a continuation prompt for the same session.

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

        We use the adapter's pending-message / FIFO machinery so any real
        user message that arrives simultaneously is handled by the same
        queue and takes priority naturally.
        r   r  z/goal continuation: goals module unavailable: %sNr  rR   r  )gather_background_processesT)user_initiatedbackground_processesrz   should_continuecontinuation_promptr 	  z%goal continuation: enqueue failed: %s)r  r  r   r   r  rS   r  r  r  evaluate_after_turnr3   r  r0  r   r  r  r  rW  r  )r  r"  r  rK	  r  r[   r  r  mgr
_gather_bg	_bg_procsr	  r  r
  r   r	  
cont_events                    r"   r	  z*GatewayRunner._post_turn_goal_continuationO0  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m''88G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3GGc                     t          | dd          }|dS t          |d          r|j        rt          |j                  S t          |d          r|j        r|j        j        S dS )z5Extract Discord guild_id from the raw message object.r  Nr'  guild)rS   r   r'  r   r  rk   )r  r  s     r"   r
  zGatewayRunner._get_guild_id0  st     e]D11;43
## 	% 	%s|$$$3   	 SY 	 9<tr$   c                 x   K    j                             |j        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 )Nr  )rz  r3   r  r  r$
  r7   )r   r  s    r"   r   z:GatewayRunner._handle_voice_channel_join.<locals>.<lambda>0  s6    9I9M9M 0#g,,??: : r$   z Failed to join voice channel: %spynaclnacldaveyz@Voice dependencies are missing (PyNaCl / davey). Install with: `z -m pip install PyNaCl`zFailed to join voice channel: _voice_sourcesr  T)r'  zJoined voice channel **zL**.
I'll speak my replies and listen to you. Use /voice leave to disconnect.zFFailed to join voice channel. Check bot permissions (Connect + Speak).)r0  r3   r  r   r   r
  get_user_voice_channelr  _handle_voice_channel_inputr  _handle_voice_timeout_cleanupr  r  r  r   r   r   r7   r8   r-   r  r   r   _voice_text_channelsto_dictr  rz  r  r  r  rt   )r  r  r   r'  voice_channelr  r  	err_lowers   `       r"   _handle_voice_channel_joinz(GatewayRunner._handle_voice_channel_join0  s     -##EL$9::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)6AE$E)E$E)$E)c                   K   | j                             |j        j                  }|                     |          }|rt          |d          sdS t          |d          r|                    |          sdS 	 |                    |           d{V  n2# t          $ r%}t          
                    d|           Y d}~nd}~ww xY wd| j        |                     |j        j        |j        j                  <   |                                  |                     ||j        j        d           t          |d	          rd|_        d
S )z Leave the Discord voice channel.leave_voice_channelzNot in a voice channel.is_in_voice_channelNzError leaving voice channel: %sr  Trn  r  zLeft voice channel.)r0  r3   r  r   r
  r   r  r  r   r   r   rz  r  r   r  r  r  )r  r  r   r'  r  s        r"   _handle_voice_channel_leavez)GatewayRunner._handle_voice_channel_leave0  su     -##EL$9::%%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   8B 
CB>>Cc                     d| j         |                     t          j        |          <   |                                  | j                            t          j                  }|                     ||d           dS )zCalled by the adapter when a voice channel times out.

        Cleans up runner-side voice_mode state that the adapter cannot reach.
        r  Tr  N)rz  r  r  r$
  r  r0  r3   r  )r  r   r   s      r"   r  z+GatewayRunner._handle_voice_timeout_cleanup0  so    
 HM)97CCD   -##H$455++GWt+LLLLLr$   r'  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+rL  z[^\w\s]rR   Fg      (@r{  Nc                 0    g | ]\  }}|z
  k    ||fS r   r   )r   ri  txtr  r  s      r"   r`  z@GatewayRunner._is_duplicate_voice_transcript.<locals>.<listcomp>1  s:     
 
 
CRx>)) I)))r$   Tr  rp
  )difflibr  r   r   rT   r8   r  r  rS   r   rB   r{  r3   r   ratior4   )r  r'  r  r  r  rO  rL  recent_storerecentrE  priorr  r  s              @@r"   _is_duplicate_voice_transcriptz,GatewayRunner._is_duplicate_voice_transcript	1  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ur$   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).
        Nr  channel)r   r   r  r  r  z/Unauthorized voice input from user %d, ignoringz?Suppressing duplicate voice transcript for guild=%s user=%s: %sr    z	@everyoneu   @​everyonez@hereu   @​herez**[Voice]** <@z>: r   )SimpleNamespace)r'  r  )r  r   r  r  )r0  r3   r  r$
  r  rS   r  	from_dictr7   r  r  r  r   r  r  r  _clientget_channelr   r   r   typesr  r  r  r  rP  )r  r'  r  r  r   
text_ch_idsource_datar  r  	safe_textr  r  s               r"   r  z)GatewayRunner._handle_voice_channel_input21  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r  r6  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:Fr  r  r  c              3      K   | ]K}|                     d           dk    o-t          d |                     d          pg D                       V  LdS )r  r  c              3   p   K   | ]1}|                     d i                                d          dk    V  2dS )r  rt   rl  NrV  )r   tcs     r"   ru  zCGatewayRunner._should_send_voice_reply.<locals>.<genexpr>.<genexpr>1  sX         z2&&**6226FF     r$   r8  N)r3   r  )r   r  s     r"   ru  z9GatewayRunner._should_send_voice_reply.<locals>.<genexpr>1  s       
 
  GGFOO{*   77<006B    
 
 
 
 
 
r$   T)rr  r  r   rz  r3   r  r   r  r  r  r  )
r  r  r  r6  r
  r   
voice_modeis_voice_inputshouldhas_agent_ttss
             r"   r
  z&GatewayRunner._should_send_voice_replyv1  s    $  	8..x88 	5,&%))$//%,:OQX*Y*Y[`aa
,0AA 5  ?l*=~ 	  	5  
 
 &
 
 
 
 
  	5  	, 	5tr$   c                 H    t          t          | j        dd                    S )zFReturn whether inbound voice/STT transcripts should be echoed to chat.stt_echo_transcriptsT)r   rS   r  r  s    r"   r
  z*GatewayRunner._should_echo_stt_transcripts1  s    GDK)?FFGGGr$   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                            |j        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)rm  _strip_markdown_for_tts  oggmp3hermes_voice
tts_reply_rj   rE  T)r  )r   output_pathz.Auto voice reply TTS returned invalid JSON: %sr  r  r  zAuto voice reply TTS failed: %sr5  play_in_voice_channelr  
send_voicer
  )r   
audio_pathr`  rU   zAuto voice reply failed: %sr~   r   )(uuidtools.tts_toolrm  r  r1   r  r6   r  r   r  r  r;   rA   tempfile
gettempdiruuid4hexmakedirsdirnamer:  r;  r  r  r  r  r   r   r3   isfiler0  r
  r   r  r  r  r  rB   r   r  r   )r  r  r   _uuidr  actual_pathrm  r  tts_textr  	audio_extresult_jsonr  r   r'  r  r  send_kwargsr  s                      r"   r
  zGatewayRunner._send_voice_reply1  su     
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 m''(=>>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 $N99
OOO=O,+O=,
O9	6O=8O9	9O=c                   K   ddl m} ddlm 	 d|v }ddlm}m} |                    |          \  }}	 |j        |          }|	                    |	          \  }
}	|
                    |	          \  }}
 |j        |          }|                     |j        |                     |                    }h d}h d}g }g }|D ]\\  }} ||          j                                        }||v r|s|s|                    |           E|                    ||f           ]g }|D ]S} ||          j                                        |v r|s|                    |           >|                    |           T|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 ]}	  ||          j                                        }||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 MEDIA: tags and local file paths 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.
        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://rR   r   )r   r  _quotes     r"   r`  z>GatewayRunner._deliver_media_from_response.<locals>.<listcomp>?2  s/    OOOa444b9OOOr$   )r   imagesrU   Nz0[%s] Post-stream image batch delivery failed: %s)is_voicer   r  rU   r   
video_pathrU   r   r  rU   z*[%s] Post-stream media delivery failed: %sz)[%s] Post-stream file delivery failed: %sz'Post-stream media extraction failed: %s)pathlibr   urllib.parser  r  r  r  extract_mediafilter_media_delivery_pathsextract_imagesextract_local_filesfilter_local_delivery_pathsr  r  r  r  r8   r4   send_multiple_imagesr   r   r   r   rt   r   r  
send_videosend_document)r  r  r  r   r   force_document_attachmentsr  r  media_filescleanedrE  local_files_thread_meta_VIDEO_EXTS_IMAGE_EXTSr1
  non_image_media
media_pathr  rC  non_image_localr  r  r  r  s                           @r"   r
  z*GatewayRunner._deliver_media_from_response1  s      	!     000000h	I
 *;h)F&^^^^^^^^#*#8#8#B#B KI-I+VVK !//88JAw$88AANKI-I+VVK;;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$&O( 6 6	DOO*0022kAA : B&&y1111#**95555 	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 - a a	a$y//06688Ck))%00$)L$8'0%1 1           &33$)L$8&/%1 4         
 ! a a aNN#NPWP\^_````````aa a$  	I 	I 	INNDaHHHHHHHHH	Is   E'N 96F0 /N 0
G%:!G N  G%%
N 0B8J)(N )
K3!KN KN &A7MN 
N(!N	N NN 
O"OOr
  r  r?	  r   r  r  c                    $%&'()*+,K   ddl m$ |pg }|pg } j                            j                  }|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   rt
  z0No adapter for platform %s in background task %sN)r  r   rP  u   ❌ Background task z, failed: no provider credentials configured.r   _get_platform_toolsr  disabled_toolsets)r  rR   r  z,Background task vision enrichment failed: %sc                      d&dd         id         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$	j        } 	 |                     %          	                    |            S # 	                    |            w xY w)'NrN  r  ry  rw
  Tverbose_loggingFry
  r,  r  rM  rJ  providers_allowedonlyproviders_ignoredignoreproviders_orderorderprovider_sortsortprovider_require_parametersrequire_parametersprovider_data_collectiondata_collectionr  r   r  user_id_altr  r   r  r  r  r	  rr  fallback_model)rF  r?	  r   )r<  r3   r  r;  r  r   r  r  r  rS   rp  rE  run_conversationr  )r  ru
  r,  ry
  enriched_promptry  r   prr  r  r  r?	  
turn_routes    r"   run_syncz4GatewayRunner._run_background_task.<locals>.run_sync2  sL     $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  't'7@PQQQ56 $(#7#77 :9 11%4 ' 2  
 11%8888D11%8888s   2E E5rK	  r5  zError: )r  r  r	  u&   ✅ Background task complete
Prompt: "z"

r  z(No response generated))r   	image_urlcaptionrU   )r  r  r   r+   r  r  )r   
image_pathrU   r  z"

(No response generated)zBackground task %s failedz	 failed: ).r
  ru
  r0  r3   r   r   r   r  r~  rE  r   r   ry  hermes_cli.tools_configr+  r7  rC  r  r  r:  r;  r<  rN  r  r   rr  r4   r
  r   r  r  r  r  r  r  
send_imager  r1   r;   r9  r8   r  r  send_image_filer  ry   )-r  r
  r  r?	  r   r  r  r   _thread_metadatar   rN  r?  r+  r  r1
  r  r;   r   r  rA  r  r  r   r  r  text_contentr	  headerrB  alt_text_should_send_media_as_audior%  r$  r'  	_is_voicerC
  ru
  r,  ry
  r>  ry  r   r?  r  r@  s-   ` ``                                @@@@@@@@@r"   _run_background_taskz"GatewayRunner._run_background_taskw2  s	      	&%%%%%%2
!'R-##FO44 	NNMv`ghhhF;;FDTUUr	.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EVETT%5D"!%!8!8!:!:D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 $9L  ==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   8A$T D'T H# "T #
I-IT ID9T $N10T 1
N>;T =N>>AT B)R:9T :
ST ST A	T 
V!V=)U'&V'
U41V3U44VVc                   K   t          | dd          r| j                            |j                  nd}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.r0  N_botget_mecheckedFz1Failed to fetch Telegram getMe topic capabilitiesTr~   rt   c                    t          |           rt          |           S t          dd           }t          |t                    r| |v r|                    |           S t          t                    r                    |           S d S )N
api_kwargs)r   rS   r   rB   r3   )rt   rT  mes     r"   _fieldz>GatewayRunner._get_telegram_topic_capabilities.<locals>._fieldS3  s    r4   )r4((( \488J*d++ ,
0B0B!~~d+++"d## $vvd||#4r$   has_topics_enabledallows_users_to_create_topics)rR  rW  rX  )
rS   r0  r3   r   r   rQ  r   r   r  r7   )r  r  r   botrV  rU  s        @r"    _get_telegram_topic_capabilitiesz.GatewayRunner._get_telegram_topic_capabilitiesG3  s$     8?jRV8W8Wa$-##FO444]agvt,,;gc844;u%%	&zz||######BB 	& 	& 	&LLLW[L\\\u%%%%	&	 	 	 	 	 	 	 "(&)=">">-3V4S-T-T
 
 	
s   A9 9*B&%B&c                   K   t          | dd          r| j                            |j                  nd}||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.r0  N_create_dm_topicSystemz&Failed to create Telegram System topicTr~   z,System topic for Hermes commands and status.r  r   r  z*Failed to send Telegram System topic introrP  pin_chat_message)r   r  disable_notificationz)Failed to pin Telegram System topic intro)rS   r0  r3   r   r   r   r   r   r   r  r   r7   r   r^  )r  r  r   r  create_topicr  send_resultrY  s           r"   _ensure_telegram_system_topicz+GatewayRunner._ensure_telegram_system_topicc3  sq     8?jRV8W8Wa$-##FO444]a?&.?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   #$B &B10B1;AC? ?&D('D(=F &F>=F>c           	      *  K   t          | dd          r| j                            |j                  nd}||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.r0  NrG  assetsz'telegram-botfather-threads-settings.jpgu/   BotFather → Bot Settings → Threads Settingsr  )r   rD  rC  rU   z)Failed to send Telegram topic setup imageTr~   )rS   r0  r3   r   r   r   r   r.   r/   r0   r:   rG  r7   r  r   r   r  )r  r  r   rD  s       r"    _send_telegram_topic_setup_imagez.GatewayRunner._send_telegram_topic_setup_image3  sP     8?jRV8W8Wa$-##FO444]a?&.?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( (&DD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  rL  rR   zHermes Chatx   Nu   r	  )r   r   r7   rT   r   rc  )r  r  r!  s      r"   _sanitize_telegram_topic_titlez,GatewayRunner._sanitize_telegram_topic_title3  sp    &c%+2&6&677==?? 	! = w<<#dsdm**,,u4Gr$   c                   K   t          j        | j        |           d{V r|j        r|j        sdS |                     |          rdS t          | dd          r| j                            |j	                  nd}|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.Nr0  _get_dm_topic_inforp  r\
  r  rR   z5Failed to verify Telegram topic binding before renameTr~   rename_dm_topic)r   r  rt   rP  edit_forum_topiceditForumTopic)r   message_thread_idrt   z8Failed to rename Telegram topic for auto-generated title)r:  r;  r  r   r  $_telegram_topic_auto_rename_disabledrS   r0  r3   r   rl   r   r7   r   r   rB   r
  r   r  ri  r   r  r   )r  r  r  r  r   get_infooperator_topicr	  r
  
topic_namerename_topicrY  rm  s                r"   (_rename_telegram_topic_for_session_titlez6GatewayRunner._rename_telegram_topic_for_session_title3  s-      &t'CVLLLLLLLL 	TZTb 	jpjz 	F 44V<< 	F 9@jRV8W8Wa$-##FO444]a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-A8F &G ?G AK *?K ,8J& &/KK KK &LL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).
        r  Nr   Fr  disable_topic_auto_rename>   r   r   r   r   )
rS   r  r   r3   r   r   r   r7   rT   r8   )r  r  r   r  rQ   s        r"   rp  z2GatewayRunner._telegram_topic_auto_rename_disabled3  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{{r$   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.NrJ  z.Telegram topic title rename failed to scheduler   log_messager   c                     	 |                                   d S # t          $ r  t                              dd           Y d S w xY w)Nz"Telegram topic title rename failedTr~   )r  r   r   r  )futs    r"   _log_rename_failurezPGatewayRunner._schedule_telegram_topic_title_rename.<locals>._log_rename_failure24  sX    R

 R R RADQQQQQQRs    &AArH  )r  rp  r:  r  r  rS   	is_closedr2  r   r   r   ru  r   rk  )r  r  r  r  rv   copied_sourcer{   r}  s           r"   %_schedule_telegram_topic_title_renamez3GatewayRunner._schedule_telegram_topic_title_rename4  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$g     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_tsrR   Tr   Nr/  F)r   r  r7   r   r  r  r3   $_TELEGRAM_CAPABILITY_HINT_COOLDOWN_Sr  s         r"   %_should_send_telegram_capability_hintz3GatewayRunner._should_send_telegram_capability_hint<4  s     t;<< 	302D-fn*++ 	4oo044WcBB:AAA558)'2tr$   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_textO4  s    M	
 	
r$   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)rd  rR   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.)rp  rq  r  r   r7   r   r  r  r   disable_telegram_topic_moder   ry   rS   r   rB   r  )r  r  r  r   currently_enabledr[   r  stores           r"   %_disable_telegram_topic_mode_for_chatz3GatewayRunner._disable_telegram_topic_mode_for_chate4  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.rR   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.rR   rS  )r   r  limitz)Failed to list unlinked Telegram sessionsTr~   zPrevious unlinked sessions:rk   rR   r  zUntitled sessionr	  z- u    — `ri  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.rR   z$To restore a previous session later:r  r  r   )rp  (list_unlinked_telegram_sessions_for_userr7   r   r  r   r   r  r4   r3   rT   extendrA   )	r  r  r;  r   rt  r  r  r	  r^  s	            r"   #_telegram_topic_root_status_messagez1GatewayRunner._telegram_topic_root_status_message4  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  rR   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\
  r  z9That session is already linked to another Telegram topic.restored)r   r  r  rG  r  managed_modezalready linkedr  r  r   zSession restored: z

Last Hermes message:
)r  rp  resolve_session_idrT   rW  r7   r3   r  #is_telegram_session_linked_to_topicr
  r   r  r  r!  r   get_session_titlerh  get_messagesr   )r  r  r  r  r  rt  linkedcurrent_bindingrG  r[   r  last_assistantrz   r  s                 r"   _restore_telegram_topic_sessionz-GatewayRunner._restore_telegram_topic_session4  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           
      >	  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                  }| j                            |j        |           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_serversrM  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)rS	  servers)refresh_agent_mcp_toolsrd  re  T)rw
  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. rR   r4  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)r5  )r:  r  tools.mcp_toolr  r  r  rM  r5   r  r
  r   r4   rA   r7  r   r  rS   rY  rE  r   rK  r   r   r  rG  r  r  r
  r  r   )r  r  rv   r  r  r  rM  old_servers	new_toolsconnected_serversaddedr  reconnectedr;  r  rz  rF  	_sess_keyr|  rv  _excchange_partstool_summarychange_detail
reload_msgr"  r  s                              r"   _execute_mcp_reloadz!GatewayRunner._execute_mcp_reload4  sL      '))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 $ 2 H H V V"77!,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 7?P7 6Q 7
QQ QQ 
R&+RRRr  r	  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 )Nrm  u   🟡 /z# cancelled. Conversation unchanged.rp  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.)rw  r  r   r  r   r   r   r7   )r  r  r[   r  noter  r	  rG  s        r"   _on_confirmzCGatewayRunner._maybe_confirm_destructive_slash.<locals>._on_confirm5  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`._)r  r  r  rz   handler)_read_user_configr   rB   r3   r   r   r  r  r7   _typed_command_prefix_forr   _request_slash_confirm)r  r  r  r  r	  r	  confirm_requiredr  r  r  _pprompt_messagerG  s     `  `      @r"   ro	  z.GatewayRunner._maybe_confirm_destructive_slashq5  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          |	           }|	                    ||||           | j
                            |j                  }|                     ||                     |                    }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   r  rn  Nr+   F)r   r  rz   rG  r  rU   r  Tz*send_slash_confirm failed for %s on %s: %s)rS	  r  r  r  rS   rm  r   rn  nextregisterr0  r3   r   r  r  send_slash_confirmr   r   r   r  )r  r  r  r  rz   r  r	  r  rG  counterr  r  r   rU   used_buttonsbutton_resultr[   s                    r"   r  z$GatewayRunner._request_slash_confirm5  s     * 	>=====226::
 $ 8$???**** &&q))G*1D'W'
 	##KWgNNN-##FO4433FD<X<XY^<_<_``&-&@&@"N# +)% 'A ' ' ! ! ! ! ! ! ! (W]Iu%M%M (#'L   @V_c         	4s   ;D	 	
D?"D::D?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  )r  r  r   rB   r   )r  r  r  s      r"   r  zGatewayRunner._read_user_config6  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                    S )z@Build the metadata dict platforms need for thread-aware replies.r   Nr   r  r  r  )r  r  )r  rS   )r  r  r  s      r"   r  z)GatewayRunner._thread_metadata_for_source6  sr     //FJ--FIt,,FK..fk488 3 Zwv|UY7Z7Z 0 
 
 	
r$   r  r  c                    |dS d|i}|                      |||||          r3d|d<   t          |          }|r	|dvr||d<   |t          |          |d<   |S )	zGBuild thread metadata for synthetic sends that only have routing state.Nr  r  r   T telegram_dm_topic_reply_fallback>   rR   r   direct_messages_topic_idtelegram_reply_to_message_id)_is_telegram_dm_topic_targetr7   )	r  r   r   r  r  r  r   rU   r  s	            r"   r  z)GatewayRunner._thread_metadata_for_target(6  s     4$/#;,, - 
 
 	T <@H78 i..C ;s)++7:34".;>?R;S;S78r$   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  Trk  z,Failed to inspect Telegram DM topic metadatar~   )r  r  rS   rl   r   r7   r   rB   r   r   r  )r   r   r  r  r   get_dm_topic_info
topic_infos          r"   r  z*GatewayRunner._is_telegram_dm_topic_targetH6  s     x(((I,=54 7 'W7KT R R)** 88!2!27CLL#i..!Y!YJ &j$777 ! ` ` `LL!OZ^L_____` us   'B &B43B4c                      t          |           S )zBReturn the platform-specific reply anchor for GatewayRunner sends.)r  )r  s    r"   r  z%GatewayRunner._reply_anchor_for_eventh6  s     'u---r$   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)	rS   rw  r:  rI  _watch_update_progressr  r  r   r  )r  existing_tasks     r"   r  z1GatewayRunner._schedule_update_notification_watch6  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_coder  Nr   r   r  rG  r  r  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]rR   )r   r   r   s    r"   _strip_ansiz9GatewayRunner._watch_update_progress.<locals>._strip_ansi6  s    62B===r$   r   rR   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.rR   N  c                 *    g | ]}||z            S r   r   )r   r  clean	max_chunks     r"   r`  zOGatewayRunner._watch_update_progress.<locals>._flush_buffer.<locals>.<listcomp>6  s&    VVVeAa)mO,VVVr$   r   ```

```r!   r   zUpdate stream send failed: %s)	rT   r  r;  r   r   rZ   r   r   r  )chunkschunkr  r  r  r  r   bufferr   last_stream_timerv   rU   r   s      @@r"   _flush_bufferz;GatewayRunner._watch_update_progress.<locals>._flush_buffer6  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.r!   r   u(   ❌ Hermes update failed (exit code {}).z&Update finished (exit=%s), notified %sz$Update final notification failed: %sTr  r  r
  r   Fsend_update_prompt)r   r
  r   rG  rU   z%Button-based update prompt failed: %sz (default: r  typed_command_prefixr   u"   ⚕ **Update needs your input:**

	

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.rH  )#r  r:  r  r  r:   r  r  r[  r3   r  r0  r  r   r   r   r  r  r  r7   r   r6   rT   r   r   rZ   formatr  r  rl  r  rS   rl   r  r  r  )'r  r  r  r  pending_pathclaimed_pathr  exit_code_pathr	  r  rG  r;   r  r  r  r  r  
bytes_sentr  r   exit_code_rawr  r  r  prompt_dataprompt_textr   sent_buttonsbtn_errdefault_hintr  r  r   r  r   r  rv   rU   r   s'                                  @@@@@@@@r"   r  z$GatewayRunner._watch_update_progress6  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  r   r   r  r  r  z2Update notification deferred: update still runningr   rR   z:Update notification deferred: %s adapter not connected yetr  z\x1b\[[0-9;]*mr  r  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.r!   r   z0Sent post-update notification to %s:%s (exit=%s)z#Post-update notification failed: %s)r  r:   r   r  r  r  r  r[  r3   r   r  rT   r   r  r0  r  r   r   r   r   rZ   r   r   )r  r  r  r  r  cleanupactive_pending_pathr  r  r   r  r  r  r  r  r  r   r   rU   r  r  s                        r"   r  z'GatewayRunner._send_update_notification{7  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  Nr   r   r  r  r  Tr  z6Restart notification skipped: %s adapter not connectedzJRestart notification suppressed: %s has gateway_restart_notification=falser  u;   ♻ Gateway restarted successfully. Your session continues.r!   r   r  Fz3Restart notification to %s:%s was not delivered: %sr5  r  z"Sent restart notification to %s:%szRestart notification failed: %s)r  r:   r  r  r[  r3   r  r  r0  r   r  r  r   r  r  r  r   r7   rZ   rS   r   r   )r  notify_pathr  r  r   r  r  r  r   r   r   rU   r  r  s                 r"   r  z(GatewayRunner._send_restart_notification7  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=falser  r!   r   r  TFz6Home-channel startup notification failed for %s:%s: %sr5  r  z/Sent home-channel startup notification to %s:%s)r5   r0  rE  r  r  r   r   r3   r  r   r  rQ   r7   r  r  r   rZ   rS   r   r9   r   )r  r  	deliveredskippedrz   r   r   r  r   r  rU   r  _startup_metar[   s                 r"   r  z6GatewayRunner._send_home_channel_startup_notifications98  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_varsr0  Nsupports_async_deliveryTrR   r  )
r   r   r  r  r  r  rG  r  r  async_delivery)rL	  r  rS   r3   r  r   rQ   r   r  r  r7   r  r  rG  r  )r  rw   r  	_adaptersr  _async_deliverys         r"   r
  zGatewayRunner._set_session_env8  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*
 
 
 	
r$   r  c                 (    ddl m}  ||           dS )z>Restore session context variables to their pre-handler values.r   )clear_session_varsN)rL	  r  )r  r  r  s      r"   r
  z GatewayRunner._clear_session_env8  s+    >>>>>>6"""""r$   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_executorr0  )r  funcr  rv   ctxs        r"   r  z+GatewayRunner._run_in_executor_with_context8  sx      '))nn)T)  G
 	
 
 
 
 
 
 
 
 
 	
r$   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.rU  NrW  Fz.Gateway is shutting down; executor unavailablerV  	_shutdownrS  r,  )max_workersthread_name_prefix)	rS   rS  rT  rU  r  
concurrentfuturesThreadPoolExecutorrV  r  rJ  executors      r"   r  zGatewayRunner._get_executor8  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.rU  NTrV  F)r  cancel_futures)r  )rS   rW  rV  r  r  r  s      r"   rr  z GatewayRunner._shutdown_executor8  s   t-t44<F 	" 	"%)D"t[$77H!DN	" 	" 	" 	" 	" 	" 	" 	" 	" 	" 	" 	" 	" 	" 	"
 F	*5>>>>> 	* 	* 	*5))))))	*s#    AAAA- - BB)r  rG  r   rM  rN  rM  c                8   	 ddl m} ddlm}m} ddlm}	 t          |t                    r|n	 |	            }
|pd	                                }|pd	                                }| p| }|dup|}|r|r	 | 
                    |||
          \  }}|s)t          |t                    r|	                                }t          |t                    r|                    d          nd}|s)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  rR   Nr4  rM  uO   image_routing: session runtime resolution failed, falling back to config — %su;   image_routing: decision failed, falling back to text — %sr   )agent.image_routingr  r  r  r   r  r  r   rB   rT   rE  r7   r3   r   r   r  )r  r  rG  r   rM  rN  r  r  r   r  r  resolved_providerresolved_modelneeds_session_runtimehas_session_identity
turn_modelr?  runtime_providerr[   s                      r"   r
  z&GatewayRunner._decide_image_input_mode8  sL   *%	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$, E<Lc1R1R E,<,B,B,D,D)    LLi        % :$7$7$9$9!! 4!1!1!3!3**+<ncRRR 	 	 	LLVX[\\\66666	sC   A1E) 4BD E) 
ED<7E) <E'E) )
F3FF	user_textr1
  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)rB  user_promptNr  analysisrR   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: rw  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   r  r  r  r3   r4   r   r5  rA   )r  r(  r1
  r*  r+  analysis_promptenriched_partsr;   r  r  descriptionr  rd  s                r"   r
  z)GatewayRunner._enrich_message_with_vision9  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r2
  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)]rw  r\  z.(The user sent a message with no text content)r   )transcribe_audiozTranscribing user voice: %sr  r  rX  r5  r  z%Voice transcription failed for %s: %sz([voice message could not be transcribed]zTranscription error: %s)rS   r  r1   r;   abspathrF  r4   rA   rT   tools.transcription_toolsr5  r   r  r:  r;  r3   r  r   r5  )r  r(  r2
  notesr;   abs_pathduration_strrd  _placeholderr5  r1  successful_transcriptsr  r  r5  r  s                   r"   r
  z0GatewayRunner._enrich_message_with_transcriptiona9  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                 p  K   |                     |          }|sdS |j        pd}g }t          |dd          pg }t          |dd          pg }t          |          D ]w\  }	}
|	t	          |          k     r||	         nd}|                    d          p(t          |dd          t          j        t          j        fv }|r|	                    |
           x|r| 
                    ||           d{V \  }}|r|                                 r| j                            |j                  }|j        r	d|j        ind}|r_|D ]\}	 |                    |j        d| d	|
           d{V  +# t$          $ r%}t&                              d|           Y d}~Ud}~ww xY w|pdS |s|rt+          |          }|pdS )u  Dequeue a pending queued message, auto-transcribing audio media.

        When a voice/audio message arrives during an active agent run, the
        adapter stores the event in its pending queue and signals an interrupt
        (see base.BaseAdapter.handle_message). The adapter path bypasses
        _handle_message entirely, so the normal STT pipeline at message-receive
        time never runs.

        This helper fills that gap: when the dequeued event has audio media,
        we transcribe inline, echo the raw transcript back to the user (same
        "🎙️" format as the fresh-message path), and return enriched text.
        Non-audio events fall back to _build_media_placeholder, matching the
        original _dequeue_pending_text behavior.
        NrR   r  r  r  r  r  r
  rX  r   r
  )rI  r   rS   r  r   rr  r  r  r  r4   r
  r
  r0  r3   r   r  r   r   r   r   r  r  )r  r   rG  r  r  r   r2
  r  r  r  r;   r   is_audioenriched_textr<  echo_adapter	echo_metatxecho_excs                      r"   #_dequeue_pending_with_transcriptionz1GatewayRunner._dequeue_pending_with_transcription9  s     ( ++K88 	4zR!#UL$77=2
e]D99?R ,, 	) 	)GAt&'#k*:*:&:&:KNNE  ** b5.$77K<M{O`;aa   )""4((( 	):>:a:ak; ; 5 5 5 5 5 51M1
 & $*K*K*M*M #}00AA?E?OY[&*:;;UY	 4 
 
	"."3"3 & 1B 1 1 1)2 #4 # #        
  )   "LL H(        !(D(  	3
 	3+E22D|ts   'E++
F5FFr  c                 \   ddl m} t          |                    d          pd                                          }d}d}d}|r	 | j                                         | j        j                            |          }|rt          |dd          r|j	        S n3# t          $ r&}t                              d||           Y d}~nd}~ww xY w|                     |          }	|	|	S t          |          }
|
r|
d         }|
d	         }|
d
         }t          |                    d          p|pd                                                                          }t          |                    d	          p|pd                                                                          }t          |                    d
          p|pd                                          }|r|r|s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  rG  rR   r  Nz>Synthetic process-event session-store lookup failed for %s: %sr   r  r   r  z9Synthetic process event has invalid platform metadata: %rr  r  r  )r   r   r  r  r  r  )r  r  r7   r3   rT   rG  r  rO  rS   r  r   r   r  r  r  r8   r  rQ   r  r  r  r  r   r   )r  r  r  rG  derived_platformderived_chat_typederived_chat_idr  r[   cached_sourcer  r  r  r   r   r  s                   r"   _build_process_event_sourcez)GatewayRunner._build_process_event_source9  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 	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	#I /H1 0I 1II %I87I8rD  c                    K   |                      |          }|s1t                              d|                    dd                     dS t	          |j        d          r|j        j        nt          |j                  }d}| j        	                                D ]\  }}|j        |k    r|} n|sdS 	 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)zInject a watch-pattern notification as a synthetic message event.

        Routing must come from the queued watch event itself, not from whatever
        foreground message happened to be active when the queue was drained.
        zCDropping watch notification with no routing metadata for process %sr  r  NrQ   Tr  rR   r   r  r  ru  r  uA   Watch pattern notification — injecting for %s chat=%s thread=%sr
  )rJ  r   r   r3   r   r   rQ   r7   r0  rE  r  r  rW  rT   r  r   r  rP  r   r5  )
r  rD  r  r  r  r   r  r{
  synth_eventr  s
             r"   r
  z(GatewayRunner._inject_watch_notificationC:  s      11#66 	NNUi00   F18'1R1Rl--X[\b\kXlXlM'')) 	 	DAqw-'' (  	F	F&(-sww|44:;;AACCKt  K KKS 	   ((55555555555 	F 	F 	FLLA1EEEEEEEEE	Fs   5BE 
E=E88E=c                 `   |                     d          rdS t          |                     dd          pd          }|sdS |                     dd          |d<   |                     dd          |d<   |                     dd          |d<   |                     d          r|d         |d<   dS dS )a  Fill platform/chat_id/thread_id/chat_type on an async-delegation event.

        Async-delegation completion events only carry ``session_key`` (the
        daemon worker has no access to the per-message routing metadata the
        terminal background watcher captures at spawn time). Parse the
        session_key into the routing fields ``_build_process_event_source``
        expects. Best-effort: a CLI-origin event (empty session_key) is left
        as-is and simply won't route on the gateway.
        r   NrG  rR   r  r   r  )r3   r  )r  r  r  s      r"    _enrich_async_delegation_routingz.GatewayRunner._enrich_async_delegation_routingj:  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 	3r$   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 ]x}|                     |           t          |          }|s)	 |                     ||           d{V  G# t          $ r%}t                              d|           Y d}~qd}~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).
        rU  Nr   r  rl   r  z$Async delegation injection error: %sz"Async delegation watcher error: %s)r:  r  r  r  rI  r  r  r  r   r3   r4   r  rO  r  r
  r   r5  r  )r  r  rB  r  async_eventsr  rD  r  s           r"   r  z'GatewayRunner._async_delegation_watcher:  ss      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"==j#NNNNNNNNNN$ P P P%KQOOOOOOOOPP  F F FA1EEEEEEEEF-))))))))); m 	* 	* 	* 	* 	*sf   E, 
A$ #E, $
A1.E, 0A11B*E, D98E, 9
E(E#E, #E((E, ,
F6FF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  |                    |          }|nt          |j                  }||k    }|}|j
        rddl m}m} |r|                    |          sddlm} |j        r ||j                  nd}d}t          |          |k    rK|| d         }|                    d          }|dk    r||dz   d         n|}dt          |           d| }n|} |d||j        |j        t)          |dd          t)          |dd          |d           }|sn|                     ||||||	|
d!          }|st                              d"|           nd}| j                                        D ]\  }}||j        k    r|} n|r|j        r	 t7          |t8          j        |d|#          }t                              d$|||j        |j                   |                     |           d{V  n2# tB          $ r%} t          "                    d%|            Y d} ~ nd} ~ ww xY w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}%|&                    ||$tO          |%|0          1           d{V  n2# tB          $ 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}%|&                    ||$tO          |%|0          1           d{V  n2# tB          $ r%} t          "                    d2|            Y d} ~ nd} ~ ww xY w4t                              d6|           dS )7u  
        Periodically check a background process and push updates to the user.

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

        Notification mode (from ``display.background_process_notifications``):
          - ``all``    — running-output updates + final message
          - ``result`` — final completion message only
          - ``error``  — final message only when exit code != 0
          - ``off``    — no messages at all
        r   r  r  check_intervalrG  rR   r   r   r  r  r  r  Nnotify_on_completeFzCProcess watcher started: %s (every %ss, notify=%s, agent_notify=%s)r  Tz"Process watcher ended (silent): %s)r  r  )
strip_ansir  r   rW  r+   u'   [… output truncated — showing last z chars]
r  completion_reasonexitedtermination_source)rl   r  r  r  rV  rX  r  )r  rG  r   r   r  r  r  zHDropping completion notification with no routing metadata for process %srL  uU   Process %s finished — injecting agent notification for session %s chat=%s thread=%sz Agent notify injection error: %s>   r  r  r5  >   Nr   i)redact_terminal_outputr  z[Background process z finished with exit code z~ Here's the final output:
rw  r!   r   zWatcher delivery error: %sr  iz is still running~ New output:
zProcess watcher ended: %s)(r  r  r3   r7   rT   r0  r   r  r:  r  rW  r   output_bufferr  is_completion_consumedtools.ansi_striprU  rx  r  r  rS   rJ  r   r0  rE  r   r   r  r  rW  r  r  rP  r   r5  r   rY  rQ   r   rZ   )&r  r  r  r  r  rG  r  r   r  r  r  r  agent_notifynotify_modert  last_output_lencurrent_output_lenhas_new_outputr  	_pr_checkrU  _raw_LIMIT_tail_nlr  rD  r  r   r  r{
  rM  r  r
  
new_outputrY  r+
  	send_metas&                                         r"   r  z"GatewayRunner._run_process_watcher:  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R	F-)))))))))&**:66G!$W%:!;!;//AN0O~ GF
 nmmmmmmm B	(H(H(T(T B;;;;;;@G@U]::g&;<<<[]D
 "F4yy6)) $fWXX#jj..36"99cAghh%eUee^cee#!<!< ,&0#*?%,%6-4W>QS[-\-\.5g?SUW.X.X"&> > " "J & !==&0'2$1#*%.#*%.? ?  F " f&   "G $ 3 3 5 5 " "1//&'G!E 0  P6> PP*6%/-8-='-)-+5+ + +K #KK w * + & & 0   #*"8"8"E"EEEEEEEEE( P P P"LL)KQOOOOOOOOP
  #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cR	Fh 	0*=====sI   .A!N 
N?N::N?5R 
SR<<S
5V   
V/
V**V/)rN  r
  )rN  r  )rj
  r'  )rj
  	threshold)rj
  target_ratio)rj
  protect_last_n)r  r,  )r!	  rM  _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 rr  r   )r   rL  s     r"   r?  zDGatewayRunner._empty_honcho_cache_busting_config.<locals>.<dictcomp>;  s    DDDcTDDDr$   )_HONCHO_CACHE_BUSTING_KEYS)clss    r"   "_empty_honcho_cache_busting_configz0GatewayRunner._empty_honcho_cache_busting_config;  s    DDS%CDDDDr$   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)r  rR   rn  )plugins.memory.honcho.clientrv  rw  statst_mtime_nsr6   r7   ro  r3   rB   from_global_configuser_peer_aliases	peer_nameai_peerr   pin_peer_nameruntime_peer_prefixr   r7  rE  r   rt  )
rs  rv  rw  r;   mtime_nsmemo_keycachedhcfgaliasesr  s
             r"   $_extract_honcho_cache_busting_configz2GatewayRunner._extract_honcho_cache_busting_config;  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                 v   i }t          |t                    r|ni }| j        D ]W\  }}|                    |          }t          |t                    r|                    |          || d| <   Md|| d| <   X	 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.
        rE  Nr   )registry_generationztools.registry_generationr!	  rM  honcho)r   rB   rm  r3   tools.registryr  rS   r   r   r7   r8   r  r  rt  )	rs  r   r2  r  sectionrL  section_valr  rM  s	            r"   _extract_cache_busting_configz+GatewayRunner._extract_cache_busting_config;  sx    !'T::Bkk: 	/ 	/LGS'''**K+t,, /*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   <B B)(B)r  ry
  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          |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   NrP  rR   rO  rM  r  T)	sort_keysr   r  )
r  r  r7   r3   r  r  r  r7  rE  r  )rN  r  ry
  r  r  r  r;  r  _j_api_key_api_key_fingerprint_cache_keys_sortedblobs                r"   _agent_config_signaturez%GatewayRunner._agent_config_signature;  sb   J 	#""""""" w{{9b117R88PX`w~~hoo.?.?@@JJLLL^`#Z%52$<$<$>$>??xx$J++J++J++,<D'(((" !&B"GMr""K%2&& !  
 
$ ~~dkkmm,,6688"==r$   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).
        NrG  z/Failed to read persisted session model overrideTr~   rN  rM  rO  )rN  rM  rO  rP  r  r  zdCredential re-resolution failed for persisted override (provider=%s); using credential-less overridezIRehydrated persisted /model override for session=%s: model=%s provider=%srR   )	r  rS   get_model_overrider   r   r  r3   r  r  )r  rG  r  	persistedr  rM  r  s          r"   r9  z/GatewayRunner._rehydrate_session_model_override<  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.
        rN  )rM  rP  rO  r  r  NrP  r  rM  )r  r3   r  )r  rG  rN  r?  r  rL  r  s          r"   r:  z+GatewayRunner._apply_session_model_overrideS<  s     044[AA 	).((We,,U 	* 	*C,,s##C&)s#y))	""#455=Z(( > 1NZ((1 1N,- n$$r$   agent_modelc                 p    | j                             |          }|duo|                    d          |k    S )zGReturn True if *agent_model* matches an active /model session override.NrN  )r  r3   )r  rG  r  r  s       r"   _is_intentional_model_switchz*GatewayRunner._is_intentional_model_switchp<  s9    044[AAt#LW(=(=(LLr$   rY
  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.
        FNrY  z%Failed to release active session slotTr~   r^  )r
  rS   r  releaser   r   r  rX  r  r   r^  r  )r  rG  rY
  leases       r"   rR  z*GatewayRunner._release_running_agent_stateu<  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          |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_notesrj  rl  r   r  z?Failed to clear slash-confirm state for session boundary %s: %sclear_sessionz:Failed to clear approval state for session boundary %s: %s)rS   r   rB   r  rS	  r  r   r  r   r  r  r  )r  rG  pending_skills_reload_notespending_approvalsupdate_prompt_pendingr	  r  _clear_approval_sessions           r"   &_clear_session_boundary_security_statez4GatewayRunner._clear_session_boundary_security_state<  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_  Nr+   )__dict__r3   r_  r   )r  rG  generationsnext_generations       r"   r	  z+GatewayRunner._begin_session_run_generation<  sj      	1m''(ABBK+6D(kook1==>>B#2K r$   c                n    |                      |          }|rt                              d|||           |S )z7Invalidate any in-flight run token for ``session_key``.u-   Invalidated run generation for %s → %d (%s))r	  r   r  )r  rG  r$  r
  s       r"   rY	  z0GatewayRunner._invalidate_session_run_generation<  sG    77DD
 	KK?	   r$   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  r3   r   )r  rG  r
  r  s       r"   r
  z%GatewayRunner._is_session_run_current<  sQ     	4m''(ABBHb;??;2233s:FFr$   c                     |r|r|dS 	 t          |di                               |          }| t          |dt          |                     dS dS # t          $ r Y dS w xY w)zDBind a gateway run generation to the adapter's active-session event.Nr  r  )rS   r3   rY  r   r   )r  r   rG  r
  interrupt_events        r"   r
  z*GatewayRunner._bind_adapter_run_generation<  s      	k 	Z-?F	%g/A2FFJJ;WWO*)A3z??SSSSS +* 	 	 	DD	s   AA 
A A T)release_running_stater  r  r  c                  K   |sdS | j                             |          }|r|t          ur|                    |           |                     ||           | j                            |j                  }|r1t          |d          r!|                    ||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_activityrI  )rX  r3   r7  r  rY	  r0  r   r   r  r   rI  rZ  r  rR  )r  rG  r  r  r  r  rE  r   s           r"   r]	  z*GatewayRunner._interrupt_and_clear_session=  s=       	F,00== 	6]2III##$4555//DW/XXX-##FO44 	Rww(DEE 	R44[&.QQQQQQQQQ 	5ww(=>> 	5''444"";555  	;--k:::::	; 	;r$   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.
        Nre  rd  message_countr   rV  rU  r+   )	rp  rS   rW  r3   r   r   rK  r   r7  )	r  rG  r  rF  rz  	_sess_row_liver  _snapshot_sids	            r"   r
  z0GatewayRunner._refresh_agent_cache_message_count&=  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c           	         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.
        re  Nrd  r   c                 B    h | ]}||t           ut          |          S rr  r7  rk   r   r{
  s     r"   r   z4GatewayRunner._evict_cached_agent.<locals>.<setcomp>=  8     
 
 
}*A!A!A qEE!A!A!Ar$   rX  Tzagent-evict-r  r  r  daemonrt   )rS   rd  r  r   rK  r7  r  rk   rS  Thread_release_evicted_agent_softr7   r  r   )r  rG  rM  evictedrz  r  running_idss          r"   r  z!GatewayRunner._evict_cached_agentq=  s   0 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<   A  AA$AD. .
E$9E
E E$E  E$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)r  _last_activity_ts_last_activity_descr   r  _api_call_count)r  r  s     r"   _init_cached_agent_for_turnz)GatewayRunner._init_cached_agent_for_turn=  sP     a&*ikkE#(DE% u455 /-.* !r$   rL  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_managerrG  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   rS   r  rO  r3   is_session_finalizabler6  r  r   rY  r   r  r   )r  r  rL  _storer  r~  r  s          r"    _commit_memory_before_soft_evictz.GatewayRunner._commit_memory_before_soft_evict=  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  rL  s      r"   _commit_then_release_softz'GatewayRunner._commit_then_release_soft=  s4     	--eS999((/////r$   c                     |dS 	 t          |d          r|                                 n|                     |           n# t          $ r Y nw xY wt          |d          r	g |_        dS dS )u  Soft cleanup for cache-evicted agents — preserves session tool state.

        Called from _enforce_agent_cache_cap and _sweep_idle_cached_agents.
        Distinct from _cleanup_agent_resources (full teardown) because a
        cache-evicted session may resume at any time — its terminal
        sandbox, browser daemon, and tracked bg processes must outlive
        the Python AIAgent instance so the next agent built for the
        same task_id inherits them.
        Nrelease_clientsr  )r   r  r  r   r  )r  r  s     r"   r  z)GatewayRunner._release_evicted_agent_soft
>  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.
        rd  NrS
  c                 B    h | ]}||t           ut          |          S rr  r  r  s     r"   r   z9GatewayRunner._enforce_agent_cache_cap.<locals>.<setcomp>A>  r  r$   rX  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  )rS   r   r  r  r   _AGENT_CACHE_MAX_SIZErY  r  r3   r   rK  rk   r4   r  r   r   r  rS  r  r  r  )r  rz  r  excess
evict_planordered_keysrL  r  r  rE  remaining_over_caps              r"   _enforce_agent_cache_capz&GatewayRunner._enforce_agent_cache_cap'>  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	  
 %'''#	 	r$   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.
        rd  Nre  r   c                 B    h | ]}||t           ut          |          S rr  r  r  s     r"   r   z:GatewayRunner._sweep_idle_cached_agents.<locals>.<setcomp>>  r  r$   rX  r  rG  z3Agent cache idle-TTL evict: session=%s (idle=%.0fs)Tzagent-cache-idle-r  r  )rS   r  r  rY  rE  r   rK  rk   _AGENT_CACHE_IDLE_TTL_SECSr  rO  r3   r   r  r6  r4   r  r   r  rS  r  r  r  r   )r  rz  rM  r  to_evictr  rL  r  r  last_activityr"  r  rE  s                r"   r9  z'GatewayRunner._sweep_idle_cached_agentsy>  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                 F   t          j        dd                                          }|r|                    d          S t	                      }|                    d          pi                     d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_URLrR   r   r%  	proxy_urlN)r1   r  rT   rc  r~  r3   )r  r  r  s      r"   _get_proxy_urlzGatewayRunner._get_proxy_url>  s     i+R006688 	#::c??""$$wwy!!'R,,["==CCEE 	#::c??"tr$   r
  c	                 d   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          |          }                     ||          }|rJ	 ddlm}m}  j        
                    |j                  }|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'        |(                                          }' j        
                    |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rK	  r~  r  rS	  uH   ⚠️ Proxy URL not configured (GATEWAY_PROXY_URL or gateway.proxy_url)GATEWAY_PROXY_KEYrR   r   c                  <     sdS                                 S rq  r
  rY
  r  rG  s   r"   _run_still_currentz>GatewayRunner._run_agent_via_proxy.<locals>._run_still_current?  )    %[%t//^LLLr$   r3  r  r  r   >   r4  r  r4  zContent-Typezapplication/jsonzBearer AuthorizationzX-Hermes-Session-Idzhermes-agentT)rN  r~  streamNr  	streamingStreamingConfigr   r  GatewayStreamConsumerStreamConsumerConfigpause_typing_for_chatc                 0    |                      |           d S rr  r  r  _chat_ids     r"   _pause_typing_before_finalizezIGatewayRunner._run_agent_via_proxy.<locals>._pause_typing_before_finalizeV?  s     %::8DDDDDr$   SUPPORTS_MESSAGE_EDITINGFfresh_final_after_secondsr/  editr  edit_intervalbuffer_thresholdcursorbuffer_onlyr  	transportr  )r   r   r  rU   on_before_finalizeinitial_reply_to_idrun_still_currentz+Proxy: could not set up stream consumer: %sr   r  )r  	sock_readr8  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 currentr  )rK	  r~  r  rS	  r  r  response_previewedr  r   )rS  r   r+   zdata:    z[DONE]choices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 charsr  z(No response from remote agent)r  rH  )Baiohttpr  r  r  r  r1   r  rT   r   r4   r3   rS   r  r  ry  r   r~  r   r   r'  r
  r  gateway.stream_consumerr  r  r0  r  r  r   r   r  MATRIXr   r  r  r   r   r  r:  rI  r0  send_typingr  postr  r   r   finishr?  r  r  rm  r   iter_anyr  r   rB  rM  rr  r  r  on_deltar  #_GATEWAY_PROXY_SSE_BUFFER_MAX_CHARSr   r5  )8r  rz   r
  r-  r  r  rG  rY
  r   _AioClientSessionr  r  	proxy_keyr  api_messagesr  r  r   r  r   _stream_consumer_scfgr  r   r   r   _plat_streaming_streaming_enabledrH  r  r  r  r  _adapter_supports_edit_effective_cursor_buffer_only_fresh_final_secs_consumer_cfg_sc_errstream_taskfull_response_start_timeoutrt  resp
error_textr  r  r   r^  r  objr  r  r  _elapseds8   `     ``                                                r"   _run_agent_via_proxyz"GatewayRunner._run_agent_via_proxy>  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________=,,V_== (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 =$$V_55 	**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 
LK==L"M4 4
N N] 9"]A)\%]] R/SS\%0\6A\%9]] 6V/WW	B\%A<[\%[!	\% [!	!1\%]%
\/	/]2\/	3]6] 
]] ]] b `3'``b 8_/``b `b 1a /b ?b c1b;:c1;/c-*c1,c--c1r   _interrupt_depthr   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.
        r  Nr  F)rG  rY
  r3  r   r   r
  r
  r
  )rS   _run_agent_inner _resolve_profile_home_for_sourcer
  )r  rz   r
  r-  r  r  rG  rY
  r3  r   r   r
  r
  r
  r   s                  r"   r
  zGatewayRunner._run_agent@  sc     2 wtXt446JERR 	..&*'!1DT-*%9'= /          <<VDD#L11 	 	..&*'!1DT-*%9'= /        	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	s   /(B$$B(+B(c                     ddl m}m} 	 |j        pd                                p |            pd} ||          S # t
          $ r ddlm}  |            cY S w xY w)u/  Resolve which profile's HERMES_HOME should serve this inbound source.

        Prefers the profile the source was routed to (``source.profile`` — set
        by the /p/<profile>/ URL prefix or a per-credential adapter), falling
        back to the active profile (the multiplexer's own home).
        r   )r  get_profile_dirrR   r   )r  )r  r  r8  r  rT   r   r  r  )r  r  r  r8  rt   r  s         r"   r6  z.GatewayRunner._resolve_profile_home_for_source=@  s     	QPPPPPPP	%N(b//11[5L5L5N5N[R[D"?4((( 	% 	% 	%888888"?$$$$$	%s   1< AAc           )      E   	
Çć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(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#                  } tK          | d-d          }!t          |!t                    rktM          | d.          r[|!'                                D ]F\  }"}#t7          |#          t7          j(                  k    r| )                    |"          r|"d<    nGtU          j+                     fd/t           ĉd0                    r j$                            j                  nd}$|$$tY          |$          j-        t\          j-        u rdd}$g dgd1dd2t6          d"t6          d#t6          d$t          f fd3t_          j        j0        	          }%|%r%|%j0        k    r 1                    	          nd4|%indte          j        5          j        j3        j"        fv rj0        r	r	ndfd6}& fd7}'dgdgdgdgtU          j+                     j4        d8t&          d9tj          ddffd:d2t6          d;t          ddffd< j$                            j                  j(        j        j3        k    rj0        r	r|%	d=n|%r 1                    	          ndd2t6          d>t6          ddffd?
	 ÈĈf)d@}(d})rtU          j6         |'                      })d}*rtU          j6         |&                      }*d}+fdA},tU          j6         |,                      }+ fdB}-tU          j6         |-                      }.tU          j7                     fdC}/tU          j6         |/                      }0tq          dDdE          }1|1dk    r|1nd |dFddG          d+k    rdts          j9                     fdH}2tU          j6         |2                      }3ddIdJt6          dKt
          dt
          fdL}4	 tq          dMdN          }5|5dk    r|5nd}6tq          dOdP          }7|7dk    r|7nd}8d}9tU          j:         ;                    |(                    d}:dQ};|6$d}<	 tU          j<        h|;R           d{V \  }=}>|=r=                                }<n艛>                                s҉rЉ j$                            j                  }?d         }@|?r|@rtM          |?dS          r|??                              r|?j@                                      }A|Ar|AjA        nd}Bt          C                    dT|0D                                rdUndV           |@E                    |B                                            n:d}<	 tU          j<        h|;R           d{V \  }=}>|=r=                                }<nd         }CdW}D|CrLtM          |CdX          r<	 |CF                                }E|E                    dYdW          }Dn# t(          $ r Y nw xY w|9s|8|D|8k    rd}9 j$                            j                  }F|Frt'          |8dZz            pd[}Gt'          |6|8z
  dZz            pd[}H	 |FG                    j(        d\|G d]|H d^_           d{V  n2# t(          $ r%}It          H                    d`|I           Y d}I~Ind}I~Iww xY w|D|6k    rd}:n艛>                                s҉rЉ j$                            j                  }?d         }@|?r|@rtM          |?dS          r|??                              r|?j@                                      }A|Ar|AjA        nd}Bt          C                    dT|0D                                rdUndV           |@E                    |B                                            7|:rd         }Ji }K|Jr6tM          |JdX          r&	 |JF                                }Kn# t(          $ r Y nw xY w|K                    dadb          }L|K                    dYd          }M|K                    dc          }N|K                    ddd          }O|K                    ded          }Pt          I                    df|M|6|L|O|P|Npdg           |Jr*tM          |Jdh          r|JE                    t                     t'          |6dZz            pd[}Qdi|Q djg}R|Nr$|RK                    dk|N dl|Mdmdn|O do|P dp	           n#|RK                    dq|L dr|Mdmds|O do|P dt	           |RK                    du           dvL                    |R          d         rd                             dwg           ng |Od         pg dddx}<d         }Sd         }T|Tr|T                    dy          nd}U|StM          |Sdz          r|Ust                      }V	 dd{lNmO}WmP}X tK          |Sd|d}          pd}}Y|Yr|Y|Wvr |X|V|Y          }Vn# t(          $ r Y nw xY w|SjQ        |Vk    r0 R                    |SjQ                  s S                               d         }Z j$                            j                  }[d}\d}]|Zr|[rr}t          |[          }\ U                    |[|\          }\|Z                    d~          r_|\s]|Z                    d          rH|Z                    d          }^t          |^          r t          C                    dpd|^           n|^}]n|\r|\jA        pd}}_tK          |\dd          pg }`tK          |\dd          pg }ag }bt          |`          D ]w\  }c}d|ct          |a          k     r|a|c         nd}}e|eY                    d          p(tK          |\dd          t          j[        t          j\        fv }f|fr|bK                    |d           x|br	  ]                    |_|b           d{V \  }g}h|gpd}]|hr ^                                rqj0        r	d4j0        ind}i|hD ]\}j	 |[G                    j(        d|j d|i_           d{V  +# t(          $ r%}kt          H                    d|k           Y d}k~kUd}k~kww xY wnT# t(          $ r6}lt          _                    d|l           |_pt          |\          }]Y d}l~lnd}l~lww xY w|_pt          |\          }]|]r#t          H                    d|]dd                    |Zr@|]s>|\s<|Z                    d          }m|mr%|m}]t          H                    d|]dd                    |]r|]a                                Y                    do          r|]a                                b                    dd[          }n|nr"|nd         d[d         c                                nd}}o|orB	 ddldme}p  |p|o          rt          C                    d|o           d}\d}]n# t(          $ r Y nw xY w jf        r8|\s|]r4t          C                    dpd g                                           d}\d}]|\s|]r7t          H                    d|]dd                    |[r:tM          |[d          r*r(|[jh        v r|[jh                 i                                  jj        k    r	t          _                    d            j$                            j                  }[|[r|\rt          |[j@        |\           n(|[r&tM          |[d          r|[l                    |]           d         p|<d	 |)r|)m                                 |*r|*m                                 |0m                                 |3m                                 |+ro	d         du}q|qs3|+m                                 	 |+ d{V  n# tT          jn        $ r Y nvw xY w	 tU          jo        |+dQR           d{V  nT# tT          jp        tT          jn        f$ r6 |+m                                 	 |+ d{V  n# tT          jn        $ r Y nw xY wY nw xY w|.m                                 r q                                jf        r r                    d           |)|*|0|.|3fD ]#}r|rr	 |r d{V  # tT          jn        $ r Y w xY w$S |Z                    d~          }s|ssyd         }t|tr|+r	 tU          jo        |+dQR           d{V  n# tT          jp        tT          jn        f$ r6 |+m                                 	 |+ d{V  n# tT          jn        $ r Y nw xY wY n1t(          $ r%}ut          H                    d|u           Y d}u~und}u~uww xY wt          |Z                    d                    }v|Z                    dd}          }w |4|t|w|vI          }x|wrv|xst	 t          C                    dpd           |[G                    j(        |w_           d{V  nQ# t(          $ r%}ut          _                    d|u           Y d}u~un'd}u~uww xY w|wrt          C                    dpd           tK          tY          |[          dd          _|[s                              }yt          |y          r8	  |y            }zt          jv        |z          r|z d{V  n# t(          $ r Y nyw xY wnt|[rrtM          |[d          rb|[jw        x                    d          }yt          |y          r8	  |y            }zt          jv        |z          r|z d{V  n# t(          $ r Y nw xY w|Z                    dw          }{}||]}}d}~d}}|\tK          |\dd          p}| y                    |\          r z                              st          C                    dpd           |Z|)r|)m                                 |*r|*m                                 |0m                                 |3m                                 |+ro	d         du}q|qs3|+m                                 	 |+ d{V  n# tT          jn        $ r Y nvw xY w	 tU          jo        |+dQR           d{V  nT# tT          jp        tT          jn        f$ r6 |+m                                 	 |+ d{V  n# tT          jn        $ r Y nw xY wY nw xY w|.m                                 r q                                jf        r r                    d           |)|*|0|.|3fD ]#}r|rr	 |r d{V  # tT          jn        $ r Y w xY w$S 	  {                    ||          }n/# t(          $ r" t          H                    dpdd           Y nw xY w |                    |\|||{|           d{V }}|}|Z|)r|)m                                 |*r|*m                                 |0m                                 |3m                                 |+ro	d         du}q|qs3|+m                                 	 |+ d{V  n# tT          jn        $ r Y nvw xY w	 tU          jo        |+dQR           d{V  nT# tT          jp        tT          jn        f$ r6 |+m                                 	 |+ d{V  n# tT          jn        $ r Y nw xY wY nw xY w|.m                                 r q                                jf        r r                    d           |)|*|0|.|3fD ]#}r|rr	 |r d{V  # tT          jn        $ r Y w xY w$S  }                    |\          }~tK          |\dd          } j$                            j                  }|r4	 |~                    j(        _           d{V  n# t(          $ r Y nw xY w                                d{V                       |}|{|||d[z   |~|
  
         d{V }t          |Z|          |)r|)m                                 |*r|*m                                 |0m                                 |3m                                 |+ro	d         du}q|qs3|+m                                 	 |+ d{V  n# tT          jn        $ r Y nvw xY w	 tU          jo        |+dQR           d{V  nT# tT          jp        tT          jn        f$ r6 |+m                                 	 |+ d{V  n# tT          jn        $ r Y nw xY wY nw xY w|.m                                 r q                                jf        r r                    d           |)|*|0|.|3fD ]#}r|rr	 |r d{V  # tT          jn        $ r Y w xY w$S 	 |)r|)m                                 |*r|*m                                 |0m                                 |3m                                 |+ro	d         du}q|qs3|+m                                 	 |+ d{V  n# tT          jn        $ r Y nvw xY w	 tU          jo        |+dQR           d{V  nT# tT          jp        tT          jn        f$ r6 |+m                                 	 |+ d{V  n# tT          jn        $ r Y nw xY wY nw xY w|.m                                 r q                                jf        r r                    d           |)|*|0|.|3fD ]#}r|rr	 |r d{V  # tT          jn        $ r Y w xY w$n# |)r|)m                                 |*r|*m                                 |0m                                 |3m                                 |+ro	d         du}q|qs3|+m                                 	 |+ d{V  n# tT          jn        $ r Y nvw xY w	 tU          jo        |+dQR           d{V  nT# tT          jp        tT          jn        f$ r6 |+m                                 	 |+ d{V  n# tT          jn        $ r Y nw xY wY nw xY w|.m                                 r q                                jf        r r                    d           |)|*|0|.|3fD ]#}r|rr	 |r d{V  # tT          jn        $ r Y w xY w$w xY wd         }tt          |<t                    rn|<                    dy          sX|<                    d          pd}}| p|dk    }t          |<                    d                    }vt          |totK          |tdd                    }t          |<                    d                    } |4|t||vI          }|s,|s*|s|r&t          C                    dpd||v|           d|<d<   n|s|r|t|tj        }|r	 |tj                            j(        ||<d         d           d{V  d|<d<   t          C                    d|pd           n5# t(          $ r(}t          _                    dpd|           Y d}~nd}~ww xY wr|$rrt          |<t                    r|<                    dy          stM          |$d          rtk                    j(        |$tU          j+                    dfd}	 |$                    |           n2# t(          $ r%}t          H                    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.
        )rz   r
  r-  r  r  rG  rY
  r   Nr   rt
  r   c                  <     sdS                                 S rq  r  r  s   r"   r  z:GatewayRunner._run_agent_inner.<locals>._run_still_currentx@  r  r$   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_overridesr  tool_progress_grouping
accumulate)choose_status_phraseresolve_status_phrase_catalogF)r   r   allow_genericr   r   r   rF  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>@  s0     ! ! ! ,D11! ! !r$   r  genericr  )r   r   r   r   r7   rT   r8   r   )r   r   r   rF  r   r   rQ   r   r   r  r   s          r"   _display_surface_modez=GatewayRunner._run_agent_inner.<locals>._display_surface_mode@  s     - 
!#:6?#K#K ! ! =! ! !
 %55:;V]^^ 6 !5++KwPWXXE%%% =%++--*=*=*?*?9*L*L$1<yyu< KK255U2r$   )r  r	  r  kindr  r	  r  c                    	  | |||          S # t           $ r-}t                              d|           | dv rdndcY d }~S d }~ww xY w)N)r  r	  r  r  catalogz*generic status phrase selection failed: %s>   r  waiting	heartbeatlong_runningzstill on itzone sec)r   r   r  )rL  r  r	  r  _phrase_err_generic_status_catalog_generic_status_recentrD  s        r"   _generic_status_phrasez>GatewayRunner._run_agent_inner.<locals>._generic_status_phrase@  s    r++'#13     r r rI;WWW(,0b(b(b}}hqqqqqqqrs    
A"A AAr  >   logr  rV  interim_assistant_messages)r   r   r  thinking_progressr  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 errorry  zvoice ack schedule failed: %s)	r0  r3   r$
  r   r   r[  r   r   r  )r  r  r  r  _ack_errr  r  _voice_ack_fired_voice_ack_guild_voice_ack_loopr  s        r"   voice_ack_callbackz:GatewayRunner._run_agent_inner.<locals>.voice_ack_callback A  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                 
   +q| dk    rg|re|dk    r_t          j                                        d          }|rd| dnd}+                    | d| d	|                                            .sdS .r
 %            sdS | d
k    r߉,d         s	 |                    d          pd}|$k    r-dk    r~ddlm}m}	m	}
m
} t                      }t          t          |dd          d          }|rB |	||          s6d,d<   .                     |                        |
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.                    |           dS 2sdS | dvrdS 	 'r'd         nd}|t%          |dd          rdS n# t          $ r Y nw xY w-dk    r|)d         k    rdS |)d<   ddlm}  ||d          }d}d}	 0j                            1j                  }n# t          $ r d}Y nw xY wt%          |dd          r|dk    rt/          |t0                    rt/          |                    d          t2                    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#}-d)k    r|d*d<   .                    |           dS d*d<   |rddlm}  |            }t=          j        |dt2          *          }|dk    r#t;          |          |k    r|d|d&z
           d'z   }| d | d+tA          |!                                           d,| }n|r| d | d-| d}n| d | d'}.                    |           dS ||}d*d<   n|rdd.lm}m"} m#}!m$}"  |            }|dk    r|nd$}t;          |          |k    r|d|d&z
           d'z   } | |          }#|#r( |"|          r| d |# }n | d |#  |!|           | }n| d | d-| d}d*d<   n| d | d'}d*d<   |(d         k    r0/dxx         d%z  cc<   .                    d/|/d         f           dS |(d<   d/d<   .                    |           dS )0z3Callback invoked by agent on tool lifecycle events.Ntool.started	_thinkingz%Y-%m-%d %H:%M:%Sz "rX  rR   z  r  ztool.completedr   r
  r  )TOOL_PROGRESS_FLAGr  r  tool_progress_hint_gatewayr   tool_progress_commandFr|  Tr  z(tool-progress onboarding hint failed: %su   💬 >   rc  is_interruptedr  )get_tool_emojiu   ⚙️supports_code_blocksr  r  )get_tool_preview_max_lenrL  r   r  r  (   r+   rU  r	  z ...r	  )ensure_asciir   (z)
z: ")rk  get_tool_verbtool_verb_connectorverb_drops_preview	__dedup__)%r   r  strftimer  rc  r3   r  re  r  r  rf  r~  r  r   r  r   r   r  rS   agent.displayri  r0  r   r   rB   r7   rT   rk  r\  r   r  r  rY  r  ro  rp  rq  )3r   r  r	  r  kwargsri  preview_strr
  re  r  r  rf  r  gate_on	_hint_errthinking_textr  _agent_for_interruptri  emoji_code_block_full_code_block_short_progress_adapterrk  	_cmd_full_block_header_pl_cap_lines
_cmd_short
_multilineargs_strro  rp  rq  r  _LONG_TOOL_THRESHOLD_Sr  _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_enableds3                                       r"   progress_callbackz9GatewayRunner._run_agent_inner.<locals>.progress_callbackJA  sP   
 $//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:F'P|AD$'3(*:E9 93 F    %%)y|*C*C$IaL 544444"N9h???E  $ $)$(M$5$5fo$F$F!! ) ) )$(!!!) )+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#####s=   B!D4 4
E#>EE#/G 
GGH2 2I Ir  r!   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logsTr  ztool_calls.logi  P rU  r  )maxBytesbackupCountr  z%(message)szhermes.tool_calls.Fr  333333?zwrite_tool_log error: %sr+   )logging.handlersr  r   r  r  r  setFormatterr  r  rk   setLevelINFO	propagate
addHandlerr  r  Emptyr:  r  r   r   r5  r  removeHandlerflushr  )r  r  log_dirfile_handlertool_loggerr  r  r  s         r"   write_tool_logz6GatewayRunner._run_agent_inner.<locals>.write_tool_log9B  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 *j                             +j                  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t0          ffd}	 	  #            sP'                                s:	 '                                 n# t          $ r Y nw xY w'                                :d S '                                }	 $r$d	         nd }|,t          |dd
          rt3          j        d	           d {V  n# t          $ r Y nw xY wt          |t6                    rBt          |          dk    r/|d	         dk    r#|\  }}}	r| d|	dz    dd<   rd         n|}
n[t          |t6                    r/t          |          dk    r|d	         dk    rd g d %d	<   d	)d	<   W|}
                    |
            |             d {V r[t;          j                    } t3          j        d            d {V   #            r"                    +j         !!           d {V  t;          j                    }||| z
  z
  }|d	k    rt3          j        |           d {V   #            sd S r85d"!                              } |           d {V }|j"        st          |d#d$          pd$#                                }t          |d%d
          r"tH          %                    d&j&                   d'|v sd(|v r4tH          '                    d)j&                   t;          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)                             t;          j                    } t3          j        d            d {V   #            r"                    +j         !!           d {V  n'# (j*        $ r t3          j        d            d {V  Y n t2          j+        $ r '                                sC	 '                                }t          |t6                    rFt          |          dk    r3|d	         dk    r'|\  }}}	r| d|	dz    dd<    |             d {V  nt          |t6                    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?}tH          ,                    d,|           t3          j        d           d {V  Y d }~nd }~ww xY w~).Nseparater/  g      ?MAX_MESSAGE_LENGTHr  r+   r   @   r   FrU   c              3   F   K   | ]}|j         t          j        j        u V  d S rr  )rL  inspect	ParameterVAR_KEYWORD)r   params     r"   ru  zQGatewayRunner._run_agent_inner.<locals>.send_progress_messages.<locals>.<genexpr>B  sC         % "J'*;*GG     r$   r  r   c                 ~   K   j         | |d}t          dd          rd|d<   r|d<    j        di | d {V S )N)r   r  r   REQUIRES_EDIT_FINALIZEFTfinalizerU   r   )r   rS   edit_message)r  r   ru  _edit_accepts_metadata_progress_metadatar   r  s      r"   _edit_progress_messagez^GatewayRunner._run_agent_inner.<locals>.send_progress_messages.<locals>._edit_progress_messageB  s|      %~",& 
 7$<eDD .)-F:&) <);F:&1W1;;F;;;;;;;;;r$   r;  r   c                 @    d                     d | D                       S )Nr   c              3   4   K   | ]}t          |          V  d S rr  rs  )r   r^  s     r"   ru  ziGatewayRunner._run_agent_inner.<locals>.send_progress_messages.<locals>._progress_text.<locals>.<genexpr>B  s(       = =tT = = = = = =r$   )rA   )r;  s    r"   _progress_textzVGatewayRunner._run_agent_inner.<locals>.send_progress_messages.<locals>._progress_textB  s#    yy = =u = = ====r$   c                     g }g }| D ]=}||gz   }|r1  |                    k    r|                     |           |g};|}>|r|                     |           |S )z>Partition progress lines into platform-sized editable bubbles.)r4   )r;  groupsr  r^  r   _PROGRESS_TEXT_LIMIT_progress_len_fnr  s        r"   _split_progress_groupsz^GatewayRunner._run_agent_inner.<locals>.send_progress_messages.<locals>._split_progress_groupsB  s    %' "! , ,D '4& 0I ,#3#3NN94M4M#N#NQe#e#eg...#'&"+ +MM'***r$   c                     rKt          | dd          r<t          | dd           r-                    t          | j                             d S d S d S d S )Nr  Fr  )rS   r4   r7   r  )r  _cleanup_msg_ids_cleanup_progresss    r"   _track_progress_resultz^GatewayRunner._run_agent_inner.<locals>.send_progress_messages.<locals>._track_progress_resultB  s    %D	599D  d;;D
 %++C0A,B,BCCCCCD D D D D Dr$   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_textB  sc      &||"N //	  ,           '&v...r$   c                    K   	rsdS  	          } t          |           dk    rdS  | d                   }
 
|           d{V }|j        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 )zStart fresh editable progress bubbles before a bubble exceeds limit.

                Returns True when it delivered/split the current buffer and the
                caller should skip the normal send/edit path for this tick.
                Fr+   r   NrW  T)r   r  r  )r  
first_textr  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_neededB  sI      & !X ! 5//??v;;!## 5+^F1I66
".#9#9/:#V#VVVVVVVF!> %#($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*;
 "(tr$   Trh  rU  rr  u    (×r  rW  	__reset__r  r   r   r5  rR   	retryableu5   [%s] Transient edit failure — keeping can_edit=Truefloodzretry afterz-[%s] Progress edit flood control, backing offr_  r  zProgress message error: %srH  )-r0  r3   r   rl   r  r  r  r  r   r   message_len_fnr   r   rS   r  r  rI  
parametersr  r  r  r   r7   rY  r   r:  r  rK  r4   r  r  r  r   rA   r  r8   r   r  rt   r  r   r  r  r  r5  ),_last_edit_ts_PROGRESS_EDIT_INTERVAL_raw_progress_limit_edit_paramsr  r  rz  rE  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_messagespB  s     ! m''88G 
 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 " " " " " " " " " " " "H|+{+--// "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  ,B 
BB C: :D	D	,AE: :FF
Y )H> =Y >
IY 
IY $Y 99J4 3Y 4
K>Y  KBY B Y !;Y 
Y *BY 7F%Y $b$b*C_/^_
^_^7_b
_b_?b`'&b'
`41b3`44b:	b5a==b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 )Nrt   rR   z
agent:step)r   r  r  r  
tool_namesrS	  z agent:step hook scheduling errorry  )r   rB   r4   r3   r7   r   r  r   rQ   r  r   )	r  r  _names_t
_hooks_ref_loop_for_stepr  r  r  s	       r"   _step_callback_syncz;GatewayRunner._run_agent_inner.<locals>._step_callback_syncC  s    %%''  !#F!'R + +b$'' +MM"&&.."6B7777MM#b''****$9? P 5 5b%~",!*"('/ /   >     r$   rw   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  r   r   r  )r   rw   r  r  r  s      r"   _event_callback_syncz<GatewayRunner._run_agent_inner.<locals>._event_callback_syncC  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  rz   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: %sr  rR      zstatus_callback (z) scheduling errorry  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 )Nr  r  F)r  r   rS   r4   r7   )r|  resmidr  s      r"   _track_status_idzWGatewayRunner._run_agent_inner.<locals>._status_callback_sync.<locals>._track_status_idD  s    !jjll$   !#|T::CsIu55 :# :(//C99999: : : :s    
&&rH  )
r   r   r   r  rQ   r   r7   r   r   rk  )r   rz   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_syncC  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 	9r$   c                  ,  )nopqrst j         vj        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 sd }
t          t          dd           dd           }|ddlm}  |            } | d          }||j        o
|j        dk    nt-          |          }|}}|}|s|rh	 ddlm}m} j                            j                   }|r
d }j         vj        k    rt9          |d          r|j        f	 dd}t          |dd          }|st;          d          |j        }d}j         vj        k    rd}d}j         vj        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 |{           s|rd!tF          dd f{sfd"}
sd<   n2# t          $ r%}t          
                    d#|           Y d }~nd }~ww xY wdd$d!tF          d%t,          dd fz{|~sfd&}$                    ||          }%                    |d'         |d(         |&                              t          d)d           t          d*d           +          }d }d} t          d,d           }!t          d-d           }"d }#j'        KrI	 j'        j(        )                              }$|$r|$                    d.d          }#n# t          $ r Y nw xY wd }%|!rv|"s|!5  |"                              }&|&rA|&d/         |k    r4tU          |&          d0k    r|&d0         nd }'tU          |&          d1k    r|&d1         nd }(|(d uo	d uo|(k    })|)sq|'o|#m|#|'k    rgt          +                    d2|'|#           j,        -                    d           }*t]          |*t^                    r
|*r|*d         nd }+|+r|+t`          ur|+}%ny|&d         }t9          |"d3          r'	 |"1                               n# td          $ r Y nw xY w3                    |y           ||_4        t          
                    d4           d} d d d            n# 1 swxY w Y   |%	 tk          j6        j7        |%fdd5tG                    d d6          7          8                                 n7# t          $ r* 	 7                    |%           n# t          $ r Y nw xY wY nw xY w| udd'|d'         i|d(         i d8|d9dd:dd;d<d=|pd d>j9        pd d?|	d@j        dA|                    dA          dB|                    dC          dD|                    dE          dF|                    dG          dH|                    dI          dJ|                    dKd          dL|                    dM          dNdO| d)j:        d*j;        dPj<        dQj        dRj=        dj>        dj?        dSdTt          j'        dUj'                  dVj@        }|!r9|"7|!5  |||#f|"<   A                                 d d d            n# 1 swxY w Y   t          
                    dW|           srnd |_B        d         nd |_C        xjD        rnd |_E        |
|_F        |r|nd |_G        }|_H        dz{|fdX},|,|_I        d |_J        w|_K        |	|_L        j        |_M        |                    dA          pi |_N        tk          jO                    qg otk          jP                    pdYtF          dd fz{|~fdZrdopqrfd[}-dYtF          dd fopqr{|fd\}.|.|_Q        |rQrOt          t          |          d]d           |S                    |-^           nt          |d_d           }/|/|-|/<                       d`i                               da          }0t]          |0t,                    r|0rdbnd}0|0r!tG          |0          T                                ndb|_U        dctF          dtF          fz|~fdd}1|1|_V        |_W        |d<   t9          |de          r|jX        nd d<   t          t          t                                f          \  }2}3| rqt          |dNd           k    r\t          |2t          |dgd                     }4|4|2ur9t          ]                    dhtU          |2          tU          |4                     |4}2t          |2          }5ddil_m`}6ma}7mb}8mc}9 djt          dd fnz|~fdk}:};}<t          dli           }=r|=-                    d           nd }>|>r|>dz   z   t                      }?t          t                    |?m          }@d }Ar3	 jh        ji                                      }An# t          $ r d }AY nw xY wd}B|A1t          |Adnd          r t          t          |Adod           |?m          }Bt-          |Ad uot          |Adnd          o|@p|B          }Ct-          |2o |2dp                             dq          drk    o|@          }D|CrBt          |Adsd           pdt}E|Edtk    rdun	|Edvk    rdwndx}F};rdy}Gndz}Gd{|F d||G d}rd ndz   n	|Dr};d~z   t          dd           }=|=r&r$|=v r |=-                    d           }H|Hr|Hdz   z   t]          tF                    rR                                s>|A<t          |Adnd          r+t          |Adsd           pdt}I|Idtk    rdun	|Idvk    rdwndx}Jd{|J dpdn |8n          }K |6n|:           	 j                              }L|Lr	 ddlkml}M  |M|L          \  }N}O|Or)t          ]                    dtU          |O          |O           t          d |ND                       r|N}Pn}Pn6# t          $ r'}Qt          ]                    d|Q           }PY d }Q~Qn
d }Q~Qww xY w}Pt          |P|3          }R|2d}S|;|;|Sd<   n|3r|Sd<   |Sd<   |<|<|Sd<    |jo        |Rfi |S}T |9n           	 ddlpmq}U  |Un           n# t          $ r Y nw xY w |7|K           n>#  |9n           	 ddlpmq}U  |Un           n# t          $ r Y nw xY w |7|K           w xY w|Td<   ssr                                 |T                    d          }Vd}Wd}Xd}Yd}Zd         }[|[r`t9          |[d          rPt          |[js        dd          }Wt          |[dd          }Xt          |[dd          }Yt          |[js        dd          pd}Z|[rt          |[d'd           nd }\d         }d}]|rt-          t          |dd                    nd}^|rt          |dN          n}_|rr|_k    rd}]t          +                    d|_           jh        ji                                      }`d}a|`rt          |`dNd           }b {            st          +                    dpd           nm|b|_k    rd}and|bk    r t          +                    dpd|b           n>|_|`_t        jh        u                                 jh        v                    |_           d}a|art          dOd           vj        k    rt          dd           dk    rt          dd           j'        	 j'        j(        w                    |_          }c|crQ|c                    d          r<tG          |cd                   _?        t          
                    dj?        |_           n,# t          $ r t          
                    dd           Y nw xY w|arx                    |`d           |_ty                    t|           |]s|^rdntU          |2          }d|VsMt          |T|VpdtU          |2                    }Vt          j         |V          }V|Vs"|T                    d          rd|Td          nd}Vi d|Vd|T                    dg           d|T                    dd          d|T                    dd          d|T                    dd          d|T                    d          d|T                    dd          d|T                    d          d|T                    d          d|T                    dd          ded         pg d|dd|^dNtd|Wd|Xd|Y|\|ZdS d|Vvrt          |T                    dg           tU          |2          |5          \  }e}f|ervt                      }gg }h|eD ]0}i|i|gvr*|g~                    |i           |h                    |i           1|fr|h                    dd           |Vdz   d                    |h          z   }V|Vrj'        r	 ddlm}j d         rd                             dg           ng }kdtF          dt          dd fd}l|l|rSt          |d'd           t          |d	d           t          |dd           t          |dd           t          |dd           dnd d}m                              r
tfd|md<    |jt          j'        dUj'                  t|V|kfi |m n# t          $ r Y nw xY wi d|Vd|T                    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 ded         pg d|dd|^d|Wd|Xd|Yd'|\d|Zt|T                    dd          |T                    dd          d         rd                             dd          nddS )Nrw  rR   r\  r  r6  r  r4  z3run_agent resolved: model=%s provider=%s session=%srM  u'   ⚠️ Provider authentication failed: r   r  r  r  r  r  r  r  r  r   c                 0    |                      |           d S rr  r  r  s     r"   r  zWGatewayRunner._run_agent_inner.<locals>.run_sync.<locals>._pause_typing_before_finalizeD  s     !) > >x H H H H Hr$   r  Tz(skip streaming for non-editable platformFr  r/  r  r  r  c                  .                          d          S )N)r  )r  )r  s   r"   r   zBGatewayRunner._run_agent_inner.<locals>.run_sync.<locals>.<lambda>D  s    ););N)K)K r$   )r   r   r  rU   on_new_messager  r  r  r   c                 J                 r                     |            d S d S rr  )r  )r   r  r   s    r"   _stream_delta_cbzJGatewayRunner._run_agent_inner.<locals>.run_sync.<locals>._stream_delta_cbD  s;    #5#5#7#7 !D$4$=$=d$C$C$C$C$C!D !Dr$   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 )NrR   r   z+interim_assistant_callback scheduling errorry  )on_segment_breakon_commentaryr7   rT   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_cbD  s    ))++ F##/' E(99;;;;(66|DDDF# ? #lFXVXBYBYB_B_BaBa F(#(('$!8 )  
 #! M	 	 	 	 	 	r$   rN  r  r  r;  )r  r  r;  re  rd  r  r+   rV  rU  zfAgent cache invalidated for session %s: message_count changed (%s -> %s), possible cross-process writerS
  z#Reusing cached agent for session %szagent-xproc-evict-r  r  ry  rw
  r.  ry
  r,  ephemeral_system_promptprefill_messagesr  rM  rJ  r/  r0  r1  r2  r3  r4  r5  r6  r7  r8  r9  r:  r  r   r  r   r  gateway_session_keyr	  rr  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 errorry  )r   r   r   r  r   r  )r   r^  r  r  r  r  r  s     r"   _notice_callback_synczOGatewayRunner._run_agent_inner.<locals>.run_sync.<locals>._notice_callback_syncE  s    & .@.@.B.B F-f55DD    LL!<tLLLLFF  F(11&$??"! K	     s   ! &A
Arz   c           
          r
             sd S t                              | t          j                            t          d           d S )Nr!   r   z+background_review_callback scheduling errorry  )r   r   rZ   r   r   )rz   r  r  r  r  r  r  s    r"   _deliver_bg_review_messagezTGatewayRunner._run_agent_inner.<locals>.run_sync.<locals>._deliver_bg_review_messageE  s    & .@.@.B.B F(#(('!=>U`f`o!p!p!p )  
 #! M	 	 	 	 	 	r$   c                                                        5  t                    }                                  d d d            n# 1 swxY w Y   | D ]} |           d S rr  )r5   rY  r  )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_messagesE  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 rr  )rr  r4   )rz   r  r  r  r  r  r  s    r"   _bg_review_sendzIGatewayRunner._run_agent_inner.<locals>.run_sync.<locals>._bg_review_sendE  s   & .@.@.B.B F)0022 #0 # #188:: #.55g>>>"# # # # # # # ### # # # # # # # # # # # # # # +*733333s   +A++A/2A/r  r
  r
  r   memory_notificationsr   questionc           
      X   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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   r  rR   rS  )rV	  rG  r  r  F)r   r  r  rV	  rG  rU   zClarify send failed to schedulery  r
  r8  r  zClarify send failed: %sz'[clarify prompt could not be delivered]z[user did not respond within r  zm])rS	  r  r  r  r  r  rY  r  r   r   send_clarifyr   r  r   rS   r   r  get_clarify_timeoutwait_for_responser   r   )r  r  r	  r  rV	  send_okr|  r  r[   r  r  r  r  r  r  rG  s              r"   _clarify_callback_synczPGatewayRunner._run_agent_inner.<locals>.run_sync.<locals>._clarify_callback_syncF  s4   AAAAAA$$$$& 2"[[]].ss3
%%) + 1r%-4>DMMM$	 &   #99/JJJJ    D  .#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4D 
D6D11D6rS	  r+  r  zPersisted transcript lagged live cached history for session %s (disk=%d, memory=%d); preserving live conversation context (possible FTS write corruption))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                              |
|          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k    r|dd         dz   n|}d| 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  rR   r2  zdangerous commandsend_exec_approvalN)r   r  rG  r2  rU   z#send_exec_approval scheduling errorry  z$send_exec_approval: loop unavailabler
  r8  zLButton-based approval failed (send returned error), falling back to text: %sz6Button-based approval failed, falling back to text: %sr  r   r  r	  u4   ⚠️ **Dangerous command requires approval:**
```
z
```
Reason: r  zapprove` to execute, `z;approve session` to approve this pattern for the session, `z,approve always` to approve permanently, or `zdeny` to cancel.r   z#Approval text-send scheduling errorz#Failed to send approval request: %s)r  r3   r   rS   rl   r   r  r   r  r  r  r   r5  r   r   r   )r  r   desc_approval_fut_approval_resultr  r  cmd_previewr  _approval_send_fut_approval_session_keyr  r  r  r  s             r"   _approval_notify_synczOGatewayRunner._run_agent_inner.<locals>.run_sync.<locals>._approval_notify_syncF  s     55oFFF#''	266$((8KLL /s33
 4002FMMY(@+>>(7(+,A,0)@ ?   +#)(M) ) ) )0"./U"V"VV+8+?+?+?+K+K(+3 #"Fj,2    %   TVX        _.DcJJ36s88c>>c$3$i%//sn'n n#n n !n n 9;n n *,	n n Z\	n n n 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   1AC2  C2 2
D!<DD!-AF7 7
G'G""G'r0  )r	  rd  rh  rW  r  r:  re  rK  za gateway restartrL  za gateway shutdownza gateway interruptionzTAddress the user's NEW message below FIRST and focus on what the user is asking now.zfReport to the user that the session was restored successfully and ask what they would like to do next.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. u^    Do NOT re-execute old tool calls — skip any unfinished work from the conversation history.]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  uF  ; the gateway is now back online. Any restart/shutdown command in the history has already run — do NOT re-execute or verify it. Report to the user that the session was restored successfully and ask what they would like to do next. Do NOT re-execute old tool calls — skip any unfinished work from the conversation history.])build_native_content_partsz:Native image attachment: skipped %d unreadable path(s): %sc              3   H   K   | ]}|                     d           dk    V  dS )rl   rB  NrV  rt  s     r"   ru  zCGatewayRunner._run_agent_inner.<locals>.run_sync.<locals>.<genexpr>G  s1      LLquuV}};LLLLLLr$   z8Native image attachment failed, falling back to text: %s)conversation_historyr?	  r
  r
  r
  r  rK	  r
  r
  session_prompt_tokenssession_completion_tokensr
  r
  u/   Session split detected: %s → %s (compression)uS   Skipping session split sync for stale run %s — generation %s is no longer currentr  znSkipping session split sync for %s because the session binding moved from %s to %s before compression finishedr  r  uG   Restored source.thread_id=%s from binding after session split %s → %sz<Failed to restore thread_id from binding after session splitr~   zagent-run-compressionr  r  r5  u   ⚠️ r~  r  r  r  r  r  interrupt_messager
  r  compacted_in_placeinput_tokensoutput_tokensri  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   r  )r|   r[   s     r"   _title_failure_cbzKGatewayRunner._run_agent_inner.<locals>.run_sync.<locals>._title_failure_cbH  s*    ^ #    r$   rO  rP  r  )rN  rM  rO  rP  r  )failure_callbackmain_runtimec                 2                         |           S rr  )r  )r  effective_session_idr  r  s    r"   r   zBGatewayRunner._run_agent_inner.<locals>.run_sync.<locals>.<lambda>H  s#    RVR|R|"0!S S r$   title_callbackr
  r  response_transformedr
  )r  r  r8  r
  rH  r   )r   rx  rQ   rT   r  r   rS   r  rE  r   r  r3   r   rC  r  r:  r;  r<  r  r  r'  r
  r   r  r  r  r0  r  r   r  r  r  r   r  r  r7   rN  r  r  rp  rr  rW  r   r  rd  r  r   rK  r7  rS
  r  r  ry  rS  r  r  r  r6  r  r;  r  r  r  r  rE  r  tool_progress_callbacktool_start_callbackr  step_callbackstream_delta_callbackinterim_assistant_callbackstatus_callbacknotice_callbacknotice_clear_callbackevent_callbackr  rM  rJ  rK  rT  background_review_callbackrl   r  r8   r  clarify_callbackrX  rS	  rU  r*  r~  rZ  r   r  r  r  r  r  r  rB   r  r  rj  rG  rO  r
  r!  r'  r  rf  r=  tools.clarify_gatewayr  r  r
  r  r  r
  %get_telegram_topic_binding_by_sessionr&  r]  r  r   r  r5   r9   r4   r<   rA   agent.title_generatorr0  BaseExceptionr  )r   combined_ephemeralevent_channel_promptcfg_channel_promptry  rN  r?  r[   r?  r  r  r!  r  r"  r#  _want_stream_deltas_want_interim_messages_want_interim_consumerr  r  r  r  r$  r%  r&  r'  r(  r)  r  r@  _sigr  reused_cached_agentrF  rz  _current_msg_countr  _xproc_evicted_agentr  
_cached_mc_cached_sid_session_id_mismatchr  	_ev_agentr  r  r  _pdc
_mem_notifr  rL  rM  	_selected_history_media_pathsr  r  r  r  r&  _persist_user_message_override _persist_user_timestamp_override_pending_notes_msn_freshness_window_interruption_is_fresh_resume_entry_resume_mark_is_fresh_is_resume_pending_has_fresh_tool_tail_reason_reason_phrase_resume_guidance_srn
_sn_reason_sn_reason_phrase_approval_session_token_native_imgsr'  rA  _skipped_run_message_img_exc_api_run_message_conversation_kwargsr  _clear_clarify_sessionrK	  _last_prompt_toks_input_toks_output_toks_context_lengthrv  _resolved_model_session_was_split_compacted_in_placeagent_session_idr  _session_split_entry_persistedentry_session_id_binding_effective_history_offsetr  r  rF   unique_tagstagr0  all_msgsr2  maybe_auto_title_kwargsr%  r  r  r  r  r   r6  ru
  r  r  r  r3  r  r  r  r  r  r  r  r  r^  r  r   r
  r,  ry
  r   r-  "interim_assistant_messages_enabledlog_mode_enabledrz   r
  needs_progress_queuer
  r
  r  r  r   result_holderrY
  r  r  rG  r  stream_consumer_holdertools_holderr   r`  s                                                                                                                 @@@@@@@r"   rA  z0GatewayRunner._run_agent_inner.<locals>.run_syncD  s@"   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"!%!8!8!:!: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#}00AAH <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 "&+
+ $ 0 4 @ @ L LI  O-6]]?A-N-N*    D $(  C7v1  B7 B7#ZZ44F @7&)t"3"3 36f++//VAYYt
36v;;??fQii (t3 : *$ 6: +z 9 - !5-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/EB7 B7 B7 B7 B7 B7 B7 B7 B7 B7 B7 B7 B7 B7 B7P $/$#?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 #NN12 %..34 %..56 %..78 )49:  't'7@PQQQ;< $(#7#7= @  
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[\\\ ';Y>NY!!UY ( '7q&9&E""4 % :D9P"Z"5"5VZE*:E'H^/h/D/DdhE,$9E!         " %:E!*.E'#7E %5E"!%!3E&0nn5H&I&I&ORE#!*!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&<  < # <  <  <  <  <  <  <  <  <  < | &<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	   %.M
 )E](S(S            VLT VLd VL VL VL VL VL VL VL VL VL VLv =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\ "333 (' "444 .-1  29.
  	: %$P %
<%< < @P< < < ,3:'g'''<  & 18.[ 	  %T+I4PPN 6+ 6+2O2O%))+t<< 6"Vmg5G 7C(( "-M+;UCC . M?DAAVEV 
 "%666 (' "%777 .-1 "!(! ! !  %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 \!_2 %&? )*= !"6 )*;  #K!" $\#$ -&5'   T ~--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  '$"2 '&FFFFFFGTUVGW_}Q/33JCCC]_H - D     -> #)-%,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
 %$ 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 a.B !"; %&9 %&7     !" !/#$ 3&,jj1Eu&M&M(.

3I5(Q(Q
 VccdUe$oM!$4$8$89JD$Q$Q$Qko3   s|  AD 
D7#	D2,D72D7*D4L 
M)M		M7Q	 	
QQ#C9W	U32W	3
V =W	?V  =W		WWAX   
Y+Y Y
YYYYY!___(m mm.x Au% $x %
v/vx vAx 'w9 9
xxy"x43y4
y>y yyB
A3AC> C>&AD'D&AD'M=C AQ Q
AQ+Q*AQ+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   NrC  )r;  r0  r:  r  )rE  r  s    r"   _start_stream_consumerz>GatewayRunner._run_agent_inner.<locals>._start_stream_consumerH  s      3ZZ * *)!,80377999999999FFmD))))))))))	* *r$   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   rC  uL   Skipping stale agent promotion for %s — generation %s is no longer currentrR   r  )r:  r  r
  r   r  rX  r  r  )r  rY
  r  rG  s   r"   track_agentz3GatewayRunner._run_agent_inner.<locals>.track_agentH  s      q/)mD))))))))) q/) 
 )$2N2N^3 3) b%2"  
 0<QD -~ 8++J777778 8r$   c                    K   sd S 	 t          j        d           d {V  	 j                            j                  } | s>t          | d          r.|                               rd         }|r| j                                      }d }||j        pd}t          |dd           pg }t          |dd           pg }g }t          |          D ]w\  }}|t          |          k     r||         nd}	|	                    d          p(t          |d	d           t          j        t          j        fv }
|
r|                    |           x|r	                     ||           d {V \  }}|}|r                                rqj        r	d
j        ind }|D ]\}	 |                     j        d| d|           d {V  +# t,          $ r%}t.                              d|           Y d }~Ud }~ww xY wnE# t,          $ r%}t.                              d|           Y d }~nd }~ww xY w|s|rt5          |          }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   rR   r  r  r  r  r  r
  rX  r   z+Voice-interrupt echo failed (non-fatal): %sz(Voice-interrupt transcription failed: %sz3Interrupt detected from adapter, signaling agent...z,monitor_for_interrupt error (will retry): %s)r:  r  r0  r3   r   r   r  rZ  r   rS   r  r   rr  r  r  r  r4   r
  r
  r  r   r   r   r   r  r   r  r  r5   r  )r  r  _peek_eventpending_text_media_urls_media_types_audio_paths_i_path_mtype	_is_audio	_enriched_transcriptsr7
  r8
  r9
  
_trans_exc_mon_err_interrupt_detectedr  r  rG  r  s                     r"   monitor_for_interruptz=GatewayRunner._run_agent_inner.<locals>.monitor_for_interruptI  s      M[mC(((((((((K[  $}00AAH# ! 
 x)@AA ="hFdFdepFqFq =" ,Q  ;" +3*D*H*H*U*UK+/L*6/:/?/E2 /6k<QU.V.V.\Z\/6{MSW/X/X/^\^/11:;1G1G !C !CIBACc,FWFWAWAW\"-=-=]_F(.(9(9((C(C )@+2;PT+U+UZeZkmxm~Y+ %. (1 %C(4(;(;E(B(B(B#/ !Y%*HLHoHo,8,I* I* C* C* C* C* C* C*(?	< 8A+7 )6D<]<]<_<_ )6\b\l9v+vGW9X9XrvJ7C -6 -6
16:B--8>8JC8J8J8JAK ;H ;6 ;6 56 56 56 56 56 56 56 56
 8A 16 16 164:LL8e8A56 56 56 56 56 56 56 5616
 ,5 %* %* %*(.,VXb)* )* )* )* )* )* )* )*%* *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[YM[st   !J DJ AG;  'GG; 
G7G2-G; 2G77G; :J ;
H*H% J %H**AJ KJ??Kr[     long_running_notifications)r   rF  c                    K   d S j                             j                  } | 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  rR   rw  r  r{  rx  r   ry  rz  r  r  r}  rJ  r  u   ⏳ Working — z minzHeartbeat edit failed: %sr  Fr!   r   r  z#Long-running notification error: %s)r0  r3   r   r:  r  	NameErrorr  r   r  r   r   r  r4   r7   rA   r   r  r   r   r  rS   r   rZ   r  )_notify_adapter_heartbeat_msg_id	_exec_ref_elapsed_mins
_agent_ref_status_detail_want_iteration_detail_arA  r	  _heartbeat_text_notify_res_ee_ne_NOTIFY_INTERVALr  r  _executor_taskrU  _long_running_mode_notify_startr  r  r   r   r  rG  r  r   s                 r"   _notify_long_runningz<GatewayRunner._run_agent_inner.<locals>._notify_long_runningiI  s     '"m//@@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sh   	A AAB'F 
FF-J! 2"G J! 
HH<J! H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)rS   r   r   r   )consumerr  r  r  s       r"    _stream_confirmed_final_deliveryzHGatewayRunner._run_agent_inner.<locals>._stream_confirmed_final_deliveryI  s     ux!6>> t %%,X7KT%R%R".// %%#$6$6z$B$BCCC$ % % %$uu%5s   A 
A! A!rW  r  rY  i  r   r8  r  zABackup interrupt detected for session %s (monitor task state: %s)rw  r  r/  r  r  r  r+   u   ⚠️ No activity for zB min. If the agent does not respond soon, it will be timed out in z- min. You can continue waiting or use /reset.r   z!Inactivity warning send error: %sr  r  rz  rx  ry  zaAgent idle for %.0fs (timeout %.0fs) in session %s | last_activity=%s | iteration=%s/%s | tool=%sr  r  u   ⏱️ Agent inactive for u(    min — no tool calls or API responses.z!The agent appears stuck on tool `z` (r  z!s since last activity, iteration r   z).zLast activity: r|  zs ago, iteration z6). The agent may have been waiting on an API response.zTo increase the limit, set agent.gateway_timeout in config.yaml (value in seconds, 0 = no limit) and restart the gateway.
Try again, or use /reset to start fresh.r   r~  )rK	  r~  r  rS	  r  r  r  rN  )_AGGREGATOR_PROVIDERSnormalize_model_for_providerrM  rR   r  r,  z5Ignoring control interrupt message for session %s: %sr  r  r  r  r  r
  rX  z'Voice-drain echo failed (non-fatal): %sz$Voice-drain transcription failed: %sz9Processing queued message after agent completion: '%s...'rl  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...'r  u^   Interrupt recursion depth %d reached for session %s — queueing message instead of recursing.queue_message)rK	  r~  r  r  z5Stream consumer wait before queued message failed: %sr  rK	  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
  r   )
rz   r
  r-  r  r  rG  rY
  r3  r   r   r
  final_content_deliveredr8  zSuppressing normal final send for session %s: final delivery already confirmed (streamed=%s previewed=%s content_delivered=%s).r
  )r   r  r   r  zPEdited streamed message %s for session %s to include plugin-transformed content.z2Failed to edit streamed message for session %s: %sr  c                  |    dfd} 	 t           |             t          d           d S # t          $ r Y d S w xY w)Nr   c                  p   K   D ]/} 	                      |            d {V   # t          $ r Y ,w xY wd S rr  )delete_messager   )_mid_adapter_snapshot_chat_id_snapshot_ids_snapshots    r"   _delete_allzRGatewayRunner._run_agent_inner.<locals>._cleanup_temp_bubbles.<locals>._delete_allfL  s       - ! !!"3"B"B 14# #          ) ! ! ! D!! !s   &
33z$Temp bubble cleanup scheduling errorry  rH  )r   r   r   )r  r  r  r  _loop_snapshots    r"   _cleanup_temp_bubblesz=GatewayRunner._run_agent_inner.<locals>._cleanup_temp_bubbleseL  s    ! ! ! ! ! ! ! !,#~%$J     
 !   DDs    - 
;;z-Post-delivery cleanup registration failed: %sNNNrH  )r  r2  r
  ru
  r  r   r~  ry  r   rE  r+  r7  r3   r   rB   r   r   rt  r;  r   r   r=  r1   r  gateway.status_phrasesrD  rE  r7   r5   r   r  r  r  Queuer
  r$
  r0  rS   r   rE  r   rY  r:  r  rl   r  r  r   r  r  rZ   FEISHUrx  rY  rI  rK  r  r  ensure_futurer  r  r  rr  r  rZ  r   r   r  rw  r  r  r   r  r5  _INTERRUPT_REASON_TIMEOUTr4   rA   r  hermes_cli.model_normalizer  r  rN  r  r  rJ  r  rP  r  r   rr  r  r  r  r
  r
  r   r  rT   rM  r8   r   r  r  r  r  r  _MAX_INTERRUPT_DEPTHr  r  rm  r  r?  r  rR  r  r
  r   r  isawaitabler
  r  r  r  r  rP
  r  r  r
  r
  r  r  r   r  r  )r  rz   r
  r-  r  r  rG  rY
  r3  r   r   r
  r
  r
  r+  agent_cfg_localdisplay_configr;  _tplr=  _ftl_resolved_tp_env_tp_display_cfg_platforms_cfg_platform_cfg_legacy_tp_overrides_tool_progress_configuredrE  rK  interim_assistant_messages_mode_thinking_mode_va_vtc_gid_tc_cleanup_adapter_progress_thread_idr  r  rA  progress_tasklog_taskr*  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_INTERVALr  rw  rE  _backup_adapter_backup_agent	_bp_event_bp_textr  
_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_linesrv  _result_for_fb_run_failed
_cfg_modelr  r  _agent_providerr  r   r  r  r,  r  r  r  r  r  r  r  r  r  r  r7
  r8
  r9
  r  _leftover_steer_pending_parts_pending_cmd_word_rc_pending_has_stream_consumerr|   was_interrupted_scr  
_previewedfirst_response_already_streamed_bg_cb
_bg_resultupdated_historynext_sourcenext_messagenext_message_idnext_channel_promptnext_session_key_followup_adapterr  _final_is_empty_sentinel_content_delivered_transformed	_streamed
_sc_msg_id	_edit_errr  _rperu
  r  r  r  r  r  r  r  r  r  rS  rU  rT  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r]  r^  r_  r  rD  r,  ry
  r  r  r  r  r  r  r  r  r   r  r  r  r  r  r  r   r  r  r  r  r   r`  s   ``````````````                                                                                                                              @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@r"   r5  zGatewayRunner._run_agent_innerL@  sP6     :    
	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 )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
 
 BS\4=,,V_===X\'!""15H5WWW !&#&( !&w!%T	$ T	$# T	$# T	$s T	$ae T	$ T	$ T	$ T	$ T	$ T	$ T	$ T	$ T	$ T	$ T	$ T	$ T	$ T	$ T	$ T	$ T	$ T	$ T	$ T	$@ :OV-/?
 
 !	+"f&666 ,,V5EFFF233&*	 	
 ::LW]Wfggg 8?H4G"HHHVM]HbrH  	5	 5	 5	 5	 5	 5	nI	+ I	+ I	+ I	+ I	+ I	+ I	+ I	+ I	+ I	+ I	+ I	+ I	+ I	+ I	+ I	+ I	+X
 vv"& !133Z
	3 	D 	T 	 	 	 	 	 	 	 	 	 	8	BS 	B4 	BD 	B 	B 	B 	B 	B 	B 	B -++FO<< .?ho--&2B-GW- 1'7A A##
 ex  'Bd&F&FvO_&`&`&`  ~B#!	9c !	9C !	9D !	9 !	9 !	9 !	9 !	9 !	9 !	9 !	9 !	9 !	9 !	9 !	9 !	9Ff	 f	 f	 f	 f	 f	 f	 f	 f	 f	 f	 f	 f	 f	 f	 f	 f	 f	 f	 f	 f	 f	 f	 f	 f	 f	 f	 f	 f	 f	 f	 f	 f	 f	 f	 f	 f	 f	 f	 f	 f	 f	 f	 f	 f	\%  	J#/0F0F0H0HIIM  	=*>>+;+;<<H 	* 	* 	* 	* 	* )*@*@*B*BCC	8 	8 	8 	8 	8 	8 	8 	8.  +KKMM:: &mooQ	[ Q	[ Q	[ Q	[ Q	[ Q	[ Q	[ Q	[ Q	[f $/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 $		 	 		 		
 	 	 	 	(o	 ",,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*.-*;*;FO*L*L(4Q+ 6 6$+O=T$U$U6$3$I$I+$V$V6 )8(I(M(Mk(Z(ZI9B'Ly~~H"KK!; +*;*@*@*B*B Q		   *33H===/3355516 .  66$+L'(.% % %      GD!  #1#8#8#:#:!-aJ!$J! !gj:P&Q&Q !!#-#B#B#D#DD)-2JC)P)PJJ( ! ! ! D! + ]~/I *n < <)-(,(9(9&/(J(J( ],/"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*.-*;*;FO*L*L(4Q+ 6 6$+O=T$U$U6$3$I$I+$V$V6 )8(I(M(Mk(Z(ZI9B'Ly~~H"KK!; +*;*@*@*B*B Q		   *33H===/33555m66p # =#/? 	# 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m''88G !MG Ap' Apk Ap 6w L L !% : :;Q^ _ _::m,, 8p] 8pvzzReGfGf 8p(.

3F(G(G%45FGG 4S'.3-    #4" .p %2$6$<"M")-t"L"L"RPRK#*=-#N#N#TRTL#%L%.{%;%; 7 7	E57#l:K:K5K5Kb!1!1QS"--h77 v&}ndKKP[PacnctOuu " % 7(//666# [_<@<c<c -|= = 7 7 7 7 7 73I| '0&74G+ *0Q0Q0S0S *PVP`-jk6;K-L-Lfj
+7 
!* 
!*C	%*.5ll,2N,>,>,>,>5? /; /* /* )* )* )* )* )* )* )* )*
 ,5 %* %* %*(.,UW`)* )* )* )* )* )* )* )*%*  ) _ _ _"NN F
   '4&^7OP]7^7^GGGGGG	_ #0"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--//  
 !% nY nYBGCRCLQQQ
  Bww0BCC B BXcgngXX,[9??AAA $t'@@@NNA(+  
 #m//@@G D= D3G4M{\ijjjj  DWWo%F%F D--k7CCC(+`(X_/`/``v  '$$&&& "!!!$$&&&!!!  ! + >.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   W #)**]";";& A% 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!%fjj1E&F&F!G!GJ%+ZZ0@"%E%EN(H(H&",) ) )%
 & .? 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%) %      *.)K)K+* /$4	 *L * * $ $ $ $ $ $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'
 %)M$5$5fo$F$F!$ /;;"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   GnYb  '$$&&& "!!!$$&&&!!!  ! + >.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 s_  >0E/ /
E<;E< ,F- -
F:9F:+GA| *h6 5A| 6
i A| iAA| *k
 	A| 

k9k4/A| 4k99DA| p" !A| "
p/,A| .p//GA| ;-x) (A| )
x63A| 5x66G
A| @AAB, A'AA9A8AB, A9
AB(BAB#BAB, B#AB(B(AB, B+A| B,
AC,B6,AC'C"A| C'AC,C,C4A| G!0AH HA| H
AHHA| HAHHD<A| OAOOAO0O/AO0O4APP/AQ"QAQ
Q	AQ"Q
AQQAQ"QAQQAQ"Q!AQ"R:ASSASSASS$A| S?AT TA| T/AVUAUUAVUAU'U$AVU&AU'U'AVU*A| U,	AVU5AVVA| VAVVAA| W(A AX) X(A| X)
AYX3AYYA| YAYYA&A| Z?&A[& [%A| [&
A[3[0A| [2A[3[3A A| \4&A] ]A| ]
A](]%A| ]'A](](BA| a$Aa-a-Aa?a>Aa?bAb b /Ac1cAccAc1cAc+c(Ac1c*Ac+c+Ac1c0Ac1e	AeeAe$e#Ae$e*Af  e?A| f )Af,f)A| f+Af,f,&A| iAiiAi&i%Ai&i*Ajj/Akj7Ak j?Akk AkkAkkAkkAkkAkl0Al9l9Amm
AmmAA| n"An; n:A| n;
AooA| oAooAA| rAr!r!Ar3r2Ar3r7Ass/At%tAttAt%tAttAt%tAttAt%t$At%u=AvvAvvAvxAx  x Ax2x1Ax2x6Ay y/Az$zAzzAz$zAzzAz$zAzzAz$z#Az${<A||A||A||A9BB~A~ ~BB~ A~2~/BB~1A~2~2BB~6ABB/B@$@B@@B@$@B@	@B@$@B@	@B@$@!BB@#B@$@$ABBA<BBBBBBBB	BBBBBB	BBBF#ABG6 G6
BH(H BH#H#BH(J"BJ; J;
BK*KBK%K%BK*rr  rH  )r   rT  )r  )r  )r  )r  r  r  r  )r  r  r  )NNr   NNNNN(-  rm   r  r  r  r  r	   r7   r   __annotations__r  r  r  r  r  r
   r   r  r   r  r  r  r   r  r  r  r  r  r:  Taskr  r  r  r   r  r  r  r  r2  r  r  r  r  r  ry  r  r  r  r  r  r  r  r  r  propertyr  r  r  r  r  r
  	frozensetr  r  r  r  r  r  r  r  r#  r&  r/  r3  rB   rK  rE  rN  r]  r  ro  rr  rt  r|  r  r  r  r  r  r  r  r  r  r  r  r  r  r  staticmethodr  r  r  r  r  r  r  r  rl  r  r  r   r5  r7  r  r  r9  r  r  r  r;  r=  r?  r@  rA  r0  rB  rY  rD  r8  r<  r?  rD  rK  rQ  rX  r  rY  r  r  r  r  r  r  r  r  r  r   r  r5   r  r  r  r&  r=  rJ  rf  rT  rV  r[  ra  rp  rs  rw  r  r  r  r  rf  r  rm  r  r  r  r  r  r  r   r  r  r  r	  rP
  r
  rW
  r  r	  r
  r[	  ry  r  r|	  r}	  r  r  r  r  r	  r
  r  r  r  r  r  r
  r
  r
  r
  rN  rZ  rb  re  ri  ru  rp  r  r  r  r  r  r  r  r  r   ro	  r  r  r  r  r  r  _APPROVAL_TIMEOUT_SECONDSr  r
  WHATSAPPr  r  EMAILSMSDINGTALKr  WECOMWECOM_CALLBACKr  r  r  rx  _UPDATE_ALLOWED_PLATFORMSr  r  r  r  r  r  r
  r
  r  r  r  r  r  rr  r
  r
  r
  rD  rJ  r
  rO  r  r  r  rm  rr  ro  classmethodrt  r  r  r  r9  r:  r  rR  r  r	  rY	  r
  r
  r]	  r
  r  r  r  r  r  r  r9  r  r2  r
  r6  r5  r   r$   r"   r  r  
  s+          ,.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0:<d3S#X#67<<<>@ $sDcN':";@@@). $...v8 v8x6 v8 v8 v8 v8r	   >-
 -
 -
 -
f$     $&??-8 -c -c - - - -4S>    4@ @ @ @,s ,d ,W[ , , , ,+c +D +UY + + + +$* * * *X   > >B4 4 4-5c]4	4 4 4 4l8% 8 8 8 86 6 6 6 6  :?  26	   . "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 + + + +Z.Y .YS .YT .Y .Y .Y .Y`^9L ^QU ^ ^ ^ ^@## #$ # # # #
)c ) ) ) )    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 * * * *@ )-$('+   !	
 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 D4K    \$ F Fc4i8H F F F \F8 +/%)	- - - '- c]	-
 
- - - -&TT #4.T 
	T T T T d
    \$ 
$ 
 
 
 \
 
3 
 
 
 \
 A# A A A \A.     \$     \6 D    \ $+    \(
$sCx. 
 
 
 
hsm    
 
# 
 
 
 
  
sHSM!	"	   : #3 #4 # # # \#Jc d    H !%83 %8| %8X\ %8 %8 %8 %8N~| ~Z] ~bf ~ ~ ~ ~@#% #E$sCx.RVBV<W # # # #<Q Q Q Q Q QE E E EN2T#s(^ 2PT 2 2 2 2hc]   }	
 
   <  -/& & &&&)&	& & & &P'c 'd ' ' ' 'R 0S T    6/c / / / /b     *J J J JX]S ]S ]S ]S~ 38U   4 d W[    J %9FFF ?$? ? 	?
 
? ? ? ?:, 4     C    4` ` ` `"I I# I I I IV
t 
 
 
 
 26'+ -. 8$ 
	   4u
T u
 u
 u
 u
n0* 0*u 0*t 0* 0* 0* 0*dq>$sCx. q>T q> q> q> q>f{' {'c {' {' {' {'zc    |' |' |' |'B !& %[ [ [ [ 	[
 [ 
[ [ [ [z* * * *< < < < <|SS/5S@DUCZ@PS	S S S Sj	# 	 	 	 	 X X# X X X \X&vv v 
%	&	v v v vp 
3x}5t;	<   JGc Gd G G G G>r:< r:HSM r: r: r: r:h-> c d    6 &*l l l l 	l
 d38n%l c]l 
#l l l l\	?s ?tCy ? ? ? ?     *c    k9# k9_b k9 k9 k9 k9Z-u c u  u  u  u t(D#(D47(D	#(D (D (D (D`%} %s %t % % % %TB8, B84 B8 B8 B8 B8X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wIwI wI
 
wI wI wI wI@ +/*.+/H HH  H 	H
 #3-H T#Y'H d3i(H 
H H H H`
] 
t 
 
 
 
8'U- 'UD 'U 'U 'U 'URU] Ut U U U U$	C 	C 	 	 	 	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.	!	
 
 
 
( $(-1!%  8$ # C=	 C= &c] # 
$sCx.	!   @  $(!%  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    &* * * *, +/%)&*"&#: : : ': c]	:
 d^: 3-: }: 
: : : :x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@ @
 
t@ @ @ @DE
t E
 E
 E
 E
N%F3 %FT %Fd %F %F %F %FN3D 3T 3 3 3 3*-* -* -* -* -* -* -*^~>$ ~>4 ~> ~> ~> ~>@ 	) 	 	 	" PRU3d
?%;T#s(^%K LQQQE4S> E E E [E <T#s(^ < < < [<: $t $ $ $ $ [$L  #'""&A> A>A>A> A> 	A>
 4KA> tA> 4ZA> 
A> A> A> \A>F8
S 8
T 8
 8
 8
 8
t%%'*%<@%	% % % %:M M# MRV M M M M )-	2 2 22 !	2
 
2 2 2 2h-# -$ - - - -^     $ UW 
 
 
c 
c 
[^ 
 
 
 
G3 GC GD G G G G  $J	
 
   . '+; ; ;; ;
 ; !;  $; 
; ; ; ;2II,4SMI	I I I IV=s =t = = = =~ "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, , , ,\%} % % % % %,  (, !*.(,%).226t0 t0t0 t0 d38n%	t0
 t0 t0 t0 !t0 t0 #3-t0 !t0 TNt0 'smt0 !)t0 
c3ht0 t0 t0 t0 t0 t0r$   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  FrI  Nz#Planned-stop watcher tick error: %s)r  r4  r5  rr  r:   rS   r  call_soon_threadsafer   r   r  )	r2  runnerrv   shutdown_handlerr  r4  r5  r}  r  s	            r"   _run_planned_stop_watcherr9  L  s^   Z        0/11K!! $'"	D""$$U;; FJ66, 8799 OOM222
 ))*:DAAA 	D 	D 	DLL>CCCCCCCC	D&&&I !! $' $' $' $' $'s   AB >B 
C!CCr  r  c                 <   ddl m}m} 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)r+   r  Nz*Channel directory refresh scheduling errorry  rv  r8  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   r  )r  s    r"   r   z-_start_gateway_housekeeping.<locals>.<lambda>,M  s    6;;}c+J+J r$   )idle_for_seconds
on_summaryzCurator tick error: %szGateway housekeeping stopped)r  r;  r<  hermes_cli.debugr=  r   r  rr  r  r  r   r  r   r  agent.curatorr?  r   r  )r2  r0  rv   r  r;  r<  r=  IMAGE_CACHE_EVERYCHANNEL_DIR_EVERYPASTE_SWEEP_EVERYCURATOR_EVERY
tick_countr  r|  r  r  deleted	remainingr?  s                      r"   _start_gateway_housekeepingrL  L  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)r0  rv   r  N)cron.scheduler_providerrN  r  )r2  r0  rv   r  rN  s        r"   _start_cron_tickerrP  5M  sC     ?>>>>>"":tV^"_____r$   g     @P@g     A@r  r  pollc                   K   | dS t          j                                                    t          d|          z   }|                                 rt          j                                                    |k     rWt          j        |           d{V  |                                 r)t          j                                                    |k     W|                                  S )u  Wait for a daemon thread to exit WITHOUT blocking the event loop.

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

    Polling ``is_alive()`` with ``await asyncio.sleep`` keeps the loop running
    so the pending delivery completes, then the ticker sees ``stop_event`` and
    exits. Returns True if the thread exited within ``timeout``.
    NTr/  )r:  r  r  r  is_aliver  )r  r  rQ  r  s       r"   _await_thread_exitrT  WM  s       ~t'))..003sG3D3DDH
//

 " 8 : : ? ? A AH L LmD!!!!!!!!! //

 " 8 : : ? ? A AH L L    r$   r   	verbosityc                   45K   ddl m}  |             ddlm}m}m}m}m}m}	  |            }
|
|
t          j
                    k    r|r ||
          }t                              d|
           	 ddlm}  ||
           n2# t          $ r%}t                              d|           Y d}~nd}~w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} nt/          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t/          j        d           &|s?t                              d|
           	 ddlm}  |             n# t          $ r Y nw xY wdS  |             	 t5                      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;          t5                                }t                              d|
|           t=          d|
 d           dS 	 ddlm }  |d           n# t          $ r Y nw xY wddl!m"}m#}  |tH          d           	 dd l%m&} d}	 dd!l'm(}  |            }n# t          $ r d}Y nw xY w |tH          |"           n2# t          $ r%}t                              d#|           Y d}~nd}~ww xY w|dd$l)m*} tV          j,        tV          j-        d%.                    |tV          j/                  }tW          j0         |                      }|1                    |           |2                     |d&                     tW          j3                    4                    |           |tW          j3                    j5        k     r&tW          j3                    1                    |           tm          |           5d4dE45fd'	}5fd(} to          j8                    }!|!9                    tt                     tw          j<                    tw          j=                    u rt|          j?        t|          j@        fD ]*}"	 |!A                    |"||"           # t          $ r Y 'w xY wt          t|          d)          r2	 |!A                    t|          jD        |            n+# t          $ r Y nw xY wnt                              d*           tw          jE                    }#tw          jF        t          |#5|!|fdd+,          }$|$H                                 ddlI}%dd-lmJ}&m}m}  |            }'|'4|'t          j
                    k    rt                              d.|'           dS  |            st                              d/           dS 	  |&             n5# t          $ r(  |             t                              d0           Y dS w xY w|%L                    |           |%L                    |           	 dd1lMmN}(  |(             n2# t          $ r%})t                              d2|)           Y d})~)nd})~)ww xY wt                       	 dd3lPmQ}* to          j8                    }+|+R                    d|*           d{V  n2# t          $ r%}t                              d4|           Y d}~nd}~ww xY w5H                                 d{V },|,sdS 5jS        rD5jT        r t                              d55jT                   5jU        t          5jU                  dS 5jW        s5X                                 d{V  5jY        r)5jT        r t                              d65jT                   dS 	 dd7lPmZ}-  |-             n# t          $ r Y nw xY w5jU        t          5jU                  dS dd8l[m\}. tw          jE                    }/ |.            }0tw          jF        |0jH        |/f5j]        to          j8                    d9dd:;          }1|1H                                 tw          jF        t          |/f5j]        to          j8                    d9dd<;          }2|2H                                 5X                                 d{V  	 dd=lMm_}3  |3             n# t          $ r Y nw xY w5jY        r)5jT        r t                              d65jT                   dS |/`                                 	 |0a                                 n2# t          $ r%}t                              d>|           Y d}~nd}~ww xY wt          |1t          ?           d{V s t                              d@t                     t          |2t          ?           d{V  |#`                                 |$e                    dA?           	 dd7lPmZ}-  |-             n# t          $ r Y nw xY w5jU        t          5jU                  4r#5jf        st                              dB           dS 5jg        r)t                              dC           t          dD          dS )Fa7  
    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_timerk  rj  terminate_pidNz<Replacing existing gateway instance (PID %d) with --replace.)write_takeover_markerz#Could not write takeover marker: %sFr   z1Permission denied killing PID %d. Cannot replace.)clear_takeover_marker)_pid_existsr  Tr1  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.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  r  z-Startup security audit failed (non-fatal): %sr  )r   r+   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  rh  r   r   r  rm  SIGINTri  r  rj  rk  rl  r  rP  r   r  r:  rI  rm  )received_signalplanned_takeoverrh  r  planned_stopri  rj  rk  rl  _shutdown_ctxr  	_diag_logrP  r7  s               r"   shutdown_signal_handlerz.start_gateway.<locals>.shutdown_signal_handlerDN  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>  )rJ  )r7  s   r"   restart_signal_handlerz-start_gateway.<locals>.restart_signal_handlerN  s"    4@@@@@r$   SIGUSR1z6Skipping signal handlers (not running in main thread).zplanned-stop-watcherr  )write_pid_filerj  rY  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)r  zMCP tool discovery failed: %szGateway exiting cleanly: %sz Gateway exiting with failure: %s)r  )resolve_cron_scheduler)r0  rv   zcron-scheduler)r  r  ru  r  rt   zgateway-housekeeping)stop_nous_auth_keepalivezCron provider stop() error: %sr8  ub   Cron ticker did not exit within %.0fs of shutdown — an in-flight delivery may have been dropped.rV  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   rr  )hgateway.code_skewrW  r  rX  rY  rZ  rk  rj  r[  r1   r  r   r  r\  r   r  ProcessLookupErrorPermissionErrorr6   r5  r]  r^  r;  r  r  r   r  r  r_  r7   printtools.skills_syncrb  hermes_loggingrd  re  r  !hermes_cli.security_audit_startuprf  r  r  r   r  r  WARNINGr  r3   DEBUGStreamHandlerr  r  r  r  levelr  r:  r  set_exception_handlerr   rS  current_threadmain_threadrm  rp  rn  add_signal_handlerNotImplementedErrorr   ry  rK  r  r9  r  atexitrz  FileExistsErrorr  hermes_cli.nous_auth_keepaliver{  rO   r  r  r
  r  r  r  
SystemExitrI  r  r  r  rO  r|  r0  rL  r}  r5   rm  rT  _CRON_SHUTDOWN_DRAIN_TIMEOUT$_HOUSEKEEPING_SHUTDOWN_DRAIN_TIMEOUTrA   r  r  )6r  r   rU  rW  rX  rY  rZ  rk  rj  r[  existing_pidexisting_start_timer\  r  r]  r^  old_gateway_exitedrE  r_  	_releasedr  rb  rd  re  rf  
_audit_cfgr  
_audit_excr  _stderr_level_stderr_handlerrv  rx  rv   sig_planned_stop_watcher_stop_planned_stop_watcher_threadr  rz  _current_pidr{  r[   r  _loopr  r  r|  	cron_stopcron_providercron_threadhousekeeping_threadr}  rP  r7  s6                                                       @@r"   start_gatewayr  nM  s     $ :99999                #?$$LLBIKK$?$? w	"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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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 "']+ ]+ ]+ ]+ ]+ ]+ ]+~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 ?>>>>>!!I**,,M""\"OW5M5O5OPP  K 
 $**\"OW5M5O5OPP#    
"
"
$
$$$$$$$$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 
D$+D$?DD$
DD$DD$#D$ F F/F/.F/H 
H%$H%5%I 
I('I(,I= =
J
	J
0J? ?
KKL/ /
L<;L<N #M4 3N 4N N NN 
O#OOU$$
U10U1
 V+ +
V87V8
Z .[[>\ 
\>\99\>5^ 
^5^00^53b 
bbf 
f%$f%-h 
h1h,,h17k 
kk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)r2  z--configr
  zPath to gateway config file)r	  z	--verboser4  
store_truezVerbose output)r  r	  r  r  r+   )hermes_cli.stdior  r   argparseArgumentParseradd_argument
parse_argsr  r  r  r  r  r  r:  r0  r  r  r	  r   r   _exit_after_graceful_shutdown)r  r  parserr  r  r  r  r  r  r  r  s              r"   r  r  O  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   ri  )drain_log_queuer  r8  N)r-   r6  r7  r  r   r  rj  rk  r  r  r1   _exit)r  r  rj  rk  r  s        r"   r  r  O  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__rH  rr  )r   N)r  r   r   N)r   r   )r   r  )r   r  r   N)NNr  )r  )NFr   (]  r  hermes_bootstrapModuleNotFoundErrorr:  concurrent.futuresr  r2  r  r  r  r1   r   r  r=   r-   rm  r  rS  r  sqlite3collectionsr   contextvarsr   r  r   r   typingr   r	   r
   r   r   r   agent.account_usager   r   agent.async_utilsr   
agent.i18nr   r  r   hermes_cli.fallback_configr   r  r  r  r  r  compiler   
IGNORECASEDOTALLr   r&  r    r   r#   _GATEWAY_PROVIDER_ERROR_REr   r   r   r   rO   r7   r   rZ   rG  ru   r   r   r   r   r   r   r   r   r   r   r   rB   r   r5   r   r   r  r   r   r  r  r  r  rK  r#  r  r"  ra  rb  r#  r*  rU  rZ  rf  rj  r  agent.replay_cleanuprn  _is_interrupted_tool_resultro  rG  rp  rH  rs  rt  ru  rF  r  r  r   r  r  r  r  r  r  r  r  r  r2   r;   r<   r.   r0   r  r  r  utilsr  r  r  r  r  dotenvr  hermes_cli.env_loaderr  	_env_pathr/   r  r  r  r  
contextlibr  _contextmanagerr  r  r  r
  r  r  _config_pathr:   r  r  r  r  r  r  r  r  r  r  r   rE  _key_valr   r3   _terminal_cfgrT   r8   _terminal_backend_terminal_env_map_cfg_key_env_varr_  rF  r  rY  r  _auxiliary_cfg_aux_bridged_keysr  rK  r|  r9   	_task_key	_task_cfg_provr'
  r(
  r  r  _upper
_agent_cfgr  _tz_cfg_security_cfg_redact_gateway_cfg_strict_allow_dirs_allow_dirs_strr@   rA   _trust_recent_trust_recent_seconds_bridge_errr  rl   rm   r7  r  dir_network_cfg_bootstrap_excr  r  gateway.cwd_placeholderr  r  _configured_cwdr  r  _resolved_cwdr  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  gateway.deliveryr  r  gateway.authz_mixinr  gateway.kanban_watchersr  gateway.slash_commandsr  r  r  r  r  r  r  r  gateway.restartr  r  r  r  gateway.whatsapp_identityr  _canonical_whatsapp_identifierr  _expand_whatsapp_auth_aliasesr  _normalize_whatsapp_identifierr  r   r-  r  r  r  r)  r  r  objectr7  r  r  r  r  r  r  r  r
  r  r  r#  rF  rJ  r^	  r_	  r   _INTERRUPT_REASON_SSE_DISCONNECTrq  rp  rN  rP  ra  ru  ry  r  r  r~  r  r  r  r  r  r  r  r  weakrefr3  r  r4  r  r  r  r  r  rK  AbstractEventLoopr9  rL  rP  r  r  r  rT  r  r  r  r   r$   r"   <module>r     s%    "	 	 	 	
 	D	             				 				   



         # # # # # # $ $ $ $ $ $             = = = = = = = = = = = = = = = = P O O O O O O O 6 6 6 6 6 6       % % % % % % 9 9 9 9 9 9  # )- &+. (&6 #)rz*TUU &BJ	  MBI#  4 (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 # #    *c s S U]^aUb    (:# : : : :
C 
C 
C#  X[ `hil`m    	F 	FC 	FRU 	FZ^ 	F 	F 	F 	F" 59$ $ $$$ $
 $ $ $'s8d?$ 
$ $ $ $N< <s <s < < < <L )0 %S Xe_    D, , , , ,$S 5 U    $  #'	) ) )) 
%) %	)
 
) ) ) )r- %S/   c C d38n cSVh    B ,M (!a  %O !_(3- _D _ _ _ _Xd^     . %)#	X+ X+ X+$sCx.!X+ SMX+ 	X+
 4S#X#./X+ X+ X+ X+v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:J J J J8     9 8 8 8 8 8 !*	 + + + ! !     <    / / / /D $$dee (1:'> $ m+ e
d
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@ @
;< 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 9 9 9 9 9 9 > > > > > > < < < < < <                                    
	8	$	$ NVOZ^N6b (3-    J !&(( Ct C C C CL     *HSM    "3t 3 3 3 3lBs Bs B B B BE E E E E EZ Z Z Z Z Z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/4 /E#*cDj:P4Q / / / /d=3 =3: = = = =@C: C# C C C C
F F F F Fd    ;d ; ; ; ;|:d : : : :( 4$; #    &  $#	   } }	
 
#Y   :  $#   
 } } o   :Xd3i0    6C M    4d |    @   >    $0L X\ 0 0 0 	A A AAA 	A
 	A A A AH$ 4    ( 
   @3
 3
 3
 3
lcG cG cG cG cG-/IKd cG cG cGXO 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!	! ! ! !.k k 7 k kbjknbo kx| k k k k\2- 2- 2-j:S :T : : : :z zDFFFFF s   
 	s V9-s 9V==s  V=s W- ,s -W52s 4W55G>s 4.`# "s #`+(s *`++R*s t"=tt"&Av v*	v%%v*.w   w&w!!w&*w< <x"xx"