
    (Gj                    l   d Z ddlZddlZddlZddlZddlZddlZddlZddlZddl	Z	ddl
Z
 ej                    dk    ZddlmZmZmZ ddlmZ ddlmZmZ ddlmZmZmZmZ ddlmZ  ej        e          Z e            d	z  Z d
Z!dZ"dZ#dZ$dZ%dZ&dZ'dZ(dZ)de*de+fdZ,e G d d                      Z- G d d          Z. e.            Z/de0de+fdZ1de2de+fdZ3de2ddfdZ4ddl5m6Z6m7Z7 dd d!d"g d#d$d%d"d&d'd"d(d'd)d*d+d,d)d-d'd)d.d+d,d/d0gd1d2Z8d3e2de2fd4Z9d5 Z: e6j;        dd6e8e:d78           dS )9a  
Process Registry -- In-memory registry for managed background processes.

Tracks processes spawned via terminal(background=true), providing:
  - Output buffering (rolling 200KB window)
  - Status polling and log retrieval
  - Blocking wait with interrupt support
  - Process killing
  - Crash recovery via JSON checkpoint file
  - Session-scoped tracking for gateway reset protection

Background processes execute THROUGH the environment interface -- nothing
runs on the host machine unless TERMINAL_ENV=local. For Docker, Singularity,
Modal, Daytona, and SSH backends, the command runs inside the sandbox.

Usage:
    from tools.process_registry import process_registry

    # Spawn a background process (called from terminal_tool)
    session = process_registry.spawn(env, "pytest -v", task_id="task_123")

    # Poll for status
    result = process_registry.poll(session.id)

    # Block until done
    result = process_registry.wait(session.id, timeout=300)

    # Kill it
    process_registry.kill(session.id)
    NWindows)_find_shell_resolve_safe_cwd_sanitize_subprocess_env)windows_hide_flags)	dataclassfield)AnyDictListOptional)get_hermes_homezprocesses.jsoni@ i  @   iQ       
      secondsreturnc                     t          dt          |                     }|dk     r| dS t          |d          \  }}|dk     r| d| dS t          |d          \  }}| d| dS )Nr   <   szm zh m)maxintdivmod)r   r   minssecshourss        </home/rurouni/.hermes/hermes-agent/tools/process_registry.pyformat_uptime_shortr!   O   s    As7||A2vvwww2JD$byy!!$!!!!r""KE4t    c                      e Zd ZU dZeed<   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d
<   dZe	e         ed<   dZeed<   dZe	e
         ed<   d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<   e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d<   dZ#eed<   dZ$e
ed <   dZ%eed!<    e&e'"          Z(e)e         ed#<    e&dd$          Z*e
ed%<    e&dd$          Z+e
ed&<    e&dd$          Z,eed'<    e&dd$          Z-eed(<    e&dd$          Z.eed)<    e&dd$          Z/eed*<    e&dd$          Z0e
ed+<    e&e1j2        d,          Z3e1j2        ed-<    e&e1j4        "          Z5e1j4        ed.<    e&dd$          Z6e	e1j7                 ed/<    e&dd$          Z8eed0<   dS )1ProcessSessionz3A tracked background process with output buffering.idcommand task_idsession_keyNpidprocessenv_refcwd        
started_athost_start_timeFexited	exit_codecompletion_reasontermination_sourceoutput_buffermax_output_charsdetachedhost	pid_scopewatcher_platformwatcher_chat_idwatcher_user_idwatcher_user_namewatcher_thread_idwatcher_message_idr   watcher_intervalnotify_on_complete)default_factorywatch_patterns)defaultrepr_watch_hits_watch_suppressed_watch_disabled_watch_last_emit_at_watch_cooldown_until_watch_strike_candidate_watch_consecutive_strikes)rB   rE   _completion_event_lock_reader_thread_pty)9__name__
__module____qualname____doc__str__annotations__r(   r)   r*   r   r   r+   
subprocessPopenr,   r
   r-   r/   floatr0   r1   boolr2   r3   r4   r5   MAX_OUTPUT_CHARSr6   r7   r9   r:   r;   r<   r=   r>   r?   r@   rA   r	   listrC   r   rF   rG   rH   rI   rJ   rK   rL   	threadingEventrM   LockrN   rO   ThreadrP    r"   r    r$   r$   Z   sX        ==GGGLLLGSKC#*.GXj&'...GSC#J%)OXc])))FD#Ix}###%s%%%    M3,c,,,HdIscOSOSss    c$$$$ %d ; ; ;NDI;;;uQU333K333"U15999s999!E%e<<<OT<<< "'s!?!?!????#(55#A#A#A5AAA$)E%e$D$D$DTDDD&+eAE&B&B&BBBB).yUZ)[)[)[y[[[!E).AAAE9>AAA16t%1P1P1PNHY-.PPPd///D#/////r"   r$   c                      e Zd ZdZdZd Zededefd            Zde	dedd	fd
Z
de	dedd	fdZdedefdZedee         defd            Zedee         dee         fd            Zedee         dee         defd            Zdee	         dee	         fdZedefd            Zedefd            ZedPdedee         dd	fd            Zededefd            Z	 	 	 	 	 dQdedededed ed!ede	fd"Z	 	 	 	 dRdededededed$ede	fd%Zde	fd&Zde	ded'ed(ed)ef
d*Zde	fd+Z de	fd,Z!d-edefd.Z"d-edefd/Z#d-edefd0Z$dSd2Z%d-edee	         fd3Z&dTd5Z'd-edefd6Z(dUd-ed9ed:edefd;Z)dPd-ed$edefd<Z*d=d>d-ed?edefd@Z+d-edAedefdBZ,dVd-edAedefdCZ-d-edefdDZ.d-edefdEZ/defdFZ0dWdedede1fdGZ2dedefdHZ3	 dPdedIee         defdJZ4defdKZ5dPdedefdLZ6dM Z7dN Z8defdOZ9d	S )XProcessRegistrya$  
    In-memory registry of running and finished background processes.

    Thread-safe. Accessed from:
      - Executor threads (terminal_tool, process tool handlers)
      - Gateway asyncio loop (watcher tasks, session reset checks)
      - Cleanup thread (sandbox reaping coordination)
    )z'bash: cannot set terminal process groupz"bash: no job control in this shellzno job control in this shellz!cannot set terminal process groupz)tcsetattr: Inappropriate ioctl for devicec                 j   i | _         i | _        t          j                    | _        g | _        dd l}|                                | _        t                      | _
        t                      | _        t          j                    | _        d| _        d| _        d| _        d| _        d | _        d | _        d S )Nr   r.   )_running	_finishedr]   r_   rN   pending_watchersqueueQueuecompletion_queueset_completion_consumed_poll_observed_global_watch_lock_global_watch_window_start_global_watch_window_hits_global_watch_tripped_until$_global_watch_suppressed_during_trip	on_outputon_close)self
_queue_mods     r    __init__zProcessRegistry.__init__   s    3546^%%
 79 	#"""2<2B2B2D2D *-! $'55
 #,."2"214'./&25(9:1 
 r"   textr   c                    |                      d          rat          fdt          j        D                       r<                    d           r%t          fdt          j        D                       <d                              S )z:Strip shell startup warnings from the beginning of output.
c              3   ,   K   | ]}|d          v V  dS )r   Nra   ).0noiseliness     r    	<genexpr>z5ProcessRegistry._clean_shell_noise.<locals>.<genexpr>   s,      cc%EU1X-ccccccr"   r   )splitanyrc   _SHELL_NOISE_SUBSTRINGSpopjoin)rx   r~   s    @r    _clean_shell_noisez"ProcessRegistry._clean_shell_noise   s     

4   	cccc?;bccccc 	IIaLLL  	cccc?;bccccc 	yyr"   sessionchunkNc                 \    | j         }||sdS 	  |||           dS # t          $ r Y dS w xY w)zForward a freshly-read chunk to the live-output sink, if one is set.
        Called from reader threads; never raise into the read loop.N)rs   	Exception)ru   r   r   sinks       r    _emit_outputzProcessRegistry._emit_output   sX     ~<u<F	D%      	 	 	DD	s    
++new_textc                    |j         r|j        rdS |j        rdS g }d}|                                D ]=}|j         D ]3}||v r-|                    |                                           ||} n4>|sdS t          j                    }d}|j        5  |j        ri||j        k     r^|xj	        t          |          z  c_	        |j        s7d|_        |xj        dz  c_        |j        t          k    rd|_        d|_        d}d}	nR|j        r|j        sd|_        d|_        ||_        |t           z   |_        |xj        dz  c_        |j	        }
d|_	        d}	ddd           n# 1 swxY w Y   |	rv|rr| j                            |j        |j        |j        d|j	        |j        |j        |j        |j        |j        |j        d|j         dt           d	t            d
d           dS d                    |dd                   }t          |          dk    r|dd         dz   }|                     |          sdS | j                            |j        |j        |j        d|||
|j        |j        |j        |j        |j        |j        d           dS )uz  Scan new output for watch patterns and queue notifications.

        Called from reader threads with new_text being the freshly-read chunk.

        Per-session rate limit: at most ONE watch-match notification per
        WATCH_MIN_INTERVAL_SECONDS. Any match arriving inside the cooldown
        window is dropped and counts as ONE strike for that window. After
        WATCH_STRIKE_LIMIT consecutive strike windows, watch_patterns is
        disabled for this session and the session is promoted to
        notify_on_complete semantics — one notification when the process
        actually exits, no more mid-process spam.
        NFT   r   watch_disabledz$Watch patterns disabled for process u    — z7 consecutive rate-limit windows triggered (min spacing zms). Falling back to notify_on_complete semantics; you'll get exactly one notification when the process exits.)
session_idr)   r&   type
suppressedplatformchat_iduser_id	user_name	thread_id
message_idmessagerz      i  z
...(truncated)watch_match)r   r)   r&   r   patternoutputr   r   r   r   r   r   r   )rC   rH   r1   
splitlinesappendrstriptimerN   rJ   rG   lenrK   rL   WATCH_STRIKE_LIMITrA   rI   WATCH_MIN_INTERVAL_SECONDSrF   rj   putr%   r)   r&   r:   r;   r<   r=   r>   r?   r   _global_watch_admit)ru   r   r   matched_linesmatched_patternlinepatnowshould_disablereturn_earlyr   r   s               r    _check_watch_patternsz%ProcessRegistry._check_watch_patterns   s    % 	)@ 	F
 > 	F '')) 	 	D-  $;;!((777&.*-E	   	Fikk] %	% %	%
 ,  %w7T1T1T))S-?-??))6 	.6:G366!;669=OOO26/ 6:2)-# 1;#;; :;G627/ /2+036P0P-##q(##$6
,-)$K%	% %	% %	% %	% %	% %	% %	% %	% %	% %	% %	% %	% %	% %	% %	%N  	  %))")*#*#6&,")"; ' 8&6&6!(!:!(!:")"<Lwz L L-L L(BL L L+ +   ( F ="-..v;;ETE]%77F '',, 	F!!!*".!&$0.. 2 2!4#
 #
 	 	 	 	 	s   CEE#&E#r   c                    | j         5  | j        rJ|| j        k    r?| j        }d| _        d| _        || _        d| _        |dk    rdddd|d| ddddddd}nd}nd}| j        r || j        k     r| xj        d	z  c_        d
}d}ni|| j        z
  t
          k    r|| _        d| _        | j        t          k    r$|t          z   | _        | xj        d	z  c_        |}d
}n| xj        d	z  c_        d}d}ddd           n# 1 swxY w Y   || j        	                    |           |>| j        	                    dddddt           dt
           dt           ddddddd
           |S )a1  Return True if this watch_match event is allowed through the global breaker.

        Semantics:
        - If we're currently in a cooldown period, drop the event and count it.
        - Otherwise, slide the rolling window and check the global cap.
        - If the cap is exceeded, trip the breaker for WATCH_GLOBAL_COOLDOWN_SECONDS
          and emit ONE summary event so the agent/user sees "N notifications were
          suppressed" instead of getting them individually.
        - When the cooldown ends, emit a release summary and reset counters.
        r.   r   r'   watch_overflow_releasedz%Watch-pattern notifications resumed. z1 match event(s) were suppressed during the flood.)r   r)   r&   r   r   r   r   r   r   r   r   Nr   FTwatch_overflow_trippedzWatch-pattern overflow: >z notifications in zCs across all processes. Suppressing further watch_match events for zs.)
r   r)   r&   r   r   r   r   r   r   r   )
rn   rq   rr   ro   rp   WATCH_GLOBAL_WINDOW_SECONDSWATCH_GLOBAL_MAX_PER_WINDOWWATCH_GLOBAL_COOLDOWN_SECONDSrj   r   )ru   r   r   release_msgadmittrip_nows         r    r   z#ProcessRegistry._global_watch_admitd  sb    $ 3	! 3	!/ #C4;[4[4[!F
360<=925/12.>> ')')#% 9&0])] ] ] %'#%#%%'%'# #KK" #'KK" / !C$:Z4Z4Z99Q>99 88<WWW69D356D215PPP7:=Z7ZD4==B=="H!EE22a722#H Eg3	! 3	! 3	! 3	! 3	! 3	! 3	! 3	! 3	! 3	! 3	! 3	! 3	! 3	! 3	!l "!%%k222!%% !090K 9 9(C9 9 59 9 9
 ' '   " s   C$C88C<?C<r*   c                 ,    | sdS ddl m}  ||           S )z1Best-effort liveness check for host-visible PIDs.Fr   )_pid_exists)gateway.statusr   )r*   r   s     r    _is_host_pid_alivez"ProcessRegistry._is_host_pid_alive  s5      	5 	/.....{3r"   c                 P    | sdS 	 ddl m}  ||           S # t          $ r Y dS w xY w)z<Kernel start ticks for a host PID, or None when unavailable.Nr   )get_process_start_time)r   r   r   )r*   r   s     r    _safe_host_start_timez%ProcessRegistry._safe_host_start_time  s[      	4	======))#... 	 	 	44	s    
%%expected_startc                 j    |                      |          sdS |dS |                     |          |k    S )u  True only if ``pid`` is alive AND still the process we spawned.

        The kernel recycles PID/PGID numbers once a process exits and is reaped,
        so a stored PID can later name an *unrelated* process — observed in the
        wild as a recycled number landing on a desktop browser's session leader,
        which our tree-kill then SIGTERMs (Firefox dying at irregular intervals).
        We compare the kernel start time captured at spawn against the live one;
        a mismatch means the number was recycled and must never be signalled.

        When no baseline was captured (legacy checkpoints, or platforms without
        ``/proc``) we degrade to a bare liveness check rather than refusing to
        act, preserving prior best-effort behaviour.
        FNT)r   r   )clsr*   r   s      r    _host_pid_is_oursz!ProcessRegistry._host_pid_is_ours  sC     %%c** 	5!4((--??r"   c                 2   ||j         s|j        r|j        dk    r|S |                     |j        |j                  r|S |j        5  |j         r|cddd           S d|_         d|_        ddd           n# 1 swxY w Y   |                     |           |S )zJUpdate recovered host-PID sessions when the underlying process has exited.Nr8   T)	r1   r7   r9   r   r*   r0   rN   r2   _move_to_finished)ru   r   s     r    _refresh_detached_sessionz)ProcessRegistry._refresh_detached_session  s   ?gn?G4D?HY]cHcHcN
 !!'+w/FGG 	N] 	% 	%~ 	% 	% 	% 	% 	% 	% 	% 	% "GN !%G	% 	% 	% 	% 	% 	% 	% 	% 	% 	% 	% 	% 	% 	% 	% 	w'''s   	A7A77A;>A;c                     	 ddl }|                                 sdS |                                 |j        k    S # t          $ r Y dS w xY w)zTrue if a psutil.Process is running and not a zombie.

        A zombie is already dead (just unreaped), so there's nothing to SIGKILL.
        r   NF)psutil
is_runningstatusSTATUS_ZOMBIEr   )procr   s     r    _proc_alivezProcessRegistry._proc_alive  s_    	MMM??$$ u;;==F$888 	 	 	55	s   9 9 
AAc                      	 ddl m} m}m}  |             } ||dd          }||d         d         }t	          t          |          d          S # t          $ r Y dS w xY w)a%  Grace window (s) between SIGTERM and escalated SIGKILL.

        Read from ``terminal.daemon_term_grace_seconds`` in config.yaml; floored
        at 0 (0 disables escalation). Falls back to the DEFAULT_CONFIG value if
        config is unreadable, so callers always get a sane number.
        r   )read_raw_configcfg_getDEFAULT_CONFIGterminaldaemon_term_grace_secondsNr.   g       @)hermes_cli.configr   r   r   r   rY   r   )r   r   r   cfgvals        r    _daemon_term_grace_secondsz*ProcessRegistry._daemon_term_grace_seconds	  s    	RRRRRRRRRR!/##C'#z+FGGC{$Z01LMuSzz3''' 	 	 	33	s   AA 
AAc                     |3                      ||          st                              d|           dS t          r	 t	          j        ddt          |          ddgdddt                      t          j        	           n`# t          t          j
        t          f$ rA 	 t          j        |t          j                   n# t          t           t"          f$ r Y nw xY wY nw xY wdS d
dl}	 |                    |          }nb# |j        $ r Y dS t          t"          f$ rB 	 t          j        |t          j                   n# t          t           t"          f$ r Y nw xY wY dS w xY w	 |                    d          }n# |j        |j        t          f$ r g }Y nw xY w|                    |           |D ]9}	 |                                 # |j        $ r Y $|j        t          f$ r Y 6w xY w                                 }|d
k    rdS t5          j                    |z   }t5          j                    |k     rGt9           fd|D                       sn+t5          j        d           t5          j                    |k     G|D ]p}	                      |          s|                                 t                              d|j         |           O# |j        $ r Y [|j        t          f$ r Y mw xY wdS )u	  Terminate a host-visible PID and its descendants.

        ``expected_start`` is the kernel start time captured when we spawned the
        process. When provided, it is re-validated against the live PID before
        any signal is sent; a mismatch (or a dead PID) means the number was
        recycled onto an unrelated process and we refuse to touch it, so a stale
        background-session PID can never tree-kill a browser or other stranger.

        POSIX: walks the process tree with ``psutil`` and SIGTERMs
        children before the parent so subprocess trees (e.g. Chromium
        renderers/GPU helpers spawned by an ``agent-browser`` daemon)
        don't get reparented to init and survive cleanup.  After a bounded
        grace window (``terminal.daemon_term_grace_seconds``) any tree member
        that ignored SIGTERM — a daemon stalled in its signal handler — is
        escalated to SIGKILL so it can't leak indefinitely.  Set the grace to
        0 to disable escalation (SIGTERM only).

        Windows: shells out to ``taskkill /PID <pid> /T /F``. This is
        the documented Microsoft primitive for tree-kill and matches the
        existing convention in ``gateway.status.terminate_pid``.  ``/F`` is
        already a hard kill, so no separate escalation step is needed.  We
        can't reuse the POSIX psutil path on Windows because:

          1. Windows doesn't maintain a Unix-style process tree —
             ``psutil.Process.children(recursive=True)`` walks PPID
             links that go stale when intermediate processes exit, so
             enumeration is best-effort and misses orphaned descendants.
          2. ``psutil.Process.terminate()`` on Windows is
             ``TerminateProcess()`` which kills only the target handle
             and is a hard kill — there is no Windows equivalent of a
             SIGTERM that cascades through a process group. (See the
             warning in ``gateway/status.py::terminate_pid``: "os.kill
             with SIGTERM is not equivalent to a tree-killing hard stop"
             on Windows.) Headless Chromium has no GUI window, so the
             softer ``taskkill /T`` without ``/F`` won't reach it either.

        ``psutil`` is a hard dependency (see ``pyproject.toml``); the
        bare-``os.kill`` fallback covers OSError / PermissionError on
        POSIX and a missing ``taskkill.exe`` on Windows (effectively
        unreachable on real Windows installs, but cheap insurance).
        Nuf   Refusing to terminate host pid %d: start-time mismatch — PID was recycled onto an unrelated process.taskkillz/PIDz/Tz/FTr   )capture_outputrx   timeoutcreationflagsstdinr   )	recursivec              3   B   K   | ]}                     |          V  d S N)r   )r|   _pr   s     r    r   z6ProcessRegistry._terminate_host_pid.<locals>.<genexpr>  s/      ==rsr**======r"   g?zDEscalated to SIGKILL for pid %d (ignored SIGTERM within %.1fs grace))!r   loggerwarning_IS_WINDOWSrW   runrU   r   DEVNULLFileNotFoundErrorTimeoutExpiredOSErroroskillsignalSIGTERMProcessLookupErrorPermissionErrorr   ProcessNoSuchProcesschildrenAccessDeniedr   	terminater   r   	monotonicr   sleepr   infor*   )	r   r*   r   r   parenttargetsr   gracedeadlines	   `        r    _terminate_host_pidz#ProcessRegistry._terminate_host_pid  s   V %c.C.CC.X.X% NN>?B   F 	S4>#'"4"6"6$,     &z'@'J   GC0000!3_E   D
 F		^^C((FF# 	 	 	FF) 	 	 	V^,,,,/A   FF		ooo55GG$f&97C 	 	 	GGG	v 	 	D    '   '1    ..00A::F >##e+n))====W===== Jt n))  	 	Dt,, 		#$(He    '   '1   	 	s   AB CB?>C?CCCCC)C? ?
EED=<E=EEEEE"E9 9FF2G
G&G&%G&>K
5K


K)K)(K)envc                 D   t          | dd          }t          |          r	  |            }t          |t                    r,|                    d          r|                    d          pdS n2# t          $ r%}t                              d|           Y d}~nd}~ww xY wdS )zEReturn the writable sandbox temp dir for env-backed background tasks.get_temp_dirN/z*Could not resolve environment temp dir: %sz/tmp)	getattrcallable
isinstancerU   
startswithr   r   r   debug)r   r   temp_direxcs       r    _env_temp_dirzProcessRegistry._env_temp_dir  s     sND99L!! 	PP'<>>h,, 71D1DS1I1I 7#??3//636 P P PI3OOOOOOOOPvs   A
A. .
B8BBr'   Fr&   r-   r(   r)   env_varsuse_ptyc                 \   t          dt          j                    j        dd          |||t	          |pt          j                              t          j                              }|r	 t          rddl	m
} nddlm
} t                      }	t          t
          j        |          }
d|
d<   |                    |	d	d
| g|j        |
d          }|j        |_        |                     |j                  |_        ||_        t+          j        | j        |fdd|j                   }||_        |                                 | j        5  |                                  || j        |j        <   ddd           n# 1 swxY w Y   |                                  |S # t>          $ r t@          !                    d           Y n1tD          $ r%}t@          !                    d|           Y d}~nd}~ww xY wt                      }	t          t
          j        |          }d|d<   t          rdtG                      ini }tI          j%        |	d	d
| gfd|j        |ddtH          j&        tH          j'        tH          j(        dd	|}||_)        |j        |_        |                     |j                  |_        	 t+          j        | j*        |fdd|j                   }||_        |                                 | j        5  |                                  || j        |j        <   ddd           n# 1 swxY w Y   |                                  n# tD          $ r 	 t          s	 tW          tX          dtX          j-                  }t          j.        t          j/        |j                  |           nE# t`          tb          td          f$ r |3                                 Y nw xY w|3                                 n# tD          $ r Y nw xY w	 |4                    d           n# tD          $ r Y nw xY w w xY w|S )aw  
        Spawn a background process locally.

        Only for TERMINAL_ENV=local. Other backends use spawn_via_env().

        Args:
            use_pty: If True, use a pseudo-terminal via ptyprocess for interactive
                     CLI tools (Codex, Claude Code, Python REPL). Falls back to
                     subprocess.Popen if ptyprocess is not installed.
        proc_N   )r%   r&   r(   r)   r-   r/   r   )
PtyProcess1PYTHONUNBUFFEREDz-liczset +m; )r   x   )r-   r   
dimensionsTzproc-pty-reader-targetargsdaemonnamez3ptyprocess not installed, falling back to pipe modez0PTY spawn failed (%s), falling back to pipe moder   utf-8replace)	rx   r-   r   encodingerrorsstdoutstderrr   start_new_sessionzproc-reader-SIGKILL   r   )5r$   uuiduuid4hexr   r   getcwdr   r   winptyr  
ptyprocessr   r   environspawnr-   r*   r   r0   rP   r]   r`   _pty_reader_loopr%   rO   startrN   _prune_if_neededre   _write_checkpointImportErrorr   r   r   r   rW   rX   PIPESTDOUTr   r+   _reader_loopr   r   r   killpggetpgidr   r   r   r   wait)ru   r&   r-   r(   r)   r  r	  r   _PtyProcessCls
user_shellpty_envpty_procreaderebg_env_popen_kwargsr   kill_signals                     r    spawn_localzProcessRegistry.spawn_local  s5   & !.tz||',..#!#"455y{{
 
 
  )	V'V HCCCCCCCGGGGGG(]]
22:xHH.1*+)//)=G)=)=>(	 0   'l*.*D*DW[*Q*Q'' #)0!8GJ88	   *0&Z 8 8))+++07DM'*-8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 &&((( V V VTUUUUU V V VQSTUUUUUUUUV !]]
 *"*h??%(!"CNV*<*>*>??TV!5G!5!56
?$$"
 
 
 
 h"&"<"<W["I"I#	%(Z0GJ00	  F &,G"LLNNN 4 4%%''',3gj)4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 ""$$$$ 	 	 	
"  $&-fi&P&P	"*TX"6"6DDDD.I $ $ $		$ IIKKK   		!	$$$$   '	* s   ,CF $E;/F ;E??F E?F $G0	G0G++G01AM	 9$L)M	 )L--M	 0L-1M	 	
P)O/AN)(O/)+OO/OO/.P)/
O<9P);O<<P) PP)
P$!P)#P$$P)r   r   c                    t          dt          j                    j        dd          ||||t	          j                    |d          }|                     |          }| d|j         d}	| d|j         d}
| d|j         d	}t          j        |          }t          j        |          }t          j        |	          }t          j        |
          }t          j        |          }d
| d| d| d| d| d| }	 |	                    ||d          }|
                    dd                                          }|                                D ]@}|                                }|                                rt          |          |_         nA|j        |d|_        t          |
                    dd                    |_        |j        dk    rd|_        d|_        d|_        |
                    dd                                          |_        n=# t*          $ r0}d|_        d|_        d|_        d|_        d| |_        Y d}~nd}~ww xY w|j        sEt-          j        | j        |||	|
|fdd|j                   }||_        |                                 | j        5  |                                  |j        s|| j        |j        <   ddd           n# 1 swxY w Y   |j        s|                                  |S )a#  
        Spawn a background process through a non-local environment backend.

        For Docker/Singularity/Modal/Daytona/SSH: runs the command inside the sandbox
        using the environment's execute() interface. We wrap the command to
        capture the in-sandbox PID and redirect output to a log file inside
        the sandbox, then poll the log via subsequent execute() calls.

        This is less capable than local spawn (no live stdout pipe, no stdin),
        but it ensures the command runs in the correct sandbox context.
        r  Nr  sandbox)r%   r&   r(   r)   r-   r/   r,   r9   z/hermes_bg_z.logz.pidz.exitz	mkdir -p z && ( nohup bash -lc z > z$ 2>&1; rc=$?; printf '%s\n' "$rc" > z ) & echo $! > z && cat F)r   rewrite_compound_backgroundr   r'   T
returncoder   failed_startzFailed to start: zproc-poller-r  )r$   r!  r"  r#  r   r  r%   shlexquoteexecutegetstripr   isdigitr   r*   r1   r2   r3   r4   r5   r   r]   r`   _env_poller_looprO   r*  rN   r+  re   r,  )ru   r   r&   r-   r(   r)   r   r   r  log_pathpid_path	exit_pathquoted_commandquoted_temp_dirquoted_log_pathquoted_pid_pathquoted_exit_path
bg_commandresultr   r   r9  r8  s                          r    spawn_via_envzProcessRegistry.spawn_via_env5  s   ( !.tz||',..#y{{	
 	
 	
 %%c**;;7:;;;;;7:;;;==GJ===	W--+h//+h//+h// ;y11D D D .D D3BD D/?D D )D D 3BD D 		<[[,1 !  F
 ZZ"--3355F))++  zz||<<>> "%d))GKE {"!%$'

<(D(D$E$E!$))(*G%,:)-;*(.

8R(@(@(F(F(H(H% 	< 	< 	<!GN "G(6G%)7G&$;$;$;G!!!!!!	< ~ 		%,sHh	B0GJ00	  F &,G"LLNNNZ 	4 	4!!###> 4,3gj)	4 	4 	4 	4 	4 	4 	4 	4 	4 	4 	4 	4 	4 	4 	4
 ~ 	%""$$$s+   ?DH 
I"&II(+KK#&K#c                    d}	 |j         j        }|	 	 |j                             d           n2# t          $ r%}t                              d|           Y d}~nd}~ww xY wd|_        |j        dk    r|j         j        |_	        d|_        | 
                    |           dS t          t          |dd          d	d          }	 |& |d
          }|sn|                    dd          }n|                    d
          }|sn|r|                     |          }d}|j        5  |xj        |z  c_        t#          |j                  |j        k    r|j        |j         d         |_        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	 |j                             d           n2# t          $ r%}t                              d|           Y d}~nd}~ww xY wd|_        |j        dk    r|j         j        |_	        d|_        | 
                    |           dS # 	 |j                             d           n2# t          $ r%}t                              d|           Y d}~nd}~ww xY wd|_        |j        dk    r|j         j        |_	        d|_        | 
                    |           w xY w)a{  Background thread: read stdout from a local Popen process.

        IMPORTANT: avoid ``TextIOWrapper.read(4096)`` here. On pipes that call can
        block until EOF (or a large buffer fills), which makes "live" output land
        in one burst at process exit. ``buffer.read1(4096)`` yields incremental
        chunks as bytes become available, then we decode to text.
        TNr  r   z$Process wait timed out or failed: %skilledr1   bufferread1   r  r  r  FzProcess stdout reader ended: %s)r+   r  r3  r   r   r  r1   r3   rA  r2   r   r   decodereadr   rN   r5   r   r6   r   r   )ru   r   first_chunkr  r9  raw_readrawr   s           r    r0  zProcessRegistry._reader_loop  s    (	,_+F~:H$$Q$//// H H HCQGGGGGGGGH!GN(H44$+O$>!,4)""7+++++G wvx>>NNH2'"(4..C JJwyJAAEE #KK--E   ( 33E::E"'K] b b))U2))7011G4LLL070EwG_F_F`F`0a-b b b b b b b b b b b b b b b **7E:::!!'5111+2,  	? 	? 	?LL:A>>>>>>>>	?H$$Q$//// H H HCQGGGGGGGGH!GN(H44$+O$>!,4)""7+++++H$$Q$//// H H HCQGGGGGGGGH!GN(H44$+O$>!,4)""7++++s   F1 0 
AAA#BF1 $AE8,F1 8E<<F1 ?E< 0F1 0I3 1
G ;GI3 G  I3 $H   
H/
H**H/3L5JL
K J;6L;K  ALrK  rL  rM  c                    t          j        |          }t          j        |          }t          j        |          }d}	|j        st          j        d           	 |                    d| dd          }
|
                    dd          }|rt          |          |	k    r
||	d	         nd}t          |          }	|j        5  ||_	        t          |j	                  |j
        k    r|j	        |j
         d	         |_	        d	d	d	           n# 1 swxY w Y   |r,|                     ||           |                     ||           |                    d
| dd          }|                    dd                                          }|r|                                d                                         dk    r|                    d| dd          }|                    dd                                          }	 t          |                                d                                                   |_        n# t"          t$          f$ r
 d|_        Y nw xY wd|_        |j        dk    rd|_        |                     |           d	S nB# t*          $ r5 d|_        d|_        d|_        d|_        |                     |           Y d	S w xY w|j        d	S d	S )zBBackground thread: poll a sandbox log file for non-local backends.r      zcat  2>/dev/nullr   r   r   r'   Nzkill -0 "$(cat z# 2>/dev/null)" 2>/dev/null; echo $?r  rB  0TrW  r1   lostbackend_lost)rD  rE  r1   r   r   rF  rG  r   rN   r5   r6   r   r   rH  r   r   r2   
ValueError
IndexErrorr3   r   r   r4   )ru   r   r   rK  rL  rM  rP  rQ  rR  prev_output_lenrT  
new_outputdeltacheckcheck_outputexit_resultexit_strs                    r    rJ  z ProcessRegistry._env_poller_loop  sx     +h//+h// ;y11. 0	JqMMM.%IO%I%I%ISUVV#ZZ"55
 
:<?
OOo<]<]J'7'788ceE&)*ooO  f f0:-w4558PPP4;4I7KcJcJdJd4eG1f f f f f f f f f f f f f f f  :227EBBB))'5999 \\\\ $    %yy266<<>> L$;$;$=$=b$A$G$G$I$IS$P$P"%++=/=== ! #. # #K  +x<<BBDDH/,/0C0C0E0Eb0I0O0O0Q0Q,R,R))&
3 / / /,.)))/%)GN0H<<4<1**7333F   !%$&!,2)-;*&&w///S . 0	 0	 0	 0	 0	s\   A(J ?DJ DJ DC*J >I  J IJ I1J ;KKc                    |j         }	 |                                r		 |                    d          }|rt          |t                    r|n|                    dd          }|j        5  |xj        |z  c_        t          |j                  |j	        k    r|j        |j	         d         |_        ddd           n# 1 swxY w Y   | 
                    ||           |                     ||           n# t          $ r Y n$t          $ r Y nw xY w|                                	n2# t          $ r%}t                              d|           Y d}~nd}~ww xY w	 |                                 n2# t          $ r%}t                              d|           Y d}~nd}~ww xY wd|_        |j        d	k    r%t'          |d
          r|j        nd|_        d|_        |                     |           dS )z2Background thread: read output from a PTY process.rZ  r  r  r[  NzPTY stdout reader ended: %sz PTY wait timed out or failed: %sTrW  
exitstatusrB  r1   )rP   isaliver]  r  rU   r\  rN   r5   r   r6   r   r   EOFErrorr   r   r  r3  r1   r3   hasattrrq  r2   r   )ru   r   ptyr   rx   r9  s         r    r)  z ProcessRegistry._pty_reader_loop  s   l	;++-- HHTNNE 9(25#(>(>kuuELLQXajLDkDk$] j j#11T911"7#899G<TTT8?8MwOgNgNhNh8i 5j j j j j j j j j j j j j j j 227DAAA))'4888   E    E ++--    	; 	; 	;LL6::::::::	;	@HHJJJJ 	@ 	@ 	@LL;Q????????	@$0029#|2L2L TRTG(0G%w'''''s   D( AC7 +AB?3C7 ?CC7 C/C7 6D( 7
DD( 	DD( DD( (
E2EEE0 0
F:FFc                    | j         5  | j                            |j        d          du}|| j        |j        <   ddd           n# 1 swxY w Y   |j                                         |                                  |rq|j        rlddl	m
} |j        r ||j        dd                   nd}| j                            d|j        |j        |j        |j        |j        |j        |d           dS dS dS )u   Move a session from running to finished.

        Idempotent: if the session was already moved (e.g. kill_process raced
        with the reader thread), the second call is a no-op — no duplicate
        completion notification is enqueued.
        Nr   
strip_ansi0r'   
completion)r   r   r)   r&   r2   r3   r4   r   )rN   re   r   r%   rf   rM   rk   r,  rA   tools.ansi_striprx  r5   rj   r   r)   r&   r2   r3   r4   )ru   r   was_runningrx  output_tails        r    r   z!ProcessRegistry._move_to_finished*  sp    Z 	1 	1-++GJ==TIK)0DN7:&	1 	1 	1 	1 	1 	1 	1 	1 	1 	1 	1 	1 	1 	1 	1 	!%%'''   
  	75 	333333GNG\d**W%:566%BCCCbdK!%%$%j&2"?$.%,%>&-&@%	' 	' 	 	 	 	 		 	 	 	s   2AA
A
r   c                     || j         v S )zECheck if a completion notification was already consumed via wait/log.)rl   ru   r   s     r    is_completion_consumedz&ProcessRegistry.is_completion_consumedJ  s    T666r"   c                 R   |sdS | j         5  | j                            |          p| j                            |          }ddd           n# 1 swxY w Y   |dS 	 |                     |           n# t
          $ r Y nw xY w|j        rdS |j        r|j        s|j	        dk    rdS dS )u  Whether a goal loop parked on this session should still be parked.

        Used by the goal-loop wait barrier (``hermes_cli.goals``) to support
        waiting on a process's OWN trigger, not just its exit. A session is
        "still waiting" when:
          - it is still running, AND
          - if it has ``watch_patterns``, none has matched yet (so a
            long-lived watcher that fires a trigger mid-run — and may never
            exit — unblocks the moment its pattern hits, not on exit).

        Returns False (don't wait) when the session has exited, its watch
        pattern has already fired, or the session is unknown — so a stale or
        already-triggered barrier can never wedge the loop.
        FNr   T)
rN   re   rG  rf   r   r   r1   rC   rH   rF   ru   r   r   s      r    is_session_waitingz"ProcessRegistry.is_session_waitingN  s-     	5Z 	V 	Vm''
33Ut~7I7I*7U7UG	V 	V 	V 	V 	V 	V 	V 	V 	V 	V 	V 	V 	V 	V 	V?5	**73333 	 	 	D	> 	5 ! 	'*A 	"Q&&uts#   5AAAA3 3
B ?B c                 &    || j         v p|| j        v S )uS  Whether the CLI drain should skip a completion event for this session.

        Skips when the agent has either truly consumed the output (wait/log →
        ``_completion_consumed``) or observed the exit inline via poll()
        (``_poll_observed``).  In both cases the CLI agent already has the
        result this turn, so injecting a [SYSTEM: ...] completion would be a
        duplicate (#8228).  The gateway/tui watchers do NOT use this — they
        check only ``is_completion_consumed`` so a read-only poll never
        suppresses their autonomous delivery turn (#10156).
        )rl   rm   r  s     r    _drain_should_skipz"ProcessRegistry._drain_should_skipr  s     T66[*H[:[[r"   list[tuple[dict, str]]c                    g }| j                                         s	 | j                                         }n# t          $ r Y nw xY w|                    dd          }|                    d          dk    r|                     |          rt          |          }|r|                    ||f           | j                                         |S )a  Pop all pending notification events and return formatted pairs.

        Returns a list of (raw_event, formatted_text) tuples.
        Skips completion events the agent already consumed via wait/log or
        observed inline via poll() (see ``_drain_should_skip``).
        r   r'   r   rz  )rj   empty
get_nowaitr   rG  r  format_process_notificationr   )ru   resultsevt_evt_sidrx   s        r    drain_notificationsz#ProcessRegistry.drain_notifications  s     '--// 
	,+6688   ww|R00Hwwv,..43J3J83T3T..s33D ,T{+++ '--// 
	, s   7 
AAc                     | j         5  | j                            |          p| j                            |          }ddd           n# 1 swxY w Y   |                     |          S )z*Get a session by ID (running or finished).N)rN   re   rG  rf   r   r  s      r    rG  zProcessRegistry.get  s    Z 	V 	Vm''
33Ut~7I7I*7U7UG	V 	V 	V 	V 	V 	V 	V 	V 	V 	V 	V 	V 	V 	V 	V--g666s   5A		AAr$   c                    ||j         rdS t          |dd          }|dS 	 |                                }n# t          $ r Y dS w xY w|dS d}t          |dd          }|at          sY	 ddl}|                                }|                    ||j                  }|                    ||j        |t          j
        z             	 |                                }	|	r.t          |	t                    r|	n|	                    dd          }n# t          t           t"          f$ r Y nw xY w	 |                    ||j        |           nB# t          $ r Y n6w xY w# 	 |                    ||j        |           w # t          $ r Y w w xY wxY wn8# t          $ r+}
t$                              d	|j        |
           Y d}
~
nd}
~
ww xY w|j        5  |rG|xj        |z  c_        t/          |j                  |j        k    r|j        |j         d         |_        d
|_         |j        dk    r||_        d|_        ddd           n# 1 swxY w Y   t$                              d|j        |           |                     |           dS )u$  Reconcile session.exited against the real child process state.

        The reader thread (`_reader_loop`) sets `session.exited = True` only
        in its `finally` block, which runs when `stdout.read()` returns EOF.
        If the direct `Popen` child has exited but a descendant process (e.g.
        a daemon spawned by `hermes update` restarting the gateway) is still
        holding the stdout pipe open, the reader blocks forever and poll()
        keeps returning "running" indefinitely (issue #17327 — 74 polls over
        7 minutes on Feishu).

        This helper closes that window: when `session.exited` is still False
        but the direct child's `Popen.poll()` reports an exit code, drain any
        readable bytes non-blocking and flip `session.exited`. The orphaned
        reader thread remains stuck on its blocking `read()` but is a daemon
        thread and will be reaped with the process.

        Safe no-op on sessions without a local `Popen` (env/PTY), already-
        exited sessions, and detached-recovered sessions.
        Nr+   r'   r  r   r  r  r[  z$Non-blocking drain failed for %s: %sTrW  r1   zxReconciled session %s: direct child exited with code %s but reader was still blocked (orphaned pipe). Flipped to exited.)r1   r   pollr   r   fcntlfilenoF_GETFLF_SETFLr   
O_NONBLOCKr]  r  rU   r\  BlockingIOErrorr   rg  r   r  r%   rN   r5   r   r6   r3   r2   r   r   )ru   r   r   rcdrainedr  r  fdflagsr   r9  s              r    _reconcile_local_exitz%ProcessRegistry._reconcile_local_exit  s7   ( ?gn?Fw	400<F	BB 	 	 	FF	:F x..kT]]__B66Bur}/DEEE
"KKMME o+5eS+A+A"n%%u||T[dm|GnGn'*=   DBu====$   Bu====$    T T TCWZQRSSSSSSSST ] 	5 	5 ^%%0%%w,--0HHH,3,A7C[B[B\B\,]G)!GN(H44$&!,4)	5 	5 	5 	5 	5 	5 	5 	5 	5 	5 	5 	5 	5 	5 	5 	DJ	
 	
 	

 	w'''''s   7 
AA+AF AD E D'$E &D''E +E F 
EF EF FE76F7
FFFFF 
G !F;;G 
A*I  IIc                 (   ddl m} |                     |          }|dd| dS |                     |           |j        5  |j        r ||j        dd                   nd}ddd           n# 1 swxY w Y   |j        |j        |j        rd	nd
|j	        t          t          j                    |j        z
            |d}|j        r8|j        |d<   |j        |d<   |j        |d<   | j                            |           |j        r
d|d<   d|d<   |S )z9Check status and get new output for a background process.r   rw  N	not_foundNo process with ID r   errorr'   r1   running)r   r&   r   r*   uptime_secondsoutput_previewr2   r3   r4   Tr7   z=Process recovered after restart -- output history unavailablenote)r{  rx  rG  r  rN   r5   r%   r&   r1   r*   r   r   r/   r2   r3   r4   rm   addr7   )ru   r   rx  r   r  rT  s         r    r  zProcessRegistry.poll  s   //////((:&&?)4V*4V4VWWW 	""7+++] 	h 	hJQJ_gZZ(=eff(EFFFegN	h 	h 	h 	h 	h 	h 	h 	h 	h 	h 	h 	h 	h 	h 	h "*").?hhi;!$)++0B"BCC,
 
 > 	0")"3F;*1*CF&'+2+EF'( ##J/// 	]!%F:\F6Ns   "A00A47A4r      offsetlimitc                    ddl m} |                     |          }|dd| dS |j        5   ||j                  }ddd           n# 1 swxY w Y   |                                }t          |          }|dk    r|dk    r|| d         }	n||||z            }	|j        |j        |j	        rdndd	
                    |	          |t          |	           d
d}
|j	        r| j                            |           |
S )z;Read the full output log with optional pagination by lines.r   rw  Nr  r  r  r1   r  rz   z lines)r   r&   r   r   total_linesshowing)r{  rx  rG  rN   r5   r   r   r%   r&   r1   r   rl   r  )ru   r   r  r  rx  r   full_outputr~   r  selectedrT  s              r    read_logzProcessRegistry.read_log  sw   //////((:&&?)4V*4V4VWWW] 	< 	<$*W%:;;K	< 	< 	< 	< 	< 	< 	< 	< 	< 	< 	< 	< 	< 	< 	< &&((%jj Q;;5199eVWW~HHVFUN23H "*").?hhiii))&h--///
 
 > 	6%))*555s   A

AAc           
         ddl m} ddlm} 	 t	          t          j        dd                    }n# t          t          f$ r d}Y nw xY w|}|}d}|r||k    r|}	d| d	| d
}n|p|}	| 	                    |          }
|
dd| dS t          j                    |	z   }t          j                    |k     r$|                     |
          }
|
dd| dS |                     |
           |
j        rV| j                            |           d|
j        |
j        |
j        |
j         ||
j        dd                   d}|r||d<   |S  |            r+d|
j         ||
j        dd                   dd}|r||d<   |S |t          j                    z
  }|dk    rnA|
j                            t1          d|                     t          j                    |k     $d|
j         ||
j        dd                   d}|r||d<   n	d|	 d|d<   |S )aY  
        Block until a process exits, timeout, or interrupt.

        Args:
            session_id: The process to wait for.
            timeout: Max seconds to block. Falls back to TERMINAL_TIMEOUT config.

        Returns:
            dict with status ("exited", "timeout", "interrupted", "not_found")
            and output snapshot.
        r   rw  )is_interruptedTERMINAL_TIMEOUT180   NzRequested wait of z%s was clamped to configured limit of r   r  r  r  r1   ry  )r   r&   r2   r3   r4   r   timeout_noteinterruptedr  z+User sent a new message -- wait interrupted)r   r&   r   r  g      ?r   r   )r   r&   r   zWaited zs, process still running)r{  rx  tools.interruptr  r   r   getenvrg  	TypeErrorrG  r   r   r   r  r1   rl   r  r&   r2   r3   r4   r5   rM   r3  min)ru   r   r   rx  _is_interrupteddefault_timeoutmax_timeoutrequested_timeoutr  effective_timeoutr   r   rT  	remainings                 r    r3  zProcessRegistry.wait/  s    	0/////EEEEEE	"!"),>"F"FGGOOI& 	" 	" 	"!OOO	"%# 	A!2[!@!@ +9%6 9 9*59 9 9 L
 !2 @[((:&&?)4V*4V4VWWW>##&77n))44W==G"-8Zj8Z8Z[[[ &&w///~ )--j999&&!(!2)0)B*1*D(j)>uvv)FGG    :-9F>*   	+&(j)>uvv)FGGI	    :-9F>* 4>#3#33IA~~%**3sI3F3F*GGGI n))N   j!6uvv!>??
 

  	[%1F>""%Z/@%Z%Z%ZF>"s   "1 AAzprocess.killsourcer  c                F   |                      |          }|dd| dS |j        r
d|j        dS 	 |j        rZ	 |j                            d           nH# t
          $ r/ |j        r$t          j        |j        t          j
                   Y nw xY w|j        r&|                     |j        j        |j                   n|j        r-|j        r&|j                            d	|j         d
d           n|j        r|j        dk    r|j        r|                     |j        |j                  sL|j        5  d|_        d|_        ddd           n# 1 swxY w Y   |                     |           d|j        dS |                     |j        |j                   ndddS d|_        d|_        d|_        ||_        |                     |           |                                  d|j        |j        |j        dS # t
          $ r}dt3          |          dcY d}~S d}~ww xY w)zKill a background process.Nr  r  r  already_exited)r   r2   T)forcezkill rc  r  r   r8   r  zkRecovered process cannot be killed after restart because its original runtime handle is no longer availablerW  )r   r   r3   r4   )rG  r1   r2   rP   r   r   r*   r   r   r   r   r+   r   r0   r,   rF  r7   r9   r   rN   r   r3   r4   r,  r%   rU   )ru   r   r  r   r9  s        r    kill_processzProcessRegistry.kill_process  s   ((:&&?)4V*4V4VWWW> 	*$.  3	8| $=L***6666  = = ={ =V^<<<=   (()<g>UVVVV W[ ''(I(I(I(IST'UUUU! g&76&A&Agk&A --gk7;RSS   1 1)-,0)1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 **7333"2%,%6   ((g6MNNNN &M   "GN #G(0G%)/G&""7+++""$$$"%j%,%>&-&@	    	8 	8 	8%A77777777	8sr   G: A G: 5BG: BB$G: 4EG: EG: E!G: 9%G: AG: :
H HH H datac                 .   |                      |          }|dd| dS |j        rdddS t          |d          r|j        r	 t          r:t          |t                    r|                    d          nt          |          }n,t          |t                    r|	                    d          n|}|j        
                    |           d	t          |          d
S # t          $ r}dt          |          dcY d}~S d}~ww xY w|j        r|j        j        sdddS 	 |j        j        
                    |           |j        j                                         d	t          |          d
S # t          $ r}dt          |          dcY d}~S d}~ww xY w)zASend raw data to a running process's stdin (no newline appended).Nr  r  r  r  Process has already finishedrP   r  ok)r   bytes_writtenr  ?Process stdin not available (non-local backend or stdin closed))rG  r1   rt  rP   r   r  bytesr\  rU   encodewriter   r   r+   r   flush)ru   r   r  r   pty_datar9  s         r    write_stdinzProcessRegistry.write_stdin  s   ((:&&?)4V*4V4VWWW> 	Y.9WXXX 7F## 
	< 
	<	< W7A$7N7N]t{{7333TWX\T]T]HH7A$7L7LVt{{7333RVH""8,,,"&TCCC < < <")CFF;;;;;;;;<  	sgo&; 	s%0qrrr	8O!''---O!'')))"SYY??? 	8 	8 	8%A77777777	8s>   BC 
D'C>8D>DAE. .
F8F	FFc                 4    |                      ||dz             S )zGSend data + newline to a running process's stdin (like pressing Enter).rz   )r  )ru   r   r  s      r    submit_stdinzProcessRegistry.submit_stdin  s    
D4K888r"   c                     | j         }|dddS |                     |          }	  |||           n)# t          $ r}dt          |          dcY d}~S d}~ww xY wd|ddS )uy  Ask the desktop GUI to close the read-only terminal tab mirroring this
        background process.

        This does NOT kill the process — it only drops the view. Output keeps
        streaming into the (capped) buffer and the user can reopen the tab from
        the status stack. Desktop-only: returns an error if no UI close sink is
        wired (e.g. CLI / messaging).Nr  z;close_terminal is only available in the Hermes desktop app.r  r  zClosed the read-only terminal tab. The process was not killed; its output remains available and the user can reopen the tab from the status stack.)r   closedr  )rt   rG  r   rU   )ru   r   r   r   r9  s        r    request_close_terminalz&ProcessRegistry.request_close_terminal  s     }<!V   ((:&&	8D*%%%% 	8 	8 	8%A77777777	8  )	
 
 	
s   2 
AAAAc                    |                      |          }|dd| dS |j        rdddS t          |d          rO|j        rH	 |j                                         dd	d
S # t
          $ r}dt          |          dcY d}~S d}~ww xY w|j        r|j        j        sdddS 	 |j        j        	                                 ddd
S # t
          $ r}dt          |          dcY d}~S d}~ww xY w)zGClose a running process's stdin / send EOF without killing the process.Nr  r  r  r  r  rP   r  zEOF sent)r   r   r  r  zstdin closed)
rG  r1   rt  rP   sendeofr   rU   r+   r   close)ru   r   r   r9  s       r    close_stdinzProcessRegistry.close_stdin
  sb   ((:&&?)4V*4V4VWWW> 	Y.9WXXX7F## 	< 	<<$$&&&"&:>>> < < <")CFF;;;;;;;;<  	sgo&; 	s%0qrrr	8O!'')))"~>>> 	8 	8 	8%A77777777	8s<   A" "
B,B=BB$"C 
C-C("C-(C-c                 N    	 t          | j                  S # t          $ r Y dS w xY w)ak  Return the count of currently-running background processes.

        Cheap O(1) read of the running dict, suitable for status-bar polling
        on every render tick. CPython dict ``len()`` is atomic; callers do not
        need to hold ``self._lock``. Reflects ``_running`` only: sessions are
        moved to ``_finished`` when their subprocess exits.
        r   )r   re   r   )ru   s    r    count_runningzProcessRegistry.count_running!  s9    	t}%%% 	 	 	11	s    
$$c                      j         5  t           j                                                  t           j                                                  z   }ddd           n# 1 swxY w Y    fd|D             }srfd|D             }g }|D ])}|j        |j        dd         |j        |j        t          j
        dt          j        |j                            t          t          j	                    |j        z
            |j        rdnd|j        r|j        dd         nd	d
}rr|j        k    r|j        k    rd|d<   |j        r,|j        s%t          |j                  |d<   |j        dk    |d<   |j        rd|d<   |j        r
|j        |d<   |j        rd|d<   |                    |           +|S )u  List all running and recently-finished processes.

        When ``task_id`` is given, processes for that task are included. When
        ``session_key`` is also given, session-scoped background processes
        (``background: true``) registered under that gateway session are
        surfaced too, even if they belong to a different task — so the agent
        can discover a forgotten preview server that is blocking session
        reset (#29177). Such cross-task entries are flagged with
        ``"session_scoped": true``.
        Nc                 :    g | ]}                     |          S ra   )r   )r|   r   ru   s     r    
<listcomp>z1ProcessRegistry.list_sessions.<locals>.<listcomp><  s'    PPPa66q99PPPr"   c                 H    g | ]}r|j         k    sr|j        k    |S ra   r(   r)   )r|   r   r)   r(   s     r    r  z1ProcessRegistry.list_sessions.<locals>.<listcomp>?  sM        !	W 4 4 !5$%M[$@$@ $@$@$@r"   r  z%Y-%m-%dT%H:%M:%Sr1   r  i8r'   )r   r&   r-   r*   r/   r  r   r  Tsession_scopedrC   r   	watch_hitrA   r2   r7   )rN   r\   re   valuesrf   r%   r&   r-   r*   r   strftime	localtimer/   r   r1   r5   r(   r)   rC   rH   rF   rA   r2   r7   r   )ru   r(   r)   all_sessionsrT  r   entrys   ```    r    list_sessionszProcessRegistry.list_sessions.  sm    Z 	X 	X 4 4 6 677$t~?T?T?V?V:W:WWL	X 	X 	X 	X 	X 	X 	X 	X 	X 	X 	X 	X 	X 	X 	X QPPP<PPP 	k 	    '  L  	! 	!Ad9TcT?uu"m,?PQP\A]A]^^"%dikkAL&@"A"A&'h=((I<=O"S!/$%%"8"8QS	 	E  /; /19+?+?AMU`D`D`*.&'  7(9 7*.q/?*@*@&'%&]Q%6k"# 3.2*+x 1%&[k"z )$(j!MM%    s   AA%%A),A)c                 h   | j         5  t          | j                                                  }ddd           n# 1 swxY w Y   |D ]}|                     |           | j         5  t          fd| j                                        D                       cddd           S # 1 swxY w Y   dS )z<Check if there are active (running) processes for a task_id.Nc              3   >   K   | ]}|j         k    o|j         V  d S r   r(   r1   r|   r   r(   s     r    r   z7ProcessRegistry.has_active_processes.<locals>.<genexpr>p  sG         	W$5QX     r"   rN   r\   re   r  r   r   )ru   r(   sessionsr   s    `  r    has_active_processesz$ProcessRegistry.has_active_processesg  sP   Z 	4 	4DM002233H	4 	4 	4 	4 	4 	4 	4 	4 	4 	4 	4 	4 	4 	4 	4   	4 	4G**73333Z 	 	    --//    	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	s!   '<A A (2B''B+.B+max_active_agec                    | j         5  t          | j                                                  }ddd           n# 1 swxY w Y   |D ]}|                     |           t          j                    | j         5  t          fd| j                                        D                       cddd           S # 1 swxY w Y   dS )u  Check if there are active processes for a gateway session key.

        When *max_active_age* is set (seconds), processes that started more
        than that many seconds ago are **ignored** — they are still running
        but are considered stale and must not block session idle / daily
        reset.  This prevents a forgotten ``http.server`` (or any long-lived
        preview process) from permanently freezing the session lifecycle.

        Args:
            session_key: Gateway session key to check.
            max_active_age: If set, ignore processes older than this many
                seconds.  ``None`` retains the legacy behaviour (any running
                process blocks).
        Nc              3   b   K   | ])}|j         k    o|j         od u p|j        z
  k     V  *d S r   )r)   r1   r/   )r|   r   r  r   r)   s     r    r   z9ProcessRegistry.has_active_for_session.<locals>.<genexpr>  sl          , VLV#t+Tal0Bn/T     r"   )rN   r\   re   r  r   r   r   )ru   r)   r  r  r   r   s    ``  @r    has_active_for_sessionz&ProcessRegistry.has_active_for_sessionu  sk   " Z 	4 	4DM002233H	4 	4 	4 	4 	4 	4 	4 	4 	4 	4 	4 	4 	4 	4 	4   	4 	4G**73333ikkZ 	 	       --//	    	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	s!   '>AA=4B>>CCc                 b   | j         5  t          | j                                                  }ddd           n# 1 swxY w Y   |D ]}|                     |           | j         5  t          d | j                                        D                       cddd           S # 1 swxY w Y   dS )a  Whether ANY background process is still running (across all sessions).

        Used by scale-to-zero idle detection (gateway/scale_to_zero): a gateway
        with a live background process (terminal background=true) is NOT idle and
        must not be suspended, or the process is lost. Refreshes detached
        sessions first so a finished-but-unreaped process reads as inactive.
        Nc              3   &   K   | ]}|j          V  d S r   )r1   )r|   r   s     r    r   z1ProcessRegistry.has_any_active.<locals>.<genexpr>  s&      DD18|DDDDDDr"   r  )ru   r  r   s      r    has_any_activezProcessRegistry.has_any_active  sL    Z 	4 	4DM002233H	4 	4 	4 	4 	4 	4 	4 	4 	4 	4 	4 	4 	4 	4 	4   	4 	4G**73333Z 	E 	EDDT]-A-A-C-CDDDDD	E 	E 	E 	E 	E 	E 	E 	E 	E 	E 	E 	E 	E 	E 	E 	E 	E 	Es   ';??'0B$$B(+B(c                    | j         5  fd| j                                        D             }ddd           n# 1 swxY w Y   d}|D ]:}|                     |j        d          }|                    d          dv r|dz  };|S )	zQKill all running processes, optionally filtered by task_id. Returns count killed.c                 <    g | ]}|j         k    |j        |S r   r  r  s     r    r  z,ProcessRegistry.kill_all.<locals>.<listcomp>  s;       OqyG';';QX'; ';';';r"   Nr   kill_allr  r   >   rW  r  r   )rN   re   r  r  r%   rG  )ru   r(   r   rW  r   rT  s    `    r    r  zProcessRegistry.kill_all  s    Z 	 	   =//11  G	 	 	 	 	 	 	 	 	 	 	 	 	 	 	  	 	G&&wz*&EEFzz(##'CCC!s   &;??c                     t          j                     fd j                                        D             }|D ]>} j        |=  j                            |            j                            |           ?t           j                  t           j                  z   }|t          k    r\ j        rUt           j         fd          } j        |=  j                            |            j                            |            j        
                                 j        
                                z  } j        |z
  }|r xj        |z  c_         j        |z
  }|r xj        |z  c_        dS dS )zGRemove oldest finished sessions if over MAX_PROCESSES. Must hold _lock.c                 @    g | ]\  }}|j         z
  t          k    |S ra   )r/   FINISHED_TTL_SECONDS)r|   sidr   r   s      r    r  z4ProcessRegistry._prune_if_needed.<locals>.<listcomp>  s:     
 
 
Cal"&::: :::r"   c                 (    j         |          j        S r   )rf   r/   )r  ru   s    r    <lambda>z2ProcessRegistry._prune_if_needed.<locals>.<lambda>  s    DN3<O<Z r"   keyN)r   rf   itemsrl   discardrm   r   re   MAX_PROCESSESr  keys)	ru   expiredr  total	oldest_idtrackedstalestale_pollsr   s	   `       @r    r+  z ProcessRegistry._prune_if_needed  s    ikk
 
 
 
"n2244
 
 
  	- 	-Cs#%--c222'',,,, DM""S%8%88M!!dn!DN0Z0Z0Z0Z[[[Iy)%--i888''	222 -$$&&)<)<)>)>>)G3 	/%%.%%)G3 	/;.	/ 	/r"   c                    	 | j         5  g }| j                                        D ]}|j        s|j        1|j        dk    r&|j        r|                     |j                  |_        |                    i d|j	        d|j
        d|j        d|j        d|j        d|j        d	|j        d
|j        d|j        d|j        d|j        d|j        d|j        d|j        d|j        d|j        d|j        d|j        i           	 ddd           n# 1 swxY w Y   ddlm}  |t4          |           dS # t6          $ r(}t8                              d|d           Y d}~dS d}~ww xY w)z=Write running process metadata to checkpoint file atomically.Nr8   r   r&   r*   r9   r0   r-   r/   r(   r)   r:   r;   r<   r=   r>   r?   r@   rA   rC   r   )atomic_json_writez#Failed to write checkpoint file: %sT)exc_info)rN   re   r  r1   r0   r9   r*   r   r   r%   r&   r-   r/   r(   r)   r:   r;   r<   r=   r>   r?   r@   rA   rC   utilsr  CHECKPOINT_PATHr   r   r  )ru   entriesr   r  r9  s        r    r,  z!ProcessRegistry._write_checkpoint  sl   #	R  --//  A8  ,49N9NSTSX9N040J0J150Q0QA- ((!$(%qy( "15( (	(
 .q/@( "15( )!,( &qy( *1=( /0B( .q/@( .q/@( 01D( 01D( 1!2F(  /0B!(" 1!2F#($ -a.>%( (                 > 0/////ow77777 	R 	R 	RLL>DLQQQQQQQQQ	Rs;   D> DDD> DD> !D"D> >
E0E++E0c                    t                                           sdS 	 t          j        t                               d                    }n# t
          $ r Y dS w xY wd}|D ]}|                    d          }|s|                    dd          }|dk    r:t                              d|                    dd	          d
d         ||           q|                    d          }| 	                    ||          sF| 
                    |          r0t                              d|                    dd          |           t          d%i d|d         d|                    dd	          d|                    dd          d|                    dd          d|d|d|d|                    d          d|                    dt          j                              ddd|                    dd          d|                    dd          d|                    dd          d|                    dd          d|                    dd          d|                    dd          d|                    dd          d|                    dd           d!|                    d!g           }| j        5  || j        |j        <   d
d
d
           n# 1 swxY w Y   |d"z  }t                              d#|j        d
d         |           |j        dk    rW| j                            |j        |j        |j        |j        |j        |j        |j        |j        |j        |j        d$
           |                                  |S )&z
        On gateway startup, probe PIDs from checkpoint file.

        Returns the number of processes recovered as detached.
        r   r  )r  r*   r9   r8   z=Skipping recovery for non-host process: %s (pid=%s, scope=%s)r&   unknownNr   r0   u   Not recovering session %s: pid %d is alive but its start time no longer matches — PID was recycled onto an unrelated process; refusing to adopt it.r   ?r%   r(   r'   r)   r-   r/   r7   Tr:   r;   r<   r=   r>   r?   r@   rA   FrC   r   z'Recovered detached process: %s (pid=%d))
r   check_intervalr)   r   r   r   r   r   r   rA   ra   )r  existsjsonloads	read_textr   rG  r   r   r   r   r$   r   rN   re   r%   r&   r@   rg   r   r)   r:   r;   r<   r=   r>   r?   rA   r,  )ru   r  	recoveredr  r*   r9   recorded_startr   s           r    recover_from_checkpointz'ProcessRegistry.recover_from_checkpoint  sp    %%'' 	1	j!:!:G!:!L!LMMGG 	 	 	11	 	 J	 J	E))E""C 		+v66IF"" SIIi33CRC8	    #YY'899N))#~>> **3// KKF 		,44c	   $   &&		)Y777 		)R000 "IImR888	
 C !/ $) IIe$$$ !99\49;;???  "'+=r!B!B!B !&		*;R @ @ @ !&		*;R @ @ @ #()),?"D"D"D #()),?"D"D"D  $)99-A2#F#F#F!" "'+=q!A!A!A#$ $)99-A5#I#I#I%&  %yy)92>>>'G*  4 4,3gj)4 4 4 4 4 4 4 4 4 4 4 4 4 4 4NIKKA7?SVTVSVCWY\]]] '!++%,,")*&-&>#*#6 ' 8&6&6!(!:!(!:")"<*1*D. .    	   s#   -A 
AA:KK	K	r   )Nr'   r'   NF)Nr'   r'   r   )r   r  )r   r$   r   N)r   r  )r'   )NN):rQ   rR   rS   rT   r   rw   staticmethodrU   r   r$   r   r   rY   rZ   r   r   r   r   r   classmethodr   r   r   r   r   r
   r  dictr=  rU  r0  rJ  r)  r   r  r  r  r  rG  r  r  r  r3  r  r  r  r  r  r  r\   r  r  r  r  r  r+  r,  r   ra   r"   r    rc   rc      sn        / / /b           \ 	N 	3 	4 	 	 	 	~^ ~s ~t ~ ~ ~ ~@Uu U U U U Un    $       \  8C= Xc]    \ @HSM @8C= @UY @ @ @ [@(.1I hWeNf    , T    \     \" } }c }8C= }TX } } } [}B 
3 
3 
 
 
 \
 I II I 	I
 I I I 
I I I I^ b bb b 	b
 b b b 
b b b bL1,N 1, 1, 1, 1,f8%8,/8;>8JM8Z]8 8 8 8t (  (  (  (  (D    @7 7 7 7 7 7"S "T " " " "H\S \T \ \ \ \   *7c 7h~&> 7 7 7 7H( H( H( H(T)s )t ) ) ) )V 3   d    @U Us US UD U U U Un >L @8 @8 @8s @8s @8PT @8 @8 @8 @8D8c 8 8 8 8 8 8>9 9s 9# 9t 9 9 9 9
 
 
 
 
 
>8c 8d 8 8 8 8.s    5 5S 5c 5T 5 5 5 5rC D     CG 08	   @E E E E E"  s    "/ / /F%R %R %RN] ] ] ] ] ] ]r"   rc   c                 *   	 t          t          d|                     }n# t          t          f$ r Y dS w xY w|dk     r| dS t	          |d          \  }}|dk     r|dk    r| dn| d| dS t	          |d          \  }}|dk    r| dn| d| dS )z5Human-friendly elapsed string ('18m', '2h3m', '45s').r   r  r   r   r   h)r   r   r  rg  r   )r   r   r   r%  s       r    _format_ager&  e  s    Aw  z"   ss2vvwww!R==DAq2vvq&&!wwwwkkQkkk1!R==DAq1ffa7777Q+++++-s     55r  c           	         ddl }|                     dd          }|                     dd          pd}|                     d          }|                     d          }|                     d	          pd
}|                     d          pd}|                     d          pd}|                     d          }	|                     d          }
|                     dd          }|                     dd          }|                     d          }|                     d          p|                                 }|                     d          }|                     d          st          |t                    r^|pg }|                     d          pg }|rt	          |          nt	          |          }|                     d|          }d| dd| ddg}t          |t
          t          f          rY|                    d|                    |                    }dt          ||z
             d}|
                    d | |            |r|
                    d!|            |r+|
                    d"d#                    |                      |
                    d$| d%| d&| d'           |
rD|sB|
                    d(           |
                    d)|
            d*                    |          S t          |d+ ,          D ]}|                    d-d          }|                    dd          }|                    d          }|                    d          }|t	          |          k     r||         n|                    dd          }|d.v rd/nd0}|
                    d           d1| d2|d3z    d4| }|r|d5| z  }|d6| z  }|                    d          r|d7|d          z  }|                    d          |d#|d          d'z  }|d8z  }|
                    |           |d.v r|r|
                    |           E|rJ|r|
                    d9| d5| d:           |
                    d;           |
                    |           |
                    d<| |rd5| ndz   d:z              d*                    |          S d}t          |t
          t          f          rdt          ||z
             d}d=| dd>dg}t          |t
          t          f          rC|                    d|                    |                    }|
                    d | |            |
                    d?|            |r|
                    d!|            |r+|
                    d"d#                    |                      |
                    d$| d%|            |
                    d@| dA| dB| d'           |
                    dC           |d.v r|	r|
                    |	           n|dDk    rL|
                    dE|
rd5|
 ndFz              |	r*|
                    d;           |
                    |	           nO|
                    dG| dH|
rd*|
 ndz              |	r*|
                    d;           |
                    |	           d*                    |          S )Iu  Format an async-delegation completion into a self-contained re-injection.

    Carries the FULL original task source (goal, the context the parent
    supplied, toolsets, role, model) plus dispatch time, status, and the
    complete result summary. When this re-enters the conversation the agent
    may be deep in unrelated context and won't remember why the subagent
    existed, so the block is written to stand entirely on its own — enough to
    use the result OR re-dispatch if the world has moved on.
    r   Ndelegation_idr  goalr'   contexttoolsetsroleleafmodelr  r   	completedsummaryr  	api_callsduration_secondsdispatched_atcompleted_atr  is_batchgoalstotal_duration_secondsu%   [ASYNC DELEGATION BATCH COMPLETE — ]zA background fan-out of u    subagent(s) you dispatched earlier has finished. All ran in parallel and waited on each other; their consolidated results are below. You may have moved on since dispatching — act on these or re-dispatch if things have changed.z%Y-%m-%d %H:%M:%Sz (z ago)zDispatched: zContext you provided: z
Toolsets: z, zRole: z
   Model: z   Total duration: r   z--- ERROR ---z)The batch did not complete successfully: rz   c                 .    |                      dd          S )N
task_indexr   )rG  )xs    r    r  z*_format_async_delegation.<locals>.<lambda>  s    quu\1/E/E r"   r  r:  )r/  successu   ✓u   ✗z--- z TASK r   r   z: z
  (status=z, api_calls=z) ---()zPartial output:u   (no summary — status=u   [ASYNC DELEGATION COMPLETE — zA background subagent you dispatched earlier has finished. You may have moved on since dispatching it; the full task source is below so you can act on the result or re-dispatch if things have changed.zOriginal goal: zStatus: z   API calls: z   Duration: z--- RESULT ---r  z.The subagent was interrupted before completing.z3The subagent did not complete successfully (status=z).)r   rG  r  r\   r   r   rY   r  r  r&  r   r   sorted)r  _timedeleg_idr)  r*  r+  r,  r.  r   r0  r  r1  durationr3  r4  batch_resultsr  r6  n	total_durr~   tsageridxr_status	r_summaryr_errorr_goaliconheaders                                  r    _format_async_delegationrQ  t  s    ww	22H7762$"Dggi  Gwwz""H776??$fDGGG#EWWX-+Fggi  GGGGEQ''Iww)3//HGGO,,M77>**:ejjllL GGI&&M
wwz 9 j== 9 %2  &B#3CLLLUGG4h??	?H???Rq R R R 
 mc5\22 	3 3U__]5S5STTBG{<-#?@@GGGCLL11C11222 	=LL;';;<<< 	=LL;dii&9&9;;<<<TdTTeTT	TTTUUU 	$ 	$LL)))LLLULLMMM99U###%E%EFFF 	 	A%%a((CuuXs++Hi((IeeGnnG#&U#3#3U3ZZvr9J9JF$(@@@55eDLL5D55a55!55F (-v--'-8---Fuu[!! :9;999uu'((47q!347777gFLL   333	3Y'''' 
 =LL!;X!;!;!;!;!;<<<.///Y''''8h88)08~G~~~b:   
 yy
C-#u.. DC;|m;<<CCC 	6(555	K 	E -#u.. /^^/1O1OPP-B---...	LL)4))*** 97g77888 97$))H"5"577888	LL1$11%11222	LLUFUU)UU(UUUVVV	LL!""")))g)W	=	 	 <$-|E|||#/	
 	
 	
  	"LL*+++LL!!! 	L&LLL$,|E|||".	
 	
 	
  	"LL*+++LL!!!99Ur"   z
str | Nonec                    |                      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t          |           S |                      dd          }|                      dd	          }|                      d          pd}	|                      d          pd	}
d	}|dv rd}|	dk    rd|
pd  }n|	d!k    rd"}n|	d#k    rd$}n|dk    rd%}nd}d| d&| d'| | d(| d)| d
S )*zFormat a process notification event into a [IMPORTANT: ...] message.

    Handles completion events (notify_on_complete), watch pattern matches,
    and watch disabled events from the unified completion_queue.
    r   rz  r   r  r&   r   z[IMPORTANT: r   r'   r8  r   r   r  r   r   r   z[IMPORTANT: Background process z matched watch pattern "z".
Command: z
Matched output:
z
(z/ earlier matches were suppressed by rate limit)async_delegationr2   r3   r1   r4   >   -15143   r  z	, SIGTERMrW  zterminated by Hermesre  z3marked lost because the process backend disappearedrC  zfailed to startzcompleted normally z (exit code z).
Command: z	
Output:
)rG  rQ  )r  evt_type_sid_cmd_pat_out_suprx   _exit_reason_source_signal_statuss                r    r  r    sN    wwv|,,H77<++D779i((D###7cggi447777=  wwy#&&wwx$$ww|Q'''d ' '#' '' ' !%' ' 	  	PO$OOOOD%%%',,,GGK%%E778R  Dgg)**6hGgg*++1rGG((((87#6h88	F		G	N	"	"#	!&	$ 	 	 	 		$	 		 	 	 	 	r"   )registry
tool_errorr+   af  Manage background processes started with terminal(background=true). Actions: 'list' (show all), 'poll' (check status + new output), 'log' (full output with pagination), 'wait' (block until done or timeout), 'kill' (terminate), 'write' (send raw stdin data without newline), 'submit' (send data + Enter, for answering prompts), 'close' (close stdin/send EOF).objectstring)r\   r  logr3  r   r  submitr  z)Action to perform on background processes)r   enumdescriptionz]Process session ID (from terminal background output). Required for all actions except 'list'.)r   rk  z@Text to send to process stdin (for 'write' and 'submit' actions)integerzJMax seconds to block for 'wait' action. Returns partial output on timeout.r   )r   rk  minimumz6Line offset for 'log' action (default: last 200 lines)z$Max lines to return for 'log' action)actionr   r  r   r  r  rn  )r   
propertiesrequired)r  rk  
parametersrT  c                 ~   t          | t                    s| S ddlm}m} |                     d          pd}dD ]=}|                     |          }t          |t                    r|r |||          | |<   >t          |                     d          t                    r| d         r || d         d          | d<   | S )uD  Redact secrets from background-process output before it reaches the
    model, session.db, and CLI display.

    Mirrors the foreground ``terminal`` redaction (terminal_tool.py) so the
    two surfaces can't diverge — issue #43025 (background output was returned
    verbatim). Respects ``security.redact_secrets`` (no force): output fields
    pass through ``redact_terminal_output`` which picks ``code_file`` based on
    the recorded command (env dumps get the ENV-assignment pass). The command
    string itself is also redacted in case it carried an inline credential.
    r   )redact_sensitive_textredact_terminal_outputr&   r'   )r   r  T)	code_file)r  r#  agent.redactrs  rt  rG  rU   )rT  rs  rt  r&   r	   values         r    _redact_process_resultrx  d  s     fd## JJJJJJJJjj##)rG- C C

5!!eS!! 	Ce 	C225'BBF5M&**Y''-- U&2C U11&2CtTTTyMr"   c                    |                     d          }|                      dd          }|                      d          #t          |                      dd                    nd}|dk    r\	 ddlm}  |d          pd}n# t          $ r d}Y nw xY wt          j        d	t                              ||pd 
          id          S |dv r+|st          d|           S |dk    r;t          j        t          t                              |                    d          S |dk    rft          j        t          t                              ||                      dd          |                      dd                              d          S |dk    rPt          j        t          t                              ||                      d                              d          S |dk    r.t          j        t                              |          d          S |dk    rPt          j        t                              |t          |                      dd                              d          S |dk    rPt          j        t                              |t          |                      dd                              d          S |dk    r.t          j        t                              |          d          S t          d| d          S )Nr(   rn  r'   r   r\   r   )get_current_session_key)rD   	processesr  F)ensure_ascii>   rh  r   r  r3  r  r  ri  zsession_id is required for r  rh  r  r  r  )r  r  r3  r   r   r   r  r  ri  r  zUnknown process action: z8. Use: list, poll, log, wait, kill, write, submit, close)rG  rU   tools.approvalrz  r   r  dumpsprocess_registryr  re  rx  r  r  r3  r  r  r  r  )r  kwr(   rn  r   rz  r)   s          r    _handle_processr  }  sA   ffYGXXh##F48HH\4J4J4VTXXlB//000\^J	>>>>>>11"===CKK 	 	 	KKK	z*88VaViei8jjk
 
 
 	
 
N	N	N 	FDFDDEEEV:45E5J5J:5V5VWWfkllllu__:45E5N5N488Ha#8#8RU@V@V 6O 6X 6X Y Ygln n n nv:45E5J5J:_c_g_ghq_r_r5J5s5stt  DI  J  J  J  Jv:.;;JGGV[\\\\w:.:::s488TZ\^K_K_G`G`aapuvvvvx:.;;JDHHU[]_L`L`HaHabbqvwwwww:.:::FFUZ[[[[qqqqrrrs   -B BBr   u   ⚙️)r  toolsetschemahandleremoji)<rT   r  loggingr   r   rD  r   rW   r]   r   r!  systemr   tools.environments.localr   r   r   hermes_cli._subprocess_compatr   dataclassesr   r	   typingr
   r   r   r   r   r   	getLoggerrQ   r   r  r[   r   r  MAX_ACTIVE_PROCESS_AGEr   r   r   r   r   r   rU   r!   r$   rc   r  rY   r&  r#  rQ  r  tools.registryrd  re  PROCESS_SCHEMArx  r  registerra   r"   r    <module>r     s   >   				             ho9, ] ] ] ] ] ] ] ] ] ] < < < < < < ( ( ( ( ( ( ( ( , , , , , , , , , , , , - - - - - -		8	$	$ "/##&66         !    "       00 00 00 00 00 00 00 00fP P P P P P P Ph6 #?$$ . .3 . . . .C$ C3 C C C CL5T 5l 5 5 5 5v 0 / / / / / / / 	_  ![[[J  !~ 
 !a 
 "k  "W 
 "E /
 
: J?   * *Z4 D    2%s %s %sP  	
     r"   