Ë
    ãß²j\.  ã            	       ó  — d Z ddlZddlZddlZddlZddlmZmZ ddlm	Z
 ddlmZmZ  ej                  d«      Z G d„ d«      Zd	ej"                  d
ededefd„Zdededz  fd„Zdedededz  defd„Zd
edefd„Zddœd
edededefd„Zy)u_  Blocking gateway approval wait for :mod:`tools.approval`.

Mirrors the CLI's synchronous ``input()`` flow: the agent thread enqueues a
pending approval, the gateway notifies the user, and the thread blocks until
``/approve`` / ``/deny`` resolves it or the approval timeout elapses. Multiple
threads (parallel subagents, execute_code RPC handlers) can block concurrently
â€” each gets its own ``threading.Event``; ``/approve`` resolves the oldest,
``/approve all`` every pending entry. Queue state (``_gateway_queues``,
``_lock``) is owned by ``tools.approval`` and reached through that module at
call time.
é    N)Úget_interrupt_reasonÚis_interrupted)Úapproval_context)Úactivity_heartbeatÚhuman_wait_windowztools.approvalc                   ó    — e Zd ZdZdZdefd„Zy)Ú_ApprovalEntryz@One pending dangerous-command approval inside a gateway session.)ÚeventÚdataÚresultÚreasonÚacknowledgedÚsettleÚ	cancelledr   c                 ó  — t        j                  «       | _        t        |«      | _        | j                  j                  dt        j                  «       j                  «       d| _	        d | _
        d | _        d | _        d | _        y )NÚ
request_idF)Ú	threadingÚEventr
   Údictr   Ú
setdefaultÚuuidÚuuid4Úhexr   r   r   r   r   )Úselfr   s     ú@/home/ubuntu/.hermes/hermes-agent/tools/approval_gateway_wait.pyÚ__init__z_ApprovalEntry.__init__   sc   € Ü—_‘_Ó&ˆŒ
Ü˜“JˆŒ	Ø�	‰	×Ñ˜\¬4¯:©:«<×+;Ñ+;Ô<Ø!ˆÔð ˆŒØ"&ˆŒà"&ˆŒð &*ˆ�ó    N)Ú__name__Ú
__module__Ú__qualname__Ú__doc__Ú	__slots__r   r   © r   r   r	   r	      s   „ ÙJØ\€Ið*˜Tô *r   r	   r
   Úsession_keyÚinterrupt_logÚreturnc                ó¬  — t        j                  «       t        t        j                  «       d«      z   }t        d«      }t        |«      5  	 t        «       r t        j                  ||«       	 ddd«       y|t        j                  «       z
  }|dk  r
	 ddd«       y| j                  t        d|«      ¬«      r
	 ddd«       y |«        Œ~# 1 sw Y   yxY w)	uF  Wait on *event* until it fires, the turn is interrupted, or approvals.timeout
    elapses; returns ``"set"`` | ``"interrupted"`` | ``"timeout"``. Polls in ~1s
    slices so activity heartbeats reach the agent's inactivity tracker every ~10s â€”
    otherwise the gateway watchdog kills the agent while the user is still
    responding (mirrors ``_wait_for_process()`` cadence). The loop is recorded as
    human-wait time so the concurrent batch deadline excludes it.

    Any interrupt (/stop, inactivity timeout, delegation teardown) ends the wait
    fail-closed: the command does not run. Who caused it is read from the
    per-thread interrupt-cause channel (``get_interrupt_reason()``, a trusted fixed
    category), never inferred from message text, so the caller can report a
    withdrawn prompt without inventing a user refusal.r   zwaiting for user approvalNÚinterruptedÚtimeoutg      ð?)r)   Úset)ÚtimeÚ	monotonicÚmaxÚ_ctxÚ_get_approval_timeoutr   r   r   ÚloggerÚinfoÚwaitÚmin)r
   r$   r%   ÚdeadlineÚ	heartbeatÚ	remainings         r   Ú_poll_eventr7   -   sÅ   € ô �~‰~Ó¤#¤d×&@Ñ&@Ó&BÀAÓ"FÑF€HÜ"Ð#>Ó?€IÜ	˜;Ó	'ñ Øô ÔÜ—‘˜M¨;Ô7Ø$÷ð ð !¤4§>¡>Ó#3Ñ3ˆIØ˜AŠ~Ø ÷ð ð �z‰z¤# c¨9Ó"5ˆzÔ6Ø÷ð ñ ŒKð ÷ð ús   Á
#C
Á6C
ÂC
ÃC
Ã
CÚstatec                 ól   — | dk(  rt        «       xs dS | dk(  r|j                  €|j                  xs dS y)u}  Why the wait ended with nobody answering: the turn was interrupted (cause from the
    per-thread channel â€” a user /stop or a parent's delegation teardown), the entry was
    withdrawn with a stamped cause (leader interrupted, session torn down), or the turn ended
    under the prompt (notifier unregistered, result never set). ``None`` for a real answer
    or a plain timeout.r(   zturn interruptedr*   Nz-the turn ended before the prompt was answered)r   r   r   )r8   Úentrys     r   Ú_cancel_causer;   L   s>   € ð �ÒÜ#Ó%Ò;Ð);Ð;Ø�‚~˜%Ÿ,™,Ð.Ø�‰ÒQÐ"QÐQØr   ÚpayloadÚresolvedÚchoicec                 ó„   — |j                  d«      rd}n
|sdn|xs d}t        j                  di | ¤d|i¤|¤Ž |||dœ|¥S )zÕFire the post hook and build the decision dict. Unresolved (timeout) and
    a None choice both mean the user never answered; ``cancelled`` carries the
    cause when the prompt was withdrawn rather than answered.r   r)   r>   )r=   r>   r   ©Úpost_approval_response)Úgetr.   Ú_fire_approval_hook)r<   r=   r>   r   ÚextraÚhook_choices         r   Ú_finishrF   Y   sQ   € ð ‡y�y�ÔØ!‰á'/‘i°fÒ6IÀ	ˆÜ×ÑÑ^¸Ñ^ÈÑ^ÐX]Ò^Ø ¨F¸fÑNÈÐNÐNr   c           
      ó  — t        j                  di |¤ddi¤Ž t        |j                  | d¬«      }t	        ||«      }|dk(  rd\  }}n|dk(  rd\  }}n|j
                  }|d	u}|d
k(  ry	|rd|ini }t        |||t        |dd	«      fddi|¤ŽS )ud  Wait on an already-pending identical approval instead of re-prompting.
    Adopts the leader's decision: ``session``/``always`` â†’ approval (same dict
    shape as a direct resolution; persistence stays the caller's and is
    idempotent across leader and followers); ``deny`` â†’ denial carrying the
    leader's reason; leader timeout / our own deadline â†’ unresolved. ``once``
    returns ``None``: single-use consent covers only the leader's execution,
    so the caller must issue a fresh prompt. Hooks fire with ``coalesced=True``
    so observers see the follower's lifecycle without a duplicate prompt.Ú	coalescedTuE   Coalesced approval wait interrupted â€” returning deny for session %s©r%   r(   )ÚdenyTr)   )NFNÚoncer   r   ©Úpre_approval_request)r.   rC   r7   r
   r;   r   rF   Úgetattr)r$   Úleaderr<   r8   r   r>   r=   rD   s           r   Ú_await_coalesced_leaderrP   e   s·   € ô 	×ÑÑO°wÑOÈ$ÓOÜ˜Ÿ™ kð'FôG€Eô ˜e VÓ,€IØ�Òà'Ñˆ‘Ø	�)Ò	Ø&Ñˆ‘à—‘ˆØ Ð%ˆØ�ÒàÙ(1ˆ[˜)Ñ$°r€EÜ�7˜H f¬g°f¸hÈÓ.MÑgÐY]ÐgÐafÑgÐgr   Úgateway)ÚsurfaceÚapproval_datarR   c          	      óø  ‡ ‡‡‡‡— ddl mŠ ddlm}m}m} ‰j                  dd«      }‰j                  dd«      ‰j                  dd«      |t        ‰j                  d|g«      «      ‰ |d	œ}t        ‰j                  d«      xs g «      Š‰j                  5  t        ˆˆfd
„‰j                  j                  ‰ g «      D «       d«      }	ddd«       	� |«       st        ‰ |	|«      }
|
�|
S t        ‰«      Š‰j                  5   |‰ ‰«       ‰j                  j                  ‰ g «      j                  ‰«       ddd«       dt        dt        dz  fˆˆˆ fd„}t!        j"                  di |¤Ž 	  |t%        ‰j&                  «      «        |«        t/        ‰j0                  ‰ d¬«      }t3        |‰«      }|dk(  r!|‰_        ‰j0                  j7                  «         ||«      }|dk(  rd}|dk7  xs |du}|rd|ini }t9        |||‰j:                  fi |¤ŽS # 1 sw Y   �ŒLxY w# 1 sw Y   ŒêxY w# t(        $ rG}t*        j-                  d|«        |d«       t!        j"                  di |¤ddi¤Ž ddddœcY d}~S d}~ww xY w)a/  Enqueue *approval_data*, notify the user, and block until resolved or timed
    out. Shared by the terminal command guard, the execute_code guard, the plugin
    escalation gate, and MCP elicitation. Returns ``{"resolved", "choice",
    "reason"}`` or ``{"resolved": False, "choice": None, "notify_failed": True}``
    when the notify callback raised. Persisting the choice and building the
    tool-facing result stay with the caller.

    Identical concurrent approvals (same command text + pattern-key set) are
    coalesced: parallel tool calls would otherwise fire N identical prompts
    the user must /approve N times while the agent sits wedged. Followers adopt
    the leader's ``session``/``always``/``deny``/timeout; a ``once`` covers only
    the leader, so the follower falls through to a fresh prompt.r   )Úapproval)Úapproval_publishedÚpreparing_terminal_approvalÚregister_prepared_approvalÚpattern_keyÚ ÚcommandÚdescriptionÚpattern_keys)r[   r\   rY   r]   r$   rR   c              3   óÒ   •K  — | ]^  }|j                   j                  d «      ‰j                  d «      k(  r/t        |j                   j                  d«      xs g «      ‰k(  r|–— Œ` y­w)r[   r]   N)r   rB   Úlist)Ú.0ÚerS   Úkeyss     €€r   ú	<genexpr>z*_await_gateway_decision.<locals>.<genexpr>œ   sY   øè ø€ ò K˜QØŸ&™&Ÿ*™* YÓ/°=×3DÑ3DÀYÓ3OÒOÜ §¡§
¡
¨>Ó :Ò @¸bÓAÀTÒIô ñ Kùs   ƒA$A'Nr8   r&   c                 ó¬  •— ‰j                   5  ‰j                  }‰j                  j                  ‰g «      }‰|v r|j	                  ‰«       |s‰j                  j                  ‰d«       ‰j                  dc}‰_        ddd«       �| dk(  r�dnd}n| }	  ||«       S S # 1 sw Y   Œ&xY w# t        $ r t        j                  dd¬«       Y S w xY w)aØ  Leave the queue and return the choice committed so far. Reading ``entry.result`` and
        removing the entry are one critical section under the approval lock: ``resolve_gateway_approval``
        commits under the same lock, so a choice that landed after the deadline check but before this
        removal is still ours to honour, and one arriving later finds no entry (the client is told
        nothing was pending instead of being acked "ok" while the agent denies).Nr*   r=   Úsession_closedzapproval settle hook failedT)Úexc_info)
Ú_lockr   Ú_gateway_queuesrB   ÚremoveÚpopr   Ú	Exceptionr0   Údebug)r8   r>   Úqueuer   r   Ú	_approvalr:   r$   s        €€€r   Ú_drop_entryz,_await_gateway_decision.<locals>._drop_entry©   sã   ø€ ð �_‰_ñ 	6Ø—\‘\ˆFØ×-Ñ-×1Ñ1°+¸rÓBˆEØ˜‰~Ø—‘˜UÔ#ÙØ×)Ñ)×-Ñ-¨k¸4Ô@Ø#(§<¡<°Ð ˆF�E”L÷	6ð Ðð ˜Š~Ø'-Ð'9™Ð?O‘à�ðKÙ�v”ð ˆˆvˆ÷)	6ð 	6ûô$ ò KÜ—‘Ð:ÀT�ÕJØˆðKús   ŽA0B#ÂB/ Â#B,Â/ CÃCz"Gateway approval notify failed: %sÚnotify_failedr>   FT)r=   r>   rp   u;   Approval wait interrupted â€” returning deny for session %srI   r(   rJ   r)   r   rL   r@   )ÚtoolsrU   Úagent.terminal_approval_batchrV   rW   rX   rB   r_   rg   Únextrh   rP   r	   r   ÚappendÚstrr.   rC   r   r   rk   r0   Úwarningr7   r
   r;   r   r*   rF   r   )r$   Ú	notify_cbrS   rR   rV   rW   rX   Úprimary_keyr<   rO   Úadoptedro   Úexcr8   r   r>   r=   rD   rn   r:   rb   s   ` `               @@@r   Ú_await_gateway_decisionr{   ‚   sy  ü€ õ ,ßyÑyà×#Ñ# M°2Ó6€Kà ×$Ñ$ Y°Ó3Ø$×(Ñ(¨¸Ó;Ø"Ü˜]×.Ñ.¨~À¸}ÓMÓNØ"¨wñ€Gô �×!Ñ! .Ó1Ò7°RÓ8€DØ	�‰ñ RÜô K )×";Ñ";×"?Ñ"?ÀÈRÓ"Pô KàLPóRˆ÷Rð ÐÑ"=Ô"?Ü)¨+°v¸wÓGˆØÐØˆNä˜=Ó)€EØ	�‰ñ LÙ" ;°Ô6Ø×!Ñ!×,Ñ,¨[¸"Ó=×DÑDÀUÔK÷Lðœ3ð ¤3¨¡:÷ ô: 	×ÑÑ?°wÒ?ðJÙ”$�u—z‘zÓ"Ô#ÙÔô ˜Ÿ™ [Ø&côe€Eä˜e UÓ+€IØ�Òà#ˆŒØ�‰�‰ÔÙ˜Ó€FØ�Òàˆð ˜	Ñ!Ò7 V°4Ð%7€HÙ(1ˆ[˜)Ñ$°r€EÜ�7˜H f¨e¯l©lÑD¸eÑDÐD÷KRñ Rú÷Lð LûôL ò JÜ�‰Ð;¸SÔAÙ�OÔ$Ü× Ñ Ñ]¸WÑ]È_Ó]Ø!¨TÀDÑIÕIûð	Jús6   Â1HÃ?5HÅ)"H) ÈHÈH&È)	I9È2<I4É.I9É4I9)r!   Úloggingr   r+   r   Útools.interruptr   r   rq   r   r.   Útools.approval_human_waitr   r   Ú	getLoggerr0   r	   r   ru   r7   r;   r   ÚboolrF   rP   r{   r#   r   r   ú<module>r�      sð   ðñ
ó Û Û Û ç @Ý *ß Kà	ˆ×	Ñ	Ð+Ó	,€÷*ñ *ð(�y—‘ð °Sð ÈCð ÐTWó ð>
˜ð 
¨¨d©
ó 
ð	O�Tð 	O Tð 	O°3¸±:ð 	OÐSWó 	Oðh¨ð h¸tó hð: ajò ^E¨ð ^EÈð ^EÐZ]ð ^EÐnrô ^Er   