
    sj                       U 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ddlZddlZddlZddlmZ ddlmZmZmZmZ ddlmZ  ej        e          ZdedefdZdd	lmZmZ dd
l m!Z! ddl"m#Z# ddl$m%Z% ddl&m'Z'm(Z(m)Z)m*Z*m+Z+ dededefdZ, e,dde-d          Z. e,dde/d          Z0dZ1dZ2dede3fdZ4de5eef         de3fdZ6ddd Z7e5e8d!<   d"Z9d# Z:i Z;e5eef         e8d$<    ej<                    Z= ej>                    Z?d% Z@d& ZAd' ZBd( ZCdefd)ZDdefd*ZEd+eddfd,ZFdd-ZGdd.lHmIZJ d/ede3fd0ZKdeeef         de3fd1ZL	 dd2ed3ed4e3de5fd5ZM eNd6          ZOd7ede3fd8ZPd9ededz  fd:ZQd;ed3edefd<ZRd=ZSd;ede3fd>ZTd2edz  d;ede3fd?ZUddAe-defdBZVdd2edDe-defdEZWdFede3fdGZXd2edHe-deYee-f         fdIZZd2edeYee-f         fdJZ[d2ede-fdKZ\de3fdLZ]d2edefdMZ^d2edz  deYedz  edz  f         fdNZ_ddOl`maZa ddPlbmcZd ddQl$meZf ddRlgmhZi ddSljmkZl ddTlmmnZo ddUlpmqZr ddVlsmtZt ddluZudWZvi Zweeef         e8dX<   i Zxeee/f         e8dY<    ej<                    Zyi Zzeeej<        f         e8dZ<    ej<                    Z{da|da}da~ ej<                    Zd[eeef         ddfd\Zi Zeeeeef         f         e8d]<   i Zeeef         e8d^<    ej<                    Zd_ee         d`ee         ddfdaZd_ee         dee         fdbZd_eddfdcZddedeeeef         fdfZddefdgZi Zeeef         e8dh<    ej<                    Zdiedjee         ddfdkZddedefdlZde3fdmZ eNh dn          Zddee         de3fdoZddee         defdpZddee         deeef         fdqZdeeef         ddee         dee         fdrZe-dfdededsedefdtZdefduZdvZ eNh dw          Zd`ede3fdxZdaddyZdeeef         fdzZd{edz  deeef         fd|Zdeeef         de5fd}Zdeeef         de5fd~Z	 	 	 	 dd3eded`ede-de5d[e5de5ddedee         fdZdde-fdZd Zd Zd ZddefdZdddee         fdZddede3fdZd Zddddede3fdZd Z ej        e           ddddddddddddZe5e-ef         e8d<   de-dedz  fdZd2ede-dedz  fdZd2ede3fdZ ej        dej        ej        z            Z ej        d          Z ej        d          Zd2edefdZ ej        dej                   ej        dej                   ej        dej                   ej        dej                   ej        dej                   ej        dej                   ej        dej                   ej        dej                  fZd2ede3fdZd2ededz  fdZde3de3deYfdZdddd9ee         ded_ee         d3ee         def
dZ	 	 	 	 	 	 	 	 	 dd2ede3dee-         ddee         dee         de3d9ee         de3de3deee                  defdZddee         ddfdZde3fdZedk    r\ ed            ed            e            Z ed¦            eded3                      eded                      eded                      eded`                      eded          dʝ            eded          dʝ            e            s ed̦            euj        dͦ            edΦ            edϦ            edЦ            edѦ            edҦ            edӦ            edԦ            edզ            ed֦            edצ           dZ ed ej        ddۦ           dܝ            ed ej        de                       ed ej        dde                        ed ej        de                       ed ej        de                       ed ej        d e                                  ddlmZ  ed ej        d eŦ             d                       ed ej        dd                       ed ej        dd                      ddl mZ devdddddddddde. de. dddddddd dddddddddidddd2gddZǐd	 Z ej        ddeeed
d           dS (  a  
Terminal Tool Module

A terminal tool that executes commands in local, Docker, Modal, SSH,
Singularity, Daytona, and Vercel Sandbox environments. Supports local
execution, containerized backends, and cloud sandboxes, including managed
Modal mode.

Environment Selection (via TERMINAL_ENV environment variable):
- "local": Execute directly on the host machine (default, fastest)
- "docker": Execute in Docker containers (isolated, requires Docker)
- "modal": Execute in Modal cloud sandboxes (direct Modal or managed gateway)
- "vercel_sandbox": Execute in Vercel Sandbox cloud sandboxes

Features:
- Multiple execution backends (local, docker, modal, vercel_sandbox)
- Background task support
- VM/container lifecycle management
- Automatic cleanup after inactivity

Cloud sandbox note:
- Persistent filesystems preserve working state across sandbox recreation
- Persistent filesystems do NOT guarantee the same live sandbox or long-running processes survive cleanup, idle reaping, or Hermes exit

Usage:
    from terminal_tool import terminal_tool

    # Execute a simple command
    result = terminal_tool("ls -la")

    # Execute in background
    result = terminal_tool("python server.py", background=True)
    N)Path)OptionalDictAnyList)env_var_enabledvaluereturnc                 J    ddl m}  || dnt          |           d          S )z?Force-redact text before serializing a terminal error envelope.r   )redact_sensitive_textN T)force)agent.redactr   str)r	   r   s     7/home/agent/.hermes/hermes-agent/tools/terminal_tool.py_redact_terminal_error_textr   9   s8    222222  u}#e**DQQQQ    )is_interrupted_interrupt_event)
tool_error)strip_inert_heredoc_bodies)_get_scratch_dir)coerce_modal_modehas_direct_modal_credentialsmanaged_nous_tools_enabled%nous_tool_gateway_unavailable_messageresolve_modal_backend_statenamedefault
type_labelc                     t          j        |           }||dk    r|S 	  ||          S # t          t          f$ r# t                              d| |||           |cY S w xY w)zParse module-level numeric env vars without breaking import.

    Terminal tool is imported by CLI, ACP, tests, and tool discovery. A single
    malformed env var must not make the whole module unloadable at import time.
    Nr   z;Invalid value for %s: %r (expected %s). Falling back to %r.)osgetenv	TypeError
ValueErrorloggerwarningr   r   	converterr    raws        r   _safe_parse_import_envr+   \   s     )D//C
{cRii
y~~z"   I	
 	
 	
 s   
+ 1AATERMINAL_MAX_FOREGROUND_TIMEOUTiX  integerTERMINAL_DISK_WARNING_GBg     @@numberz/vercel/sandbox)node24node22z
python3.13runtimec                     |  p| t           v S N)_SUPPORTED_VERCEL_RUNTIMES)r2   s    r   _is_supported_vercel_runtimer6      s    ;?'%???r   configc                 &   |                      d          pd                                }t          |          s8d                    t                    }t
                              d||           dS |                      dd          }|dvrt
                              d	|           dS t          j        	                    d
          t
                              d           dS ddl
m} t           |d                    }t           |d                    }t           |d                    }t           |d                    }|rdS |s|s|r$|r|r|rdS t
                              d           dS t
                              d           dS )z6Validate Vercel Sandbox terminal backend requirements.vercel_runtimer   z, zVVercel Sandbox runtime %r is not supported. Set TERMINAL_VERCEL_RUNTIME to one of: %s.Fcontainer_disk   >   r   r;   zmVercel Sandbox does not support custom TERMINAL_CONTAINER_DISK=%s. Use the default shared setting (51200 MB).vercelNzNvercel is required for the Vercel Sandbox terminal backend: pip install vercelr   
get_secretVERCEL_OIDC_TOKENVERCEL_TOKENVERCEL_PROJECT_IDVERCEL_TEAM_IDTzVercel Sandbox backend selected with token auth, but VERCEL_TOKEN, VERCEL_PROJECT_ID, and VERCEL_TEAM_ID must all be set together. VERCEL_OIDC_TOKEN is supported for one-off local development only.zVercel Sandbox backend selected but no supported auth configuration was found. Set VERCEL_TOKEN, VERCEL_PROJECT_ID, and VERCEL_TEAM_ID for normal use. VERCEL_OIDC_TOKEN is supported for one-off local development only.)getstripr6   joinr5   r&   error	importlibutil	find_specagent.secret_scoper>   bool)	r7   r2   	supporteddiskr>   has_oidc	has_tokenhas_projecthas_teams	            r   "_check_vercel_sandbox_requirementsrR      s   zz*++1r88::G'00 II899	9		
 	
 	
 u::&..D:9	
 	
 	

 u~))1\	
 	
 	
 u------JJ23344HZZ//00Izz"56677KJJ/0011H t 	K 	8 	 	 	 	4&	
 	
 	
 u
LL	   5r   g        F)	timestampresult_disk_usage_cacheg     r@c                  ,   ddl } |                                 }|t          d         z
  t          k     rt          d         S 	 t	                      }d}ddl}|                    t          |dz                      D ]}t          |                              d          D ]g}|	                                rQ	 ||
                                j        z  }4# t          $ r&}t                              d||           Y d}~_d}~ww xY wh|dz  }|t          k    }	|	r!t                              d	|t                     |                                 t          d<   |	t          d<   |	S # t"          $ r(}t                              d
|d           Y d}~dS d}~ww xY w)a   Check if total disk usage exceeds warning threshold.

    Result is cached for :data:`_DISK_USAGE_CACHE_TTL` seconds (default:
    5 minutes) to avoid an expensive recursive filesystem scan on every
    terminal command.  The check is advisory-only so a stale result is
    harmless.
    r   NrS   rT   hermes-**zCould not stat file %s: %si   @z\Disk usage (%.1fGB) exceeds threshold (%.0fGB). Consider running cleanup_all_environments().z#Disk usage warning check failed: %sTexc_infoF)time	monotonicrU   _DISK_USAGE_CACHE_TTLr   globr   r   rglobis_filestatst_sizeOSErrorr&   debugDISK_USAGE_WARNING_THRESHOLD_GBr'   	Exception)
	_time_modnowscratch_dirtotal_bytesr^   pathfetotal_gbexceededs
             r   _check_disk_usage_warningrp      s    




C
{++.CCC **&(( IIc+
":;;<< 	I 	ID$ZZ%%c** I I99;; II#qvvxx'77" I I I%A1aHHHHHHHHIII ),== 	FNNy#%DF F F)2)<)<)>)>+&&.(#   :AMMMuuuuusD    A3E! 4CE! 
DC<7E! <DAE! !
F+FF_sudo_password_cachec                  .    t          t          dd           S )Nsudo_passwordgetattr_callback_tls r   r   _get_sudo_password_callbackrx     s    =/4888r   c                  .    t          t          dd           S )Napprovalrt   rw   r   r   _get_approval_callbackr{     s    =*d333r   c                     | t           _        dS )u   Register a callback for sudo password prompts (used by CLI).

    Per-thread scope — ACP sessions that run concurrently in a
    ThreadPoolExecutor each have their own callback slot.
    N)rv   rs   cbs    r   set_sudo_password_callbackr     s     #%Mr   c                     | t           _        dS )u   Register a callback for dangerous command approval prompts.

    Per-thread scope — ACP sessions that run concurrently in a
    ThreadPoolExecutor each have their own callback slot. See
    GHSA-qg5c-hvr5-hjgr.
    N)rv   rz   r}   s    r   set_approval_callbackr      s      Mr   c                     	 ddl m}   | dd          }n%# t          $ r t          j        dd          }Y nw xY w|rd| S t                      }|Zt          |dd          }t          |dd          }|$|"d	t          |           d
t          |           S dt          |           S dt          j	                     S )z6Return the cache scope for interactive sudo passwords.r   )get_session_envHERMES_SESSION_KEYr   zsession:N__self____func__zcallback-owner::z	callback:zthread:)
gateway.session_contextr   rf   r"   r#   rx   ru   id	threading	get_ident)r   session_keycallbackownerfuncs        r   _get_sudo_password_cache_scoper   *  s    :;;;;;;%o&:B?? : : :i 4b99: ('+'''*,,H*d33xT22!1;RYY;;D;;;)2h<<))),Y(**,,,s    77c                      t                      } t          5  t                              | d          cddd           S # 1 swxY w Y   dS )z6Return the cached sudo password for the current scope.r   N)r   _sudo_password_cache_lockrq   rC   )scopes    r   _get_cached_sudo_passwordr   @  s    *,,E	" 3 3#''r223 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3s   >AApasswordc                     t                      }t          5  | r| t          |<   nt                              |d           ddd           dS # 1 swxY w Y   dS )z.Persist a sudo password for the current scope.N)r   r   rq   pop)r   r   s     r   _set_cached_sudo_passwordr   G  s    *,,E	" 2 2 	2*2 '' $$UD111	2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2s   )AAAc                  x    t           5  t                                           ddd           dS # 1 swxY w Y   dS )z`Clear all cached sudo passwords.

    Internal helper for tests and process teardown paths.
    N)r   rq   clearrw   r   r   _reset_cached_sudo_passwordsr   Q  s    
 
# % %""$$$% % % % % % % % % % % % % % % % % %s   /33)check_all_command_guardsvolume_specc                     t          | t                    sdS |                                 }t          |          o=|                    d          p(t          |          dk    o|d         dk    o	|d         dv S )z>Return True when a docker volume spec bind-mounts a host path.F)/~z./z../      r      )r   \)
isinstancer   rD   rK   
startswithlen)r   vols     r   _docker_volume_uses_host_pathr   c  s{    k3'' u




C99 .// 	D	SQ	B3q6S=	BSV{-Br   c                     |                      d          dk    rdS |                      d          r|                      d          rdS t          d |                      dg           D                       S )	zIReturn True when a Docker sandbox exposes host paths through bind mounts.env_typedockerFhost_cwddocker_mount_cwd_to_workspaceTc              3   4   K   | ]}t          |          V  d S r4   )r   ).0r   s     r   	<genexpr>z*_docker_has_host_access.<locals>.<genexpr>u  s+      ^^c,S11^^^^^^r   docker_volumes)rC   anyr7   s    r   _docker_has_host_accessr   o  sx    zz*))uzz* &**-L"M"M t^^VZZHXZ\=]=]^^^^^^r   commandr   has_host_accessc                 @    t          | |t                      |          S )zJDelegate to consolidated guard (tirith + dangerous cmd) with CLI callback.)approval_callbackr   )_check_all_guards_implr{   )r   r   r   s      r   _check_all_guardsr   x  s/     "'84J4L4L2AC C C Cr   z/\:_-.~ +@=,chc                     | sdS t          |           dk     st          |           dk    rdS |                                 p| t          v S )NF       )ordisalnum_WORKDIR_SAFE_ASCII_CHARS)r   s    r   _is_safe_workdir_charr     sL     u 2ww||s2ww#~~u::<<:2!:::r   workdirc                 `    | sdS | D ]&}t          |          sdt          |           dc S 'dS )zReject workdir values that don't look like a filesystem path.

    Uses an allowlist of safe characters rather than a deny-list, so novel
    shell metacharacters can't slip through.

    Returns None if safe, or an error message string if dangerous.
    Nz/Blocked: workdir contains disallowed character z<. Use a simple filesystem path without shell metacharacters.)r   repr)r   r   s     r   _validate_workdirr     sk      t  $R(( 	M$r(( M M M  	
 4r   outputc                 x    t          d          }|s| S g d}|D ]}|| v rddlm} | d |             dz   c S  | S )z
    Check for sudo failure and add helpful message for messaging contexts.
    
    Returns enhanced output if sudo failed in messaging context, else original.
    HERMES_GATEWAY_SESSION)zsudo: a password is requiredzsudo: no tty presentzsudo: a terminal is requiredr   display_hermes_homeu@   

💡 Tip: To enable sudo over messaging, add SUDO_PASSWORD to z/.env on the agent machine.)r   hermes_constantsr   )r   r   
is_gatewaysudo_failuresfailure_dhhs         r   _handle_sudo_failurer     s     !!9::J   M ! E EfDDDDDD  Eaeaeagag  E  E  E  E  E  E  E  Mr   )zsudo: authentication failedz sudo: incorrect password attemptz1sudo: maximum 3 incorrect authentication attemptsz#sudo: 3 incorrect password attemptsc                 t    | sdS |                                  t          fdt          D                       S )z0Return True when sudo rejected a piped password.Fc              3       K   | ]}|v V  	d S r4   rw   )r   markerlowereds     r   r   z/_sudo_wrong_password_failure.<locals>.<genexpr>  s(      LLVv LLLLLLr   )lowerr   _SUDO_WRONG_PASSWORD_MARKERS)r   r   s    @r   _sudo_wrong_password_failurer     sA     ullnnGLLLL/KLLLLLLr   c                     dt           j        v rdS t          |          sdS t          | pd          dk    rdS t	                      sdS t          d           dS )u   Drop a session-cached sudo password after sudo rejects it.

    Env-configured ``SUDO_PASSWORD`` is left alone — that is an explicit
    operator choice, not an interactive cache entry.
    SUDO_PASSWORDFr   r   T)r"   environr   _count_real_sudo_invocationsr   r   )r   r   s     r   '_invalidate_cached_sudo_on_auth_failurer     sm     "*$$u'// u#GMr22a77u$&& ub!!!4r   -   timeout_secondsc                 F   ddl }t                      }|	  |            pdS # t          $ r Y dS w xY wdddfd}	 dt          j        d<   t          j        d	           t                       t          d
           t          d           t          d           t          d           t          d           t          d|  ddz   dz              t          d           t                       t          ddd           t          j	        |d          }|
                                 |                    |            d         r~d         pd}t                       |rt          d           nt          d           t                       |j                                         |dt          j        v rt          j        d= S S t          d           t          d           t                       |j                                         	 dt          j        v rt          j        d= dS dS # t          t          f$ re t                       t          d           t                       |j                                         Y dt          j        v rt          j        d= dS dS t          $ rT}t          d | d!           |j                                         Y d}~dt          j        v rt          j        d= dS dS d}~ww xY w# dt          j        v rt          j        d= w xY w)"a  
    Prompt user for sudo password with timeout.
    
    Returns the password if entered, or empty string if:
    - User presses Enter without input (skip)
    - Timeout expires (45s default)
    - Any error occurs
    
    Only works in interactive mode (HERMES_INTERACTIVE=1).
    If a _sudo_password_callback is registered (by the CLI), delegates to it
    so the prompt integrates with prompt_toolkit's UI.  Otherwise reads
    directly from /dev/tty with echo disabled.
    r   Nr   F)r   donec                     d} d}	 t          j                    dk    r\ddl}g }	 |                                }|dv rn#|dk    rt          |                    |           <d                    |          
d<   nddl}t          j	        d	t          j
                  } |                    |           }|                    |           }|d
         |j         z  |d
<   |                    | |j        |           g }	 t          j        | d          }|r|dv rn|                    |           2d                    |                              dd          
d<   n2# t"          t          t$          f$ r d
d<   Y nt&          $ r d
d<   Y nw xY w| V|T	 ddl}|                    | |j        |           n2# t&          $ r%}	t(                              d|	           Y d}	~	nd}	~	ww xY w| H	 t          j        |            n2# t&          $ r%}	t(                              d|	           Y d}	~	nd}	~	ww xY wd
d<   dS # | V|T	 ddl}|                    | |j        |           n2# t&          $ r%}	t(                              d|	           Y d}	~	nd}	~	ww xY w| H	 t          j        |            n2# t&          $ r%}	t(                              d|	           Y d}	~	nd}	~	ww xY wd
d<   w xY w)zKRead password with echo disabled. Uses msvcrt on Windows, /dev/tty on Unix.NWindowsr   T>   
r   r   z/dev/ttyr   r   >      
   r   utf-8replaceerrorsz)Failed to restore terminal attributes: %szFailed to close tty fd: %sr   )platformsystemmsvcrtgetwchKeyboardInterruptappendrE   termiosr"   openO_RDONLY	tcgetattrECHO	tcsetattr	TCSAFLUSHreaddecodeEOFErrorrc   rf   r&   rd   close)tty_fd	old_attrsr   charscr   	new_attrsb_termiosrm   rT   s             r   read_password_threadz7_prompt_for_sudo_password.<locals>.read_password_thread  s   	*	"  I--$AL((F{{//LLOOO$ &(WWU^^z""R[99#--f55	#--f55	(|w|m;	!!!&'*;YGGG$**A ^ 3 3LLOOO	$
 &)XXe__%;%;GI%;%V%Vz"+W5 	$ 	$ 	$!#F: 	$ 	$ 	$!#F:	$ !i&;Q....&&vx/A9MMMM  Q Q QLL!LaPPPPPPPPQ!BHV$$$$  B B BLL!=qAAAAAAAAB!F6NNN !i&;Q....&&vx/A9MMMM  Q Q QLL!LaPPPPPPPPQ!BHV$$$$  B B BLL!=qAAAAAAAAB!F6N!!!!s   EE H5 F	6H5 8F	H5 F		H5  F2 2
G!<GG!'G< <
H+H&&H+5K; IK
J&JKJKJ&%K&
K0KKK	K1HERMES_SPINNER_PAUSEg?u   ┌──────────────────────────────────────────────────────────┐uA   │  🔐 SUDO PASSWORD REQUIRED                              │u   ├──────────────────────────────────────────────────────────┤u?   │  Enter password below (input is hidden), or:            │uA   │    • Press Enter to skip (command fails gracefully)     │u   │    • Wait zs to auto-skipz                           u   │u   └──────────────────────────────────────────────────────────┘z  Password (hidden): T)endflushtargetdaemontimeoutr   r   u1     ✓ Password received (cached for this session)u'     ⏭ Skipped - continuing without sudou(   
  ⏱ Timeout - continuing without sudoz    (Press Enter to dismiss)u)     ⏭ Cancelled - continuing without sudoz
  [sudo prompt error: z] - continuing without sudo
)sysrx   rf   r"   r   r[   sleepprintr   ThreadstartrE   stdoutr
  r   r   )r   r  _sudo_cbr  password_threadr   rm   rT   s          @r   _prompt_for_sudo_passwordr    s    JJJ +,,H	8::## 	 	 	22	 ..F." ." ." ." ."`03-0
)*
3()))CDDD()))OPPPQRRR@@@@8KeSTTT()))%2T::::#*2FtTTT_555&> 	j)/RHGGG AIJJJJ?@@@GGGJ& "RZ//
122 0# =>>>0111GGGJ "RZ//
1222 0/ '(   9:::
 "RZ//
1222 0/    IIIIJJJ
rrr!RZ//
1222 0/
 "RZ//
122222sJ   # 
11E-H. 	AH. .AL L #	L ,,K;L ;L  L L    limitc                     | dS t          | t                    r
| d|         S 	 t          |           d|         S # t          $ r dt	          |           j         dcY S w xY w)z>Return a log-safe preview for possibly-invalid command values.Nz<None><>)r   r   r   rf   type__name__)r   r  s     r   _safe_command_previewr   c  s    x'3 vv-G}}VeV$$ - - -,4==),,,,,,-s   < "A! A!tokenc                     d| vs|                      d          rdS |                     dd          \  }}t          t          j        d|                    S )zCReturn True when *token* is a leading shell environment assignment.=Fr   z^[A-Za-z_][A-Za-z0-9_]*$)r   splitrK   rematch)r!  r   _values      r   _looks_like_env_assignmentr(  n  sW    
%5++C00u;;sA&&LD&4d;;<<<r   r  c                    |}t          |           }||k     r| |         }|                                s|dv rn|dk    r:|dz  }||k     r#| |         dk    r|dz  }||k     r| |         dk    ||k     r|dz  }g|dk    r@|dz  }||k     r4| |         }|dk    r|dz   |k     r|dz  }#|dk    r|dz  }n|dz  }||k     4|dk    r|dz   |k     r|dz  }|dz  }||k     | ||         |fS )zERead one shell token, preserving quotes/escapes, starting at *start*.z;|&()'r   "r   r   )r   isspace)r   r  inr   inners         r   _read_shell_tokenr0  v  s]   AGA
a%%QZ::<< 	2==99FAa%%GAJ#--Q a%%GAJ#--1uuQ99FAa%%
D==QUQYYFAC<<FAQ a%% ::!a%!))FA	Q5 a%%8 57Qr   c                    g }d}t          |           }d}d}||k     r| |         }|                                r#|                    |           |dk    rd}|dz  }F|dk    r]|r[|                     d|          }|dk    r|                    | |d                    n;|                    | ||                    |}|                     d|          s,|                     d	|          s|                     d
|          r)|                    | ||dz                       |dz  }d}|dv r|                    |           |dz  }d}6|dk    r|                    |           |dz  }d}Zt          | |          \  }}	|r!|dk    r|                    d           |dz  }n|                    |           |rt          |          rd}nd}|	}||k     d                    |          |fS )zRewrite only real unquoted sudo command words, not plain text mentions.

    Returns the rewritten command and the number of sudo invocations rewritten.
    r   Tr   r   #N&&||;;r   ;|&()Fsudozsudo -S -p ''r   )r   r,  r   findr   r0  r(  rE   )
r   outr-  r.  command_start
sudo_countr   comment_endr!  next_is
             r   _rewrite_real_sudo_invocationsr@    sB   
 C	AGAMJ
a%%QZ::<< 	JJrNNNTzz $FA999!,,tQ//Kb  

7122;'''JJwq}-...AdA&& 	'*<*<T1*E*E 	I[I[\`bcIdId 	JJwqQw'(((FA M<<JJrNNNFA M99JJrNNNFA!M)'155v 	Uf__JJ'''!OJJJJu 	"7>> 	" MM!Ma a%%d 773<<##r   c                 $   d}d}t          |           }d}||k     r| |         }|                                r|dk    rd}|dz  }0|dk    r"|r |                     d|          }|dk    rn|}X|                     d|          s,|                     d|          s|                     d	|          r|d
z  }d}|dv r|dz  }d}|dk    r|dz  }d}t	          | |          \  }}|r|dk    r|dz  }|rt          |          rd}nd}|}||k     |S )zReturn how many real sudo command words appear in *command*.

    Lightweight scan that reuses the same tokeniser as
    ``_rewrite_real_sudo_invocations`` but skips the string-building, so it
    is cheap to call from the result-processing path.
    r   Tr   r   r2  r3  r4  r5  r6  r   r7  r8  Fr9  )r   r,  r:  r   r0  r(  )	r   countr-  r.  r<  r   r>  r!  r?  s	            r   r   r     s    E	AGAM
a%%QZ::<< 	Tzz $FA999!,,tQ//Kb  AdA&& 	'*<*<T1*E*E 	I[I[\`bcIdId 	FA M<<FA M99FA!M)'155v 	Uf__QJE 	"7>> 	" MM!MO a%%R Lr   c                  6   t          j        dd                                                                          pd} | dk    rdS 	 t	          j        g dt          j        t          j        t          j        dd          }|j        dk    S # t          $ r Y dS w xY w)aN  Return True when local sudo currently works without prompting.

    Only probes for the `local` terminal backend; Docker/SSH/Modal/etc. must
    not inherit the host's sudo state. Re-probes every call (no process-level
    cache) so an expired sudo timestamp cannot make a later command silently
    block waiting for a password.
    TERMINAL_ENVlocalF)r9  z-ntruer   )stdinr  stderrr  checkr   )	r"   r#   rD   r   
subprocessrunDEVNULL
returncoderf   )terminal_envprobes     r   _sudo_nopasswd_worksrP    s     9^W55;;==CCEEPLwu"""$%%
 
 
 1$$   uus   AB
 

BBc                 T   t          |           }d}d}d}d}g }||k     rv| |         }|dk    r|dk    r|dk    rd}|dz  })|                                r|dz  }C|dk    r!|                     d|          }|dk    rn|}j|dk    r|dz   |k     r|dz  }|dv r't          | |          \  }	}
t	          |
|dz             }|d	k    r|dz  }|dz  }|d
k    rt	          d|dz
            }|dz  }|dk    rA|dz   |k     r8| |dz                                            s| |dz            dk    r|dz  }|dz  }!|dk    r|dk    r|dz  }d}|dz  };|dk    s|dk    r|dz  }N|                     d|          s|                     d|          r|dz   }|dz  }|dk    r	d}|dz  }|dk    r	d}|dz  }|dk    r|dz   |k     r| |dz            dk    r|dz  }|dz
  }|dk    r?| |                                         r%|dz  }|dk    r| |                                         %|dk    r| |         dv r|dz  }*|dk    r|                    ||f           d}|dz  }Pt          | |          \  }	}
t	          |
|dz             }||k     v|s| S | }t          |          D ]{\  }}|}||k     r?||                                         r%|dz  }||k     r||                                         %|d|         }|||         }||dz   d         }|dz   |z   dz   |z   }||S )u  Wrap `A && B &` (or `A || B &`) to `A && { B & }` at depth 0.

    Bash parses ``A && B &`` with `&&` tighter than `&`, so it forks a
    subshell for the whole `A && B` compound and backgrounds it. Inside
    the subshell, `B` runs foreground, so the subshell waits for `B` to
    finish. When `B` is a long-running process (`python3 -m http.server`,
    `yes > /dev/null`, anything that doesn't naturally exit), the subshell
    never exits. It leaks as a process stuck in ``wait4`` forever — and
    on the way, its open stdout pipe can prevent the terminal tool from
    returning promptly.

    Rewriting the tail to `A && { B & }` preserves `&&`'s error semantics
    (skip B if A fails) while replacing the subshell with a brace group.
    The brace group runs in the current shell (no fork), backgrounds B as
    a simple command (bash doesn't wait for it in non-interactive mode),
    and exits immediately. B runs as a normal backgrounded child, orphaned
    when the parent shell exits.

    Handles redirects (``&>``, ``2>&1``) and skips content inside quoted
    strings and parenthesised subshells. Leaves simple ``cmd &`` alone —
    that construct doesn't have the subshell-wait bug.
    r   r3  r   r   r2  r   r   >   r+  r*  (r8  {}r4  r5  ;|&r  z<>Nz{ z& })r   r,  r:  r0  maxr   r   reversed)r   r.  r-  paren_depthbrace_depthlast_chain_op_endrewritesr   nl_r?  jrT   	chain_endamp_pos
insert_posprefixmiddlesuffixs                      r   _rewrite_compound_backgroundrg  ,  sg   . 	GA	AKK &(H
a%%QZ ::+**{a/?/? "FA::<< 	FA
 99dA&&BRxxA::!a%!))FA )'155IAvFAE""A991KFA99aq11KFA 99QA(>(>(@(@GAPQENVZDZDZ1KFA99q1K "FA
 ??kAooFA dA&& 	'*<*<T1*E*E 	 !AFA 99 "FA 99 "FA 991uqyyWQU^s22QAAq&&WQZ//11&Q q&&WQZ//11&Avv'!*,,Q A%%!2A 6777 "FA &gq11	6A] a%%`   F&x00 9 9	7 
7""vj'9'A'A'C'C"!OJ 7""vj'9'A'A'C'C"$
7*+!& $'%/&8Mr   c                 2   | dS t          |           \  }}|dk    r| dfS 	 ddlm}m} 	  |d          }n*# |$ r" t          j                            d          }Y nw xY wn/# t          $ r" t          j                            d          }Y nw xY w|du}|r|nt                      }|s|st                      r| dfS t                      du}t          d          p|}	|s%|s#|	r!t          d          }|rt          |           |s|r|d	z   }
||
|z  fS | dfS )
a  
    Transform sudo commands to use -S flag if SUDO_PASSWORD is available.

    This is a shared helper used by all execution environments to provide
    consistent sudo handling across local, SSH, and container environments.

    Returns:
        (transformed_command, sudo_stdin) where:
        - transformed_command has every bare ``sudo`` replaced with
          ``sudo -S -p ''`` so sudo reads its password from stdin.
        - sudo_stdin is the password string with a trailing newline that the
          caller must prepend to the process's stdin stream.  sudo -S reads
          exactly one line (the password) and passes the rest of stdin to the
          child command, so prepending is safe even when the caller also has
          its own stdin_data to pipe.
        - If no password is available, sudo_stdin is None and the command is
          returned unchanged so it fails gracefully with
          "sudo: a password is required".

    Callers that drive a subprocess directly (local, ssh, docker, singularity)
    should prepend sudo_stdin to their stdin_data and pass the merged bytes to
    Popen's stdin pipe.

    Callers that cannot pipe subprocess stdin (modal, daytona,
    vercel_sandbox) must embed the password in the command string
    themselves; see their execute() methods for how they handle the
    non-None sudo_stdin case.

    If SUDO_PASSWORD is not set and an interactive UI is available
    (HERMES_INTERACTIVE=1 or a registered sudo password callback):
      Prompts user for password with 45s timeout, caches for session.

    If SUDO_PASSWORD is not set and NOT interactive:
      Command runs as-is (fails gracefully with "sudo: a password is required").
    N)NNr   )UnscopedSecretErrorr>   r   HERMES_INTERACTIVEr   )r   r   )r@  rJ   ri  r>   r"   r   rC   rf   r   rP  rx   r   r  r   )r   transformedr=  ri  r>   _configured_passwordhas_configured_passwordrs   has_sudo_prompt_callbackshould_prompt_for_sudopassword_lines              r   _transform_sudo_commandrq    s   H z<WEEKQ}
?FFFFFFFF	C#-:o#>#>  " 	C 	C 	C#%:>>/#B#B   	C ? ? ?!z~~o>>?2$> #	)&((  # = =Q=S=S }:<<DH,--I1I  # 5= 5=S 51"EEE 	5%m444 7- 7 &,MJ666D=s1   A" 7 A" $AA" AA" ")BB)EnvironmentConnectionError)LocalEnvironment)SingularityEnvironment)SSHEnvironment)DockerEnvironment)ModalEnvironment)ManagedModalEnvironment)is_managed_tool_gateway_readyu  Execute shell commands on a Linux environment. Filesystem, current working directory, and exported environment variables persist between calls.

Do NOT use cat/head/tail (use read_file), grep/rg/find/ls (use search_files), sed/awk (use patch), or echo/heredoc file creation (use write_file). Reserve terminal for: builds, installs, git, processes, scripts, network, package managers, and anything that needs a shell.
NEVER pipe a build/test command through tail/head/cat to shorten output (e.g. `cargo build | tail -20`): output is auto-truncated with the full text saved to a file, and the pipe makes exit_code report the LAST pipeline command's status (tail's 0), masking real failures. Run the command bare; the same applies to `cmd || echo failed`, which also masks the exit code.
Environment state persists: activate a virtualenv or export variables once per session, not before every command.

Foreground (default): returns INSTANTLY when the command finishes, even with a high timeout — set timeout generously for long builds.
Background: set background=true (returns a session_id). Pair with notify_on_complete=true for bounded tasks; leave silent only for servers/daemons that never exit. Never use nohup/setsid/trailing '&' — use background=true so Hermes tracks the process. After starting a server, verify readiness with a health check, then act in a separate call; no blind sleep loops. Manage with process(action="poll"/"wait").
Working directory: use 'workdir' for per-command cwd. When a command changes the session cwd (cd, pushd), the result includes a "cwd" field — trust it instead of prefixing every command with 'cd'.
PTY: set pty=true for interactive CLIs (they hang without it). Pipe git output to cat if it might page.
_active_environments_last_activity_creation_lockscontainer_configc                 d   |                      dd          sdS t          rdS t          5  t          r	 ddd           dS daddd           n# 1 swxY w Y   	 t          t	          j        dd                    }n# t          t          f$ r d}Y nw xY wt          d|          }|dz  }	 d	d
l	m
}m} n# t          $ r Y dS w xY w	  |            } |||          }|rt                              d||           dS dS # t          $ r&}t                              d|           Y d}~dS d}~ww xY w)uo  Run the docker orphan reaper once per process, if enabled.

    Sweeps long-Exited containers labeled ``hermes-agent=1`` for the current
    profile that match the issue #20561 leak class — containers left behind
    by Hermes processes that exited without firing ``atexit`` (SIGKILL,
    OOM, terminal-window-close). The reaper is conservative by default:
    only Exited containers older than ``2 × lifetime_seconds`` and scoped to
    the current profile.

    Gates:

    * ``terminal.docker_orphan_reaper: false`` disables it entirely (the
      operator opted out — usually because they're running multiple
      Hermes processes in the same profile and don't trust the
      conservative defaults).
    * ``_docker_orphan_reaper_ran`` flag — sweep runs once per Python
      interpreter, not on every subagent / RL-rollout / parallel
      ``terminal()`` call.
    docker_orphan_reaperTNTERMINAL_LIFETIME_SECONDS300,  <   r   r   )reap_orphan_containers_get_active_profile_name)max_age_secondsprofile_filterzADocker orphan reaper removed %d stale container(s) for profile %szDocker orphan reaper raised: %s)rC   _docker_orphan_reaper_ran_docker_orphan_reaper_lockintr"   r#   r$   r%   rX  tools.environments.dockerr  r  ImportErrorr&   inforf   rd   )r}  lifetimemax_ager  r  profileremovedrm   s           r   _maybe_reap_docker_orphansr  R  s2   *  6==  ! 	# ) )$ 	) ) ) ) ) ) ) ) %)!) ) ) ) ) ) ) ) ) ) ) ) ) ) )ry!<eDDEEz"   2x  HlG	
 	
 	
 	
 	
 	
 	
 	
 	
    ;**,,((#G
 
 
  	KKS    	 	
  ; ; ;6:::::::::;sR   	AAAA"A< <BB+B4 4
CC5C? ?
D/	D**D/_task_env_overrides_session_cwdr   cwdc                    t          |t                    r|                                sdS t          | pd          }t          5  t                              |          |k    r
|t          |<   ddd           dS # 1 swxY w Y   dS )a  Record *cwd* as the working directory of *session_key*.

    Called wherever a session's live cwd becomes known: after a terminal
    command completes (the env's post-command tracking has just parsed the
    resulting cwd) and when a surface registers a workspace cwd override.
    Empty/None session keys collapse to ``"default"`` (single-session CLI).
    Non-string / empty cwds are ignored.
    Nr   )r   r   rD   _session_cwd_lockr  rC   )r   r  keys      r   record_session_cwdr    s     c3 syy{{ 
k&Y
'
'C	 $ $C  C'' #L$ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $s   )A::A>A>c                     t          | pd          }t          5  t                              |          cddd           S # 1 swxY w Y   dS )a  Return the recorded working directory for *session_key*, if any.

    No fallback chain here on purpose: callers decide what an absent record
    means (config default, TERMINAL_CWD seed, process cwd). ``None``/empty
    keys read the ``"default"`` record.
    r   N)r   r  r  rC   )r   r  s     r   get_session_cwdr    s     k&Y
'
'C	 % %$$% % % % % % % % % % % % % % % % % %s   A  AAc                 |    t           5  t                              | d           ddd           dS # 1 swxY w Y   dS )z/Drop a session's cwd record (session teardown).N)r  r  r   )r   s    r   clear_session_cwdr    s    	 , ,d+++, , , , , , , , , , , , , , , , , ,s   155task_id	overridesc                    |t           | <   |                    d          }t          |t                    r|                                rt          | |           t          |           }t          5  t                              |           pt                              |          }ddd           n# 1 swxY w Y   |t          |dd          ||_
        dS dS dS dS dS )a#  
    Register environment overrides for a specific task/rollout.

    Called by Atropos environments before the agent loop to configure
    per-task sandbox settings (e.g., a custom Dockerfile for the Modal image).

    Supported override keys:
        - modal_image: str -- Path to Dockerfile or Docker Hub image name
        - docker_image: str -- Docker image name
        - cwd: str -- Working directory inside the sandbox

    Args:
        task_id: The rollout's unique task identifier
        overrides: Dict of config keys to override
    r  N)r  rC   r   r   rD   r  _resolve_container_task_id	_env_lockrz  ru   r  )r  r  new_cwdcontainer_idenvs        r   register_task_env_overridesr    s:     $-  mmE""G'3 GMMOO  	7G,,, 2':: 	^ 	^&**733]7K7O7OP\7]7]C	^ 	^ 	^ 	^ 	^ 	^ 	^ 	^ 	^ 	^ 	^ 	^ 	^ 	^ 	^?wsE488DCGGG    ?DDs   /5B00B47B4c                     t                               | d           t          |            t          5  t                              | d           ddd           dS # 1 swxY w Y   dS )z
    Clear environment overrides for a task after rollout completes.

    Called during cleanup to avoid stale entries accumulating.
    N)r  r   r  _container_alias_lock_container_aliasesr  s    r   clear_task_env_overridesr    s     GT***g	 . .w---. . . . . . . . . . . . . . . . . .s   AA"Ar  child_task_idparent_task_idc                     | sdS t           5  t          |pd          t          | <   ddd           dS # 1 swxY w Y   dS )a&  Make *child_task_id* resolve to *parent_task_id*'s container.

    Called by ``delegate_task`` at child spawn so subagents share the parent
    session's sandbox under per-session container isolation. A missing/empty
    parent id aliases the child to ``"default"`` (top-level CLI parent).
    Nr   )r  r   r  )r  r  s     r   register_container_aliasr    s      	 M M,/0K),L,L=)M M M M M M M M M M M M M M M M M Ms   377c                     t                      }| }t          5  |t          v r3||vr/|                    |           t          |         }|t          v r||v/ddd           n# 1 swxY w Y   |S )uA   Follow the child→parent alias chain (cycle-safe) for *task_id*.N)setr  r  add)r  seenr  s      r   _resolve_container_aliasr    s    55D
C	 * *'''CtOOHHSMMM$S)C '''CtOO* * * * * * * * * * * * * * * Js   =A!!A%(A%c                      t                       t          j        dd          dk    rdS t          j        dd                                          dvS )a  True when docker sessions get their OWN containers (issue: stale
    workspace mounts leaking between desktop sessions).

    Gated on ``terminal.backend: docker`` + ``container_persistent: false``:
    a non-persistent sandbox is a statement that state must not survive the
    session, so sharing one container across sessions contradicts it. With
    ``container_persistent: true`` the documented ONE-long-lived-container
    contract is unchanged.
    rD  rE  r   FTERMINAL_CONTAINER_PERSISTENTrF  >   r  yesrF  )_ensure_terminal_env_bridgedr"   r#   r   rw   r   r   !_docker_session_isolation_enabledr  (  sQ     !"""	y))X55u94f==CCEEMaaar   >   r   modal_imagedocker_imagedaytona_imagesingularity_imagec                     | r	| t           vrdS t          t          t           |                                                    t          z            S )u   True when *task_id* registered backend-image/env_type overrides.

    The single owner of the "is this an RL/benchmark-style isolated rollout"
    predicate — shared by container-key resolution and container creation so
    the two can't drift.
    F)r  rK   r  keys_ISOLATION_OVERRIDE_KEYSr  s    r   _has_isolation_overridesr  >  sJ      g%888u'0557788;SSTTTr   c                 j    | rt          |           r| S | rt                      rt          |           S dS )uE  
    Map a tool-call ``task_id`` to the container/sandbox key used by
    ``_active_environments``.

    The top-level agent passes ``task_id=None`` and lands on ``"default"``.
    ``delegate_task`` children pass their own subagent ID so that
    file-state tracking, the active-subagents registry, and TUI events stay
    distinct per child -- but we deliberately collapse that ID back to
    ``"default"`` here so subagents share the parent's long-lived container
    (one bash, one /workspace, one set of installed packages).

    Exception: RL / benchmark environments (TerminalBench2, HermesSweEnv, ...)
    call ``register_task_env_overrides(task_id, {...})`` to request a
    per-task Docker/Modal image. When an override is registered for a
    task_id, we honour it by returning the task_id unchanged -- those
    rollouts need their own isolated sandbox, which is the whole point of
    the override.

    CWD-only overrides (registered by the ACP adapter for workspace
    tracking) are *not* isolation signals — they should not cause each
    session to spin up its own container.  Only overrides containing
    backend-specific image keys or ``env_type`` trigger isolation.

    Per-session container isolation (docker + ``container_persistent:
    false``): each session's task_id is its own container key, so a fresh
    chat gets a fresh sandbox with only ITS mounts — a previous session's
    workspace can no longer appear in a new session's container.
    ``delegate_task`` children keep sharing the parent's container via the
    alias registry (``register_container_alias``).
    r   )r  r  r  r  s    r   r  r  J  sJ    >  +G44  1466 1'0009r   c                     | pd}t                               |          p(t                               t          |                    pi S )a  Return the env overrides for *task_id*, raw key first then collapsed.

    ``register_task_env_overrides`` writes under the *raw* task/session id, but
    a CWD-only override collapses (:func:`_resolve_container_task_id`) to the
    shared ``"default"`` container so per-session surfaces (ACP/gateway/
    dashboard) don't each spin up their own sandbox. Callers that need the
    override (terminal command setup, file-tool cwd resolution) must therefore
    read the raw id FIRST and only fall back to the collapsed container id, or
    the originating session's override is silently dropped. This is the single
    source of that lookup so the terminal and file layers can't drift apart.
    r   )r  rC   r  )r  r*   s     r   resolve_task_overridesr  p  sK     
YC$$ 	""#=c#B#BCC	r   c                    |                      d          dk    rdS |                      d          sdS t                      s|                      d          S t          |          dk    r|                      d          S t          |          }|                     d          dk    rdS |                     d	          }t	          |t
                    r|                                sdS t          j        	                    t          j        
                    |                    }t          j                            |          sdS |                    d
          rdS |S )u  Host directory to bind-mount at ``/workspace`` for *task_id*'s container.

    The single owner of the cwd-mount policy, shared by every environment
    creation site (terminal tool, file tools, execute_code, lazy bring-up):

    * Shared-container mode (the default): the process-global
      ``TERMINAL_CWD``-derived ``config["host_cwd"]`` — unchanged legacy
      behavior, ONE container whose mount tracks the configured workspace.
    * Per-session isolation mode (docker + ``container_persistent: false``):
      only the SESSION's own registered workspace may mount.  The process
      env var is a launch artifact — the TUI/desktop workspace picker writes
      ``os.environ["TERMINAL_CWD"]`` and it outlives the session that set it,
      so deriving a fresh session's mount from it leaks the previous
      session's directory into a chat that never attached one.  Overrides
      tagged ``cwd_source: "process"`` (gateway fallback to the global env
      var) are likewise refused as mount sources; only a workspace the user
      actually attached to THIS session (``cwd_source: "session"`` or an
      untagged override from ACP/RL surfaces) mounts.
    r   r   Nr   r   r   
cwd_sourceprocessr  
/workspace/root)rC   r  r  r  r   r   rD   r"   rk   abspath
expanduserisdirr   )r7   r  r  	candidates       r   _resolve_task_host_cwdr    sA   ( zz*))t::566 t,.. &zz*%%%!'**i77zz*%%%&w//I}}\""i//te$$Ii%% Y__->-> t 2 29 = =>>I7==## t344 tr   r)   c           
          t          j        | |          }	  ||          S # t          t          j        f$ r t          d|  d|d| d          w xY w)zParse an environment variable with *converter*, raising a clear error on bad values.

    Without this wrapper, a single malformed env var (e.g. TERMINAL_TIMEOUT=5m)
    causes an unhandled ValueError that kills every terminal command.
    zInvalid value for : z (expected z1). Check ~/.hermes/.env or environment variables.)r"   r#   r%   jsonJSONDecodeErrorr(   s        r   _parse_env_varr    s     )D'
"
"C
y~~,- 
 
 
> > > > >: > > >
 
 	

s	   
" 0Ac                      	 t          j                    S # t          $ r6 t          j        d          pt           j                            d          cY S w xY w)am  Return the current working directory, tolerating a deleted CWD.

    ``os.getcwd()`` raises FileNotFoundError when the process's working
    directory has been removed out from under it (e.g. a scratch workspace
    that was cleaned up mid-session). Fall back to TERMINAL_CWD, then the
    user's home directory, so terminal setup never crashes on a stale CWD.
    TERMINAL_CWDr   )r"   getcwdFileNotFoundErrorr#   rk   r  rw   r   r   _safe_getcwdr    s^    Dy{{ D D Dy((CBG,>,>s,C,CCCCDs    =AA)z/Users/z/home/zC:\zC:/>   modalr   daytonasingularityvercel_sandboxc                       sdS t           fdt          D                       rdS t          j                                       sdS dS )a  Return True if *cwd* is a host/relative path that won't work as the
    working directory inside a container sandbox.

    A container's cwd must be an absolute path that exists *inside* the
    sandbox (e.g. ``/workspace`` or ``/root``). A host path (``/home/user``,
    ``C:\Users\me``) or a relative path (``.``, ``src/``) is meaningless to
    ``docker run -w`` and makes the container fail to start (exit 125).
    Fc              3   B   K   | ]}                     |          V  d S r4   r   )r   pr  s     r   r   z-_is_unusable_container_cwd.<locals>.<genexpr>  s/      
9
93>>!
9
9
9
9
9
9r   T)r   _HOST_CWD_PREFIXESr"   rk   isabs)r  s   `r   _is_unusable_container_cwdr    s_      u

9
9
9
9&8
9
9
999 t 7== t5r   c                  H   t           rdS da 	 ddlm} m}  |            }t	          |                    d          t                    }|r | dd           dS dt          j        vr | dd           dS dS # t          $ r  t                              d	d
           Y dS w xY w)u-  Backfill TERMINAL_* env vars from config.yaml when no launcher did.

    terminal_tool reads ALL terminal settings from os.environ (TERMINAL_*).
    The CLI (cli.py ``env_mappings``), the gateway (gateway/run.py
    ``_terminal_env_map``), and TUI/dashboard PTY launches
    (``apply_terminal_config_to_env``) bridge ``terminal.*`` config into env
    vars at startup — but processes that skip all of those paths (``hermes
    serve`` / the Desktop app backend's in-process agents, the desktop cron
    ticker, ACP) used to silently fall back to the local backend even when
    config.yaml selects ``terminal.backend: docker``, running commands on the
    host the user intended to sandbox (#63141, #54449, #61115, #65696).

    Explicit terminal config keys win: when config.yaml has a ``terminal``
    section, each key present there overrides its matching env value (which may
    be stale from ``hermes setup``). Environment values for omitted terminal
    keys are preserved. When no terminal section exists, exported/.env values
    keep working unchanged.
    NTr   )apply_terminal_config_to_envread_raw_configterminal)r  overriderD  Fu.   terminal config → env fallback bridge failedrY   )!_terminal_config_bridge_attemptedhermes_cli.configr  r  r   rC   dictr"   r   rf   r&   rd   )r  r  
raw_confighas_terminal_sections       r   r  r    s    ( ) (,%VSSSSSSSS %_&&
)*..*D*DdKK 	C((TDAAAAAA2:-- )(TEBBBBBB .-  V V V 	EPTUUUUUUVs   A	A7 A7 7&B! B!c                  D
   d} t                       t          j        dd          }t          j        dd                                          dv }|dv }|dk    }|r8t	          d	d
t
          d          }t	          dd          }t	          dd          }nd}d}d}|rt	          ddt          j        d          }t	          ddt          j        d          }	t	          ddt          j        d          }
t	          ddt          j        d          }t          j        dd          }n
g }g }	i }
g }d}|dk    rt                      }n|dk    rd}n|dk    rt          }nd}t          j        d |          }d!d"l
m} |r+ |||          st          j                            |          }d#}|dk    r|rt          j        d           pt                      }t          j                            t          j                            |                    t          fd$t           D                       sSt          j                                      r8t          j                                      r                    d%          s}d&}n?|t(          v r6|r4t+          |          r%||k    rt,                              d'|||           |}i d(|d)t1          t          j        d*d+                    d,t          j        d-|           d.|d/t          j        d0d1|            d2t          j        d3|           d4t          j        d5|           d6t          j        d7d8                                          d9|d:|d;|d<t	          d=d>          d?t	          d@dA          dBt          j        dCd8          dDt          j        dEd8          dFt	          dGdH          dIt          j        dJd8          t          j        dKt          j        dLdM                                                    dv t          j        dNd                                          dv |||t          j        dOdM                                          dv |	|
t          j        dPd                                          dv t          j        dQdM                                          dv ||t          j        dRdM                                          dv t          j        dSdM                                          dv dTS )UzBGet terminal environment configuration from environment variables.*nikolaik/python-nodejs:python3.11-nodejs20rD  rE  &TERMINAL_DOCKER_MOUNT_CWD_TO_WORKSPACEfalse>   r  r  rF  >   r  r   r  r  r  r   TERMINAL_CONTAINER_CPUr  r/   TERMINAL_CONTAINER_MEMORY5120TERMINAL_CONTAINER_DISK51200g      ?   r;   TERMINAL_DOCKER_FORWARD_ENVz[]z
valid JSONTERMINAL_DOCKER_VOLUMESTERMINAL_DOCKER_ENVz{}TERMINAL_DOCKER_EXTRA_ARGSTERMINAL_DOCKER_SHM_SIZE1gsshr   r  r  r  r   )_is_ssh_remote_tilde_cwdNc              3   B   K   | ]}                     |          V  d S r4   r  )r   r  r  s     r   r   z"_get_env_config.<locals>.<genexpr>b  s1      DDA	$$Q''DDDDDDr   r  r  zeIgnoring TERMINAL_CWD=%r for %s backend (host/relative path won't work in sandbox). Using %r instead.r   
modal_modeTERMINAL_MODAL_MODEautor  TERMINAL_DOCKER_IMAGEdocker_forward_envr  TERMINAL_SINGULARITY_IMAGE	docker://r  TERMINAL_MODAL_IMAGEr  TERMINAL_DAYTONA_IMAGEr9   TERMINAL_VERCEL_RUNTIMEr   r  r   r   r  TERMINAL_TIMEOUT180lifetime_secondsr  r  ssh_hostTERMINAL_SSH_HOSTssh_userTERMINAL_SSH_USERssh_portTERMINAL_SSH_PORT22ssh_keyTERMINAL_SSH_KEYTERMINAL_SSH_PERSISTENTTERMINAL_PERSISTENT_SHELLrF  TERMINAL_LOCAL_PERSISTENTr   TERMINAL_DOCKER_RUN_AS_HOST_USERTERMINAL_DOCKER_NETWORK(TERMINAL_DOCKER_PERSIST_ACROSS_PROCESSESTERMINAL_DOCKER_ORPHAN_REAPER)ssh_persistentlocal_persistentcontainer_cpucontainer_memoryr:   container_persistentr   
docker_envdocker_run_as_host_userdocker_networkdocker_extra_argsdocker_shm_sizedocker_persist_across_processesr  )r  r"   r#   r   r  floatr  loadsr  _VERCEL_SANDBOX_DEFAULT_CWDr  r   rk   r  r  r   r  r  r  r   _CONTAINER_BACKENDSr  r&   r  r   rD   )default_imager   mount_docker_cwdcontainer_backenddocker_backendr!  r"  r:   r  r   r$  r'  r(  default_cwdr  r   r   docker_cwd_sourcer  s                     @r   _get_env_configr4  $  s    AM """y11Hy!I7SSYY[[_ss $cc)N  &'?eXVV)*EvNN'(A7KK +,I4QUQ[]ijj'(A4Uabb#$94\ZZ
*+Gtz[ghh)$>EE

 7"nn	U			%	%	%1 )NK
0
0C::::::
 &++Hc:: &g  %%H8 0In55GGOOBG$6$67H$I$IJJ	DDDD1CDDDDD	i((	-/W]]9-E-E	NWNbNbczN{N{	 !HC	(	(	(S	(%c** 	sk/A/AKK XX{4 4 4 C7H7'	2G(P(PQQ7 		"9=II7 	0	7
 	RY'CE`Q^E`E`aa7 	ry!7GG7 	#;]KK7 	")$=rBBHHJJ7 	s7 	H7 	()97 	>"4e<<7 	N+FNN7 	BI12667  	BI1266!7" 	N#6==#7$ 	29/44%7, )%I16::
 
 %'')* I&A7KKQQSSWkk ',( "	*I6 R R X X Z Z^r r( #%9-OQX#Y#Y#_#_#a#aey#y)$=vFFLLNNRff.* ,.96,
 ,

%''),* !#	+V!
 !

%'')!*i7 7 7 7r   r  c                 X    t          | t                      t          d                    S )z2Resolve direct vs managed Modal backend selection.r  )
has_directmanaged_ready)r   r   ry  )r  s    r   _get_modal_backend_stater8    s0    &/113G<<   r   c                     |                      dd          |                      dd          |                      dd          |                      dd          |                      dd          d	S )
a  Build the ``ssh_config`` dict passed to :func:`_create_environment`.

    Shared by the terminal tool's own get-or-create path and the lazy
    :func:`ensure_task_env` bring-up so both derive SSH connection settings
    from the resolved config identically.
    r  r   r  r     r  r  F)hostuserportr  
persistentrC   r   s    r   _ssh_config_from_configr@    si     

:r**

:r**

:r**zz)R((jj!1599  r   c                    i d|                      dd          d|                      dd          d|                      dd          d|                      dd          d	|                      d	d
          d|                      dd          d|                      dg           d|                      dd          d|                      dg           d|                      di           d|                      dd          d|                      dg           d|                      dd          d|                      dd          d|                      dd          d|                      dd          S )zBuild the ``container_config`` dict passed to :func:`_create_environment`.

    Shared by the terminal tool's own get-or-create path and the lazy
    :func:`ensure_task_env` bring-up (see :func:`_ssh_config_from_config`).
    r!  r   r"  r  r:   r;   r#  Tr  r  r9   r   r   r   Fr  r$  r%  r'  r(  r  r&  r)  r  r?  r   s    r   _container_config_from_configrB    s   OQ77FJJ'94@@ 	&**%5u== 	

+A4 H H	
 	fjjv66 	&**%5r:: 	&**%5r:: 	(4SUZ)[)[ 	fjj)=rBB 	fjjr22 	"6::.G#O#O 	VZZ(;R@@ 	6::&7>> 	&**%5t<< 	*6::6WY]+^+^  	

+A4 H H! r   imager  
ssh_configlocal_configr   c	           
         |pi }	|	                     dd          }
|	                     dd          }|	                     dd          }|	                     dd          }|	                     d	g           }|	                     d
g           }|	                     di           }|	                     dg           }|	                     dd          }| dk    rt          ||          S | dk    rt          |	           t                      o|dk    ot	          |           }t          dOi d|d|d|d|
d|d|d|d|d|d|d|	                     dd          d|d |d!|	                     d"d          d#|d$|d%|rdn|	                     d&d          d'|	                     d(d)          }|r	 d|_        n# t          $ r Y nw xY w|S | d*k    rt          ||||
||||+          S | d,k    rXi }|
d-k    r|
|d<   |d-k    r||d<   |d-k    rE	 d-d.l	}d-d.l
}d/|                    |j        j                  j        v r||d/<   n# t          $ r Y nw xY wt!          |	                     d0                    }|d1         d2k    rt#          ||||||3          S |d1         d4k    r|d5         r"t%          d6t'          d7          z   d8z             |d9         d2k    rt%          d:t'          d7          z             |d9         d4k    rt%          d;          d<}t)                      rd=}t%          |          t+          ||||||3          S | d>k    r&d-d?lm}  ||||t1          |
          ||||+          S | d@k    r.d-dAlm}  ||	                     dB          pd.|||
||||C          S | dDk    r|r*|                     dE          r|                     dF          st%          dG          t7          |dE         |dF         |                     dHdI          |                     dJdK          ||L          S t%          dM|  dN          )Pa  
    Create an execution environment for sandboxed command execution.
    
    Args:
        env_type: One of "local", "docker", "singularity", "modal",
            "daytona", "vercel_sandbox", "ssh"
        image: Docker/Singularity/Modal image name (ignored for local/ssh/vercel)
        cwd: Working directory
        timeout: Default command timeout
        ssh_config: SSH connection config (for env_type="ssh")
        container_config: Resource config for container backends (cpu, memory, disk, persistent)
        task_id: Task identifier for environment reuse and snapshot keying
        host_cwd: Optional host working directory to bind into Docker when explicitly enabled
        
    Returns:
        Environment instance with execute() method
    r!  r   r"  r  r:   r;   r#  Tr   r  r$  r'  r&  rE  )r  r  r   r   rC  r  r  cpumemoryrM   persistent_filesystemr  volumesr   auto_mount_cwdr   Fforward_envr  run_as_host_userr%  network
extra_argspersist_across_processesr)  shm_sizer(  r  r  )rC  r  r  rG  rH  rM   rI  r  r  r   Nephemeral_diskr  selected_backendmanaged)rC  r  r  modal_sandbox_kwargsrI  r  directmanaged_mode_blockedzModal backend is configured for managed mode, but Nous Tool Gateway access is not currently available and no direct Modal credentials/config were found. managed Modal executionzH Choose TERMINAL_MODAL_MODE=direct/auto to use direct Modal credentials.modez[Modal backend is configured for managed mode, but the managed tool gateway is unavailable. z_Modal backend is configured for direct mode, but no direct Modal credentials/config were found.zHModal backend selected but no direct Modal credentials/config was found.z`Modal backend selected but no direct Modal credentials/config or managed tool gateway was found.r  )DaytonaEnvironmentr  )VercelSandboxEnvironmentr9   )r2   r  r  rG  rH  rM   rI  r  r  r;  r<  z?SSH environment requires ssh_host and ssh_user to be configuredr=  r:  r  r   )r;  r<  r=  key_pathr  r  zUnknown environment type: zV. Use 'local', 'docker', 'singularity', 'modal', 'daytona', 'vercel_sandbox', or 'ssh'rw   )rC   _LocalEnvironmentr  r  r  _DockerEnvironment_session_scopedAttributeError_SingularityEnvironmentinspectr  	signatureSandboxcreate
parametersrf   r8  _ManagedModalEnvironmentr%   r   r   _ModalEnvironmenttools.environments.daytonarZ  r  !tools.environments.vercel_sandboxr[  _SSHEnvironment)r   rC  r  r  rD  r}  rE  r  r   ccrG  rH  rM   r>  rJ  r  r$  r'  r&  session_scopeddocker_env_objsandbox_kwargsrb  r  modal_statemessage_DaytonaEnvironment_VercelSandboxEnvironments                               r   _create_environmentrt    sl   , 
	RB
&&!
$
$CVV&--F66"E**D.55Jff%r**G 4b99b))J2B77VV,d33N7 S'::::	X		 	#2&&& .// 69$6,W555 	
 , 
 
 
%
 S
*1'

"F
)-
 #-*
 7>g
 G	

 X
 66"A5III
 +*
 

  VV$=uEEE
 #N
 )(
 ( EVV=tDD
  VV-t444!
,  	15..!   	]	"	"&S'F",g
 
 
 	
 
W		77$'N5!A::'-N8$!88%%%%%%%%#w'8'89M'N'N'YYY7;N#34    /rvvl/C/CDD)*i77+g%3&0'    )*h6612 	 < <1  aa   6"i// q;1    6"h.. u   aG)++ v  W%%% S'!/",g
 
 
 	
 
Y		XXXXXX""S'Cd",g
 
 
 	
 
%	%	%	
 	
 	
 	
 	
 	
 )(FF+,,4",	
 	
 	
 		
 
U		 	`!7!7 	`z~~f?U?U 	`^___F#F#++^^E2..
 
 
 	
 M M M M
 
 	
s$   2F: :
GG3I 
IIr  r  c                    t          j                     }	 ddlm} t          t                                                    D ]!}|                    |          r
|t          |<   "n# t          $ r Y nw xY wg }t          5  t          t          	                                          D ]]\  }}||z
  | k    rOt                              |d          }t                              |d           ||                    ||f           ^t          5  |D ] \  }}t                              |d           !	 ddd           n# 1 swxY w Y   ddd           n# 1 swxY w Y   |D ]+\  }}	 ddlm}  ||           n# t          $ r Y nw xY w	 t#          |d          r|                                 nIt#          |d          r|                                 n$t#          |d          r|                                 t*                              d|           # t.          $ rl}	t1          |	          }
d	|
v sd
|
                                v rt*                              d|           nt*                              d||	           Y d}	~	%d}	~	ww xY wdS )zOClean up environments that have been inactive for longer than lifetime_seconds.r   process_registryNclear_file_ops_cachecleanupstop	terminatez,Cleaned up inactive environment for task: %s404	not found*Environment for task %s already cleaned up-Error cleaning up environment for task %s: %s)r[   tools.process_registryrw  listr{  r  has_active_processesr  r  itemsrz  r   r   _creation_locks_lockr|  tools.file_toolsry  hasattrrz  r{  r|  r&   r  rf   r   r   r'   )r  current_timerw  r  envs_to_stop	last_timer  r_  ry  rm   	error_strs              r   _cleanup_inactive_envsr    sq   9;;L;;;;;;N//1122 	7 	7G44W== 7*6w'	7     L	 3 3"&~';';'='=">"> 	8 	8GYi'*:::*..w==""7D111? ''#777 " 	3 	3* 3 3
##GT22223	3 	3 	3 	3 	3 	3 	3 	3 	3 	3 	3 	3 	3 	3 	33 3 3 3 3 3 3 3 3 3 3 3 3 3 3 % \ \	======  )))) 	 	 	D		\sI&&  f%%  



k**  KKFPPPP 	\ 	\ 	\AI	!![IOO4E4E%E%EH'RRRRNPWYZ[[[	\'\ \su   AA$ $
A10A1=BE	$D:.E:D>	>ED>	EEE%E77
FFB	H
JA!JJc                  6   t           r	 t                      } t          | d                    n4# t          $ r'}t                              d|d           Y d}~nd}~ww xY wt          d          D ]}t           s nt          j        d            t           dS dS )zKBackground thread worker that periodically cleans up inactive environments.r  zError in cleanup thread: %sTrY   Nr  r   )	_cleanup_runningr4  r  rf   r&   r'   ranger[   r  )r7   rm   r_  s      r   _cleanup_thread_workerr    s    
 
	L$&&F"6*<#=>>>> 	L 	L 	LNN8!dNKKKKKKKK	L r 	 	A# JqMMMM  
 
 
 
 
s   #- 
AAAc                      t           5  t          t                                          s6dat	          j        t          d          at                                           ddd           dS # 1 swxY w Y   dS )z;Start the background cleanup thread if not already running.NTr  )r  _cleanup_threadis_aliver  r   r  r  r  rw   r   r   _start_cleanup_threadr    s     
 $ $"/*B*B*D*D"#'.6LUYZZZO!!###	$ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $s   AA,,A03A0c                      da t          6	 t                              d           dS # t          t          f$ r Y dS w xY wdS )z#Stop the background cleanup thread.FN   r  )r  r  rE   
SystemExitr   rw   r   r   _stop_cleanup_threadr    sb     "	   +++++-. 	 	 	DD	 #"s   ( ==c                     t          |           }t          5  t                              |          pt                              |           cddd           S # 1 swxY w Y   dS )z9Return the active BaseEnvironment for *task_id*, or None.N)r  r  rz  rC   )r  lookups     r   get_active_envr    s    '00F	 U U#''//T3G3K3KG3T3TU U U U U U U U U U U U U U U U U Us   4AAAc                    t                      }|d         }|dk    rdS t          |           }t          |          }|<t          5  t	          j                    t
          |<   ddd           n# 1 swxY w Y   |S t          |           }|dk    r|                    d          p|d         }nn|dk    r|                    d          p|d         }nJ|dk    r|                    d	          p|d	         }n&|d
k    r|                    d          p|d         }nd}t                       t          5  t                              |t          j                              }ddd           n# 1 swxY w Y   |5  t          |          }||cddd           S 	 t          |||d         |d         |dk    rt          |          nd|t           v rt#          |          ndd|t%          ||           	  	        }nH# t&          $ r;}	t(                              d||dd         |	           Y d}	~	ddd           dS d}	~	ww xY wt          5  |t,          |<   t	          j                    t
          |<   ddd           n# 1 swxY w Y   t(                              d||dd                    |cddd           S # 1 swxY w Y   dS )u3  Lazily create and cache the sandbox env for *task_id* if none is active.

    :func:`terminal_tool` creates the environment on the first terminal command,
    but nothing else did — so under a non-local backend (ssh, docker, …) a
    session whose first action is ``vision_analyze`` on a container-only path hit
    "no active sandbox session" because the SSH/Docker handshake never ran
    (issue #62825). vision reads such paths inside the sandbox (see
    ``tools.image_source``), so it calls this to bring the env up on demand,
    reusing the same creation machinery as the terminal tool.

    No-op on the local backend (images are read host-side). Returns the env
    instance, or ``None`` when local or when creation fails (best-effort: a
    failure leaves the caller's fail-closed error path intact).
    r   rE  Nr   r  r  r  r  r  r  r  r   r  r  r  	r   rC  r  r  rD  r}  rE  r  r   z/Lazy %s environment init failed for task %s: %s   z-%s environment lazily initialized for task %s)r4  r  r  r  r[   r{  r  rC   r  r  r|  
setdefaultr   Lockrt  r@  r-  rB  r  rf   r&   r'   rz  r  )
r  r7   r   effective_task_idexistingr  rC  	task_locknew_envexcs
             r   ensure_task_envr    s]    Fj!H7t27;; /00H 	< 	<04	N,-	< 	< 	< 	< 	< 	< 	< 	< 	< 	< 	< 	< 	< 	< 	<&w//I8n--G1G	]	"	"122Qf=P6Q	W		m,,E}0E	Y		o..I&2I 
 T T#../@).BRBRSS	T T T T T T T T T T T T T T T 
 ! !!"344! ! ! ! ! ! ! !	)!5My)>F%>O>O26:::UY  #666 2&999<@!)/@@  GG  	 	 	NNA+BQB/   4441! ! ! ! ! ! ! !&	  	< 	<6= !2304	N,-	< 	< 	< 	< 	< 	< 	< 	< 	< 	< 	< 	< 	< 	< 	< 	;'+	
 	
 	
 C! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! !s   A..A25A21-E**E.1E.7J6AG87J68
H=%H8'J68H==
J6&I9-J69I=	=J6 I=	(J66J:=J:c                     t          |           }|dS t          |dd          rdS t          t          |dd                    S )u,  Return True if the active environment for task_id is configured for
    cross-turn persistence (``persistent_filesystem=True``).

    Used by the agent loop to skip per-turn teardown for backends whose whole
    point is to survive between turns (docker with ``container_persistent``,
    daytona, modal, etc.). Non-persistent backends (e.g. Morph) still get torn
    down at end-of-turn to prevent leakage. The idle reaper
    (``_cleanup_inactive_envs``) handles persistent envs once they exceed
    ``terminal.lifetime_seconds``.

    Session-scoped docker containers (per-session isolation mode) also count
    as persistent HERE: their lifetime is the SESSION, not the turn — they
    are removed by ``AIAgent.close()`` → ``cleanup_vm`` at session teardown
    and by the idle reaper, not per-turn.
    NFr_  T_persistent)r  ru   rK   )r  r  s     r   is_persistent_envr  Z  sO      
!
!C
{us%u-- t]E22333r   c                  t   t          t                                                    } d}| D ]L}	 t          |           |dz  }# t          $ r(}t
                              d||d           Y d}~Ed}~ww xY wt                      }ddl}|                    t          |dz                      D ]g}	 t          j        |d           t
                              d	|           5# t          $ r&}t
                              d
||           Y d}~`d}~ww xY w|dk    rt
                              d|           |S )z3Clean up ALL active environments. Use with caution.r   r   zError cleaning %s: %sTrY   NrW   )ignore_errorszRemoved orphaned: %sz%Failed to remove orphaned path %s: %szCleaned %d environments)r  rz  r  
cleanup_vmrf   r&   rF   r   r^   r   shutilrmtreer  rc   rd   )task_idscleanedr  rm   ri   r^   rk   s          r   cleanup_all_environmentsr  t  s   (--//00HG M M	MwqLGG 	M 	M 	MLL0'1tLLLLLLLLL	M #$$KKKK		#kJ67788 K K	KM$d3333KK.5555 	K 	K 	KLL@$JJJJJJJJ	K {{-w777Ns/   A
A5A00A521C$$
D.DDforce_remover  c                   d}t           5  t                              | d          }t                              | d           ddd           n# 1 swxY w Y   t          5  t
                              | d           ddd           n# 1 swxY w Y   	 ddlm}  ||            n# t          $ r Y nw xY w|dS 	 t          |d          rSddl
}|                    |j                  }d|j        v r|                    |           n^|                                 nIt          |d          r|                                 n$t          |d          r|                                 t                               d	|            dS # t$          $ rr}t'          |          }d
|v sd|                                v rt                               d|            n"t                               d| |           Y d}~dS Y d}~dS d}~ww xY w)u$  Manually clean up a specific environment by task_id.

    *force_remove* (default False) is forwarded to backends that accept it
    — currently only ``DockerEnvironment``. The default of False matches
    session-lifecycle semantics: this function is called from
    ``AIAgent.close()`` (TUI session close, gateway session teardown) and the
    per-turn cleanup branch for non-persistent envs, both of which should
    honor the user's persist-mode preference. Stopping the container here
    would defeat the "ONE long-lived container shared across sessions"
    contract — exactly the bug Ben reported when the container was killed
    on every TUI session close.

    Pass ``force_remove=True`` for actual user-initiated teardown
    (e.g. ``/reset``-style flows that haven't been wired yet, or future
    "destroy my sandbox" commands).

    The idle reaper passes the env through ``env.cleanup()`` directly (not
    via this function), so persist-mode idle envs are similarly no-op'd —
    only the orphan reaper at next startup reclaims them.
    Nr   rx  rz  r  r  r{  r|  z,Manually cleaned up environment for task: %sr}  r~  r  r  )r  rz  r   r{  r  r|  r  ry  r  r  rb  rc  rz  rf  r{  r|  r&   r  rf   r   r   r'   )r  r  r  ry  rb  sigrm   r  s           r   r  r    s   0 C	 * *"&&w557D)))* * * * * * * * * * * * * * *
 
 + +GT***+ + + + + + + + + + + + + + +999999W%%%%    {X3	"" 	 NNN##CK00C//6666S&!! 	HHJJJJS+&& 	MMOOOBGLLLLL X X XFF	I	0A0A!A!AKKDgNNNNNNJGUVWWWWWWWWW ONNNNNXsO   7AAABBBB% %
B21B2:CF 
G?A!G::G?c                     t                       t          rt          t                    } t                              d|            t          t                                                    }t                       |D ]W}t          |dd          }|	  |d           $# t          $ r%}t          
                    d|           Y d}~Nd}~ww xY wdS dS )zBStop cleanup thread and shut down all remaining sandboxes on exit.z)Shutting down %d remaining sandbox(es)...wait_for_cleanupNg      .@r  z#wait_for_cleanup raised on exit: %s)r  rz  r   r&   r  r  valuesr  ru   rf   rd   )rB  envs_to_waitr  wait_fnrm   s        r   _atexit_cleanupr    s
    G())?GGG 07799:: """
   	G 	GCc#5t<<GG%%%%% G G GBAFFFFFFFFG%G G	G 	Gs   B
C)C		CzSIGQUIT (quit from keyboard)uE   SIGILL (illegal instruction — corrupt binary or wrong architecture)uJ   SIGABRT (abort — assertion failure, fatal runtime error, or glibc abort)u;   SIGBUS (bus error — misaligned or unmapped memory access)z>SIGFPE (fatal arithmetic error, e.g. integer division by zero)uT   SIGKILL — often the kernel OOM killer on memory exhaustion, or an explicit kill -9u4   SIGSEGV (segmentation fault — the program crashed)uN   SIGPIPE (wrote to a closed pipe — e.g. output piped to a reader that exited)uF   SIGTERM (terminated — kill/timeout or shutdown requested it to stop)z!SIGXCPU (CPU time limit exceeded)z"SIGXFSZ (file size limit exceeded))r            r  	                  _SIGNAL_EXIT_NOTES	exit_codec                 ^   | dk     rt|  }|dk    rdS t                               |          }|rd| d| S 	 ddl}|                    |          j        }n# t
          t          f$ r d| }Y nw xY wd| d| d	S | d
k    r,| d
z
  }t                               |          }|rd|  d| d| S dS )aP  Map signal-termination exit codes to a human-readable note.

    Returns None when ``exit_code`` does not look like a signal death.
    Negative codes are Python ``subprocess`` semantics (definite); codes in
    the 128+signum band are the shell convention (very likely but not
    guaranteed, so those notes hedge with "usually").
    r   r   NzCommand terminated by signal r  zsignal zCommand terminated by z	 (signal r8     z
Exit code z4 usually means the command was terminated by signal )r  rC   signalSignalsr   r%   r  )r  signumnote_signalr   s        r   _interpret_signal_exitr  	  s)    1}}Q;;4!%%f-- 	DC6CCTCCC	&$$$$??6**/DDK( 	& 	& 	&%V%%DDD	&@@@v@@@@3S!%%f-- 	9Y 9 9(.9 9269 9
 4s   A A/.A/c                    |dk    rdS t          |          }||S t          j        d|           }|r|d         n|                                 }|                                }d}|D ]7}d|v r|                    d          s|                    d          d         } |sdS d	d
id	d
id	d
id	d
id	d
id	d
id	did	did	did	did	didddddd	did}|                    |          }	|	r||	v r|	|         S dS )a
  Return a human-readable note when a non-zero exit code is non-erroneous.

    Returns None when the exit code is 0 or genuinely signals an error.
    The note is appended to the tool result so the model doesn't waste
    turns investigating expected exit codes.
    r   Nz\s*(?:\|\||&&|[|;])\s*r3  r   r#  -r   r   zNo matches found (not an error)z%Files differ (expected, not an error)zGSome directories were inaccessible (partial results may still be valid)z5Condition evaluated to false (expected, not an error)zCould not resolve hostzFailed to connect to hostz2HTTP response code indicated error (e.g. 404, 500)zOperation timed out)r  r  r:     uL   Non-zero exit (often normal — e.g. 'git diff' returns 1 when files differ))grepegrepfgreprgagackdiff	colordiffr:  test[curlgit)r  r%  r$  rD   r   rC   )
r   r  signal_notesegmentslast_segmentwordsbase_cmdw	semanticscmd_semanticss
             r   _interpret_exit_coder  -	  s    A~~t )33K
 x17;;H$,9HRLL'@@BBL   EH  !88ALL--8773<<# t
 676767676767<=@A^_LMLM (*D%	
 
 cd1, ,I6 MM(++M (m33Y''4r   c                     d                     |                                                                           }|                    d          od|v S )au  Return True when PTY mode would break stdin-driven commands.

    Some CLIs change behavior when stdin is a TTY. In particular,
    `gh auth login --with-token` expects the token to arrive via piped stdin and
    waits for EOF; when we launch it under a PTY, `process.submit()` only sends a
    newline, so the command appears to hang forever with no visible progress.
     zgh auth loginz--with-token)rE   r   r$  r   r   
normalizeds     r   _command_requires_pipe_stdinr  |	  sL     '--////1122Jo.. 	)j(r   z=(?:^|[;&|]\s*|&&\s*|\|\|\s*|\$\(\s*)(?:nohup|disown|setsid)\bz\s&\sz\s&\s*(?:#.*)?$c                     t          |           }t          j        dd|          }t          j        dd|          }t          j        dd|          }|S )aA  Remove single- and double-quoted content so regex checks don't match inside strings.

    This prevents false positives when keywords like 'nohup' or 'setsid' appear
    in commit messages, Python -c code, echo arguments, or PR body text.
    Also strips backtick-quoted content and provably-inert heredoc body text.
    z'[^']*'z''z"(?:[^"\\]|\\.)*"z""z`[^`]*`z``)r   r%  sub)r   rT   s     r   _strip_quotesr  	  sP     (00FVJf--FV($77FVJf--FMr   z@\b(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?(?:dev|start|serve|watch)\bz\bdocker\s+compose\s+up\bz\bnext\s+dev\bz\bvite(?:\s|$)z\bnodemon\bz\buvicorn\bz\bgunicorn\bz$\bpython(?:3)?\s+-m\s+http\.server\bc                     d                     |                                                                           }d|v p-|                    d          pd|v p|                    d          S )zGReturn True for informational invocations that should never be blocked.r  z --helpz -hz
 --versionz -v)rE   r   r$  endswithr  s     r   #_looks_like_help_or_version_commandr  	  so    '--////1122JZ 	&u%%	&:%	& u%%	r   c                 4   t          |           rdS t          |           }t                              |          r	 dS t                              |          st
                              |          r	 dS t          D ]}|                    |          r	  dS dS )zSuggest background mode when a foreground command looks long-lived.

    Prevents workflows that start a server/watch process and then stall before
    follow-up checks or test commands run.
    Na	  Foreground command uses shell-level background wrappers (nohup/disown/setsid). Re-send WITHOUT the wrapper as terminal(command="<cmd>", background=true, notify_on_complete=true) so Hermes tracks the process, then run readiness checks and tests in separate commands.u   Foreground command uses '&' backgrounding. Re-send WITHOUT the '&' as terminal(command="<cmd>", background=true) — add notify_on_complete=true for bounded jobs — then run health checks and tests in follow-up terminal calls.zThis foreground command appears to start a long-lived server/watch process. Run it with background=true, verify readiness (health endpoint/log signal), then execute tests in a separate command.)r  r  _SHELL_LEVEL_BACKGROUND_REsearch_INLINE_BACKGROUND_AMP_RE_TRAILING_BACKGROUND_AMP_RE_LONG_LIVED_FOREGROUND_PATTERNS)r   unquotedpatterns      r   _foreground_background_guidancer  	  s     +733 t W%%H!((22 
5	
 	
 !''11 
5P5W5WX`5a5a 
a	
 	
 3  >>(## 	<  	 4r   notify_on_complete
backgroundc                 "    |r
| r|rd}d|fS |dfS )uK  Decide what to do when both notify_on_complete and watch_patterns are set.

    These flags produce duplicate, delayed notifications when combined — one
    notification per watch-pattern match AND one on process exit, with async
    delivery that can spam the user long after the process ends. When both are
    set, we drop watch_patterns in favor of notify_on_complete (the more useful
    "let me know when it's done" signal) and return a human-readable note.

    Returns:
        (watch_patterns_to_use, conflict_note). conflict_note is "" when there
        is no conflict.
    zuwatch_patterns ignored because notify_on_complete=True; these two flags produce duplicate notifications when combinedNr   rw   )r  watch_patternsr  r  s       r   #_resolve_notification_flag_conflictr  	  s=    $  ( ^ L 	 Tz2r   )r   r   r2  c                     | r| S t          |          }|r7|t          v r.t          |          rt                              d|||           |S |p|S )u  Return the cwd for a command. Explicit ``workdir=`` overrides everything.

    Otherwise the session's own cwd RECORD (``get_session_cwd``) wins — it is
    written after every completed command for this session, so it IS the
    session's ``cd`` state, with no shared-env ambiguity: another session's
    ``cd`` lands in another record and can't affect us. A session with no
    record yet (first command) runs in ``default_cwd`` (config/override cwd),
    which is also what seeds a fresh environment.

    ``env_type`` makes the record container-aware: on container backends a
    recorded HOST path (a desktop/TUI surface registering its host workspace
    via ``register_task_env_overrides`` → ``record_session_cwd``) is unusable
    inside the sandbox — the shell prefixes every command with ``cd <host
    path>`` and fails with exit 126. Same guard class as the env-creation
    sanitizers (#50636, #54447); this is the per-command sibling site.
    zmIgnoring recorded session cwd %r for %s backend (host/relative path won't work in sandbox). Using %r instead.)r  r-  r  r&   r  )r   r2  r   r   recordeds        r   _resolve_command_cwdr  
  sz    .  {++H
+++&x00 , 	Lh	
 	
 	

 "{"r   
session_idr   ptyr  c
                 &  ijk 	 t          | t                    s]t                              dt	          |           j                   t          j        dddt	          |           j         ddd          S t                      }
|
d	         }t          |          }t          |          }|d
k    r|                    d          p|
d         }nn|dk    r|                    d          p|
d         }nJ|dk    r|                    d          p|
d         }n&|dk    r|                    d          p|
d         }nd}|                    d          pt          |          p|
d         }t          |
|          }|t          v r@t          |          r1|rdn|
d         }||k    rt                              d|||           |}|
d         }||dk    rt#          d| d          S |p|}|s(|r&|t$          k    rt#          d| dt$           d          S |s,t'          |           }|rt          j        dd|ddd          S t)                       djt*          5  |t,          v r|n|r|t,          v r|nd}|+t/          j                    t0          |<   t,          |         jd}nd}ddd           n# 1 swxY w Y   |r.t2          5  |t4          vrt7          j                    t4          |<   t4          |         }ddd           n# 1 swxY w Y   |5  t*          5  |t,          v r|n|r|t,          v r|nd}|*t/          j                    t0          |<   t,          |         jd}ddd           n# 1 swxY w Y   |r\|dk    rt;                       t                              d||dd                    	 |d k    rt=          |
          nd}|t          v rt?          |
          nd}d}|d!k    rd"|
                    d#d          i}tA          |||||||||$	  	        }nO# tB          $ rB}t          j        ddtE          d%| d&          d'dd          cY d}~cddd           S d}~ww xY wt*          5  |t,          |<   t/          j                    t0          |<   |jddd           n# 1 swxY w Y   t                              d(||dd                    ddd           n# 1 swxY w Y   jJ dd)l#m$}  |d*          p|pd}tJ          j&                            d+          d,k    rdd-l'm(im)}m*}   | |           rt          j        dd.d/ddd          S t          |          }!|!tW          jdd          p|}!tY          ||!||0          kd1t          d2tZ          t                   fijkfd3}" || k|"4          rt          j        dd.d5ddd          S |r]t]          |          }#|#rLt                              d6|dd7         t_          |                      t          j        dd|#d8dd          S |d!k    rzdd9l0m1}$m2}% tY          |||:          k |%            r |$| k          nd;\  }&}'|&rCt                              d<t_          |                      t          j        dd.|'d8dd          S d}(tg          |          })|suti          | |tk          |
          =          }*|*d>         s|*                    d?          d@k    rt          j        dddd@d|*                    dA|           |*                    dBdC          |*                    dDd          |*                    dEd          |*                    dFd          dG
d          S |*                    dBdC          }+dH|+ dI},t          j        dd|*                    dJ|,          d8dd          S |*                    dK          r|*                    dBdL          }+dM|+ dN}(d})n1|*                    dO          r|*                    dBdL          }+dP|+ dQ}(d}-|}.|rtm          |           rd}.dR}-|rddSl7m8}/ tY          ||||0          }0	 |d!k    r3|/9                    | |0||tu          jdT          rjj;        nd|.U          }1n|/<                    j| |0||V          }1dW|1j=        |1j>        dddX}2|(r|(|2dY<   |-r|-|2dZ<   |r	|s|	sd[|2d\<   |rG| rEd]| v pd^| v }3d_| v pd`| v pda| v }4db| v p|3o|4}5|5r'|2                    d\d          }6dc}7|6r|6ddz   |7z   n|7|2d\<   |r|s|	rddel?m@}8mA}9  |8            s/d}d}	d|2df<   dg|2dh<   t                              di|1j=                   n |9djd          }:|:rw |9dkd          }; |9dld          }< |9dmd          }= |9dnd          }> |9dod          }?|:|1_B        |;|1_C        |=|1_D        |>|1_E        |<|1_F        |?|1_G         |9dpd          |1_H        t          tg          |          |	tg          |          q          \  }	}@|@r&t                              dr|1j=        |@           |@|2ds<   |rj|rhd|1_J        d|2df<   |1jB        rUdt|1_K        |/jL        M                    |1j=        dt||1jB        |1jC        |1jD        |1jE        |1jF        |1jG        d|1jH        du           |	r |rt          |	          |1_O        |1jO        |2dv<   t          j        |2d          S # t          $ r4}t          j        ddtE          dw|           dxd          cY d}~S d}~ww xY wdy}Ad}Bd}Cd}D|)rddzlQmR}E  |E             |B|Ak    rs	 tY          ||||0          }D||Ddd{}F jjS        | fi |F}CnH# t          $ r:}t          |          T                                }Gd|Gv r#t          j        dd|d}| d~dxd          cY d}~S |B|Ak     rd|Bd.z  }Bd|Bz  }Ht                              d|H|B|At_          |           t	          |          j        |||	  	         t/          jU        |H           Y d}~t          V                    d|At_          |           t	          |          j        |||           t          j        ddtE          dt	          |          j         d|           dxd          cY d}~S d}~ww xY w	 |s6|Cpi                     d          rt          |tW          jdd                     |C                    dd          }I|C                    dd          }J|C                    d          }K|C                    d          }Lt          |I|          }It          |I          }Mt          | |I          }N|Nr&t                      du}O|Ost          d          r|Idz  }I	 ddl]m^}P  |Pd| |I|J|pd|          }Q|QD ]}Rt          |Rt                    r|R}I nn# t          $ r Y nw xY wddl_m`}S  |S            }Tt          |I          |Tk    r[t          |Tdz            }U|T|Uz
  }Vt          |I          |Uz
  |Vz
  }Wd|W dt          |I           d}X|Id|U         |Xz   |I|V d         z   }Iddlcmd}Y  |Y|I          }Iddlemf}Z |Ir |Z|Ig                                |           nd}It          | |J          }[d}\|Jdk    r)|[s'	 ddlimj}]  |]| |J|I          }\n># t          $ r d}\Y n0w xY w|Jdk    r&	 ddlimk}^  |^| |I          }\n# t          $ r d}\Y nw xY w|I|Jddx}_	 |Cpi                     d          rtW          jdd          nd}`|`rn|DrltJ          jl        m                    t          |`                    tJ          jl        m                    t          |D                    k    rt          |`          |_d<   n# t          $ r Y nw xY w|Lr	 t          |L          }a|ao                    dd          }bddlpmq}c  |c|a |Z |Y|b          |           ddd           |K|_d<   |L|_d<   d|Kdd|L d|_d<   n_# t          $ rR t          r                    dd           	 t          |L          s                                 n# t          $ r Y nw xY wY nw xY w	 ddlumv}d  |d| |D|p|p|pd|J|I          }e|erV|e                    d?          |e                    d          |e                    d          |e                    d          d|_d<   n,# t          $ r t          r                    dd           Y nw xY w|(r+|Jdk    r d|Iv r|(w                    d          dz   |_dY<   n|(|_dY<   |[r|[|_d<   |\r|\|_d\<   |Mrd|_d<   |Nrd|_d<   t          j        |_d          S # t          $ rF}tK          jy        dd          g                                T                                }f|fdk    rqddlz}g|g{                                }ht          V                    d|h           t          j        ddtE          d|           tE          |h          ddd          cY d}~S t                              d|j|                   	 t          |           n,# t          $ r t          r                    dd           Y nw xY wt          j        ddd|j|        |j~        d|j|         dd          cY d}~S d}~wt          $ rv}ddlz}g|g{                                }ht          V                    d|h           t          j        ddtE          d|           tE          |h          ddd          cY d}~S d}~ww xY w)u|  
    Execute a command in the configured terminal environment.

    Args:
        command: The command to execute
        background: Whether to run in background (default: False)
        timeout: Command timeout in seconds (default: from config)
        task_id: Unique identifier for environment isolation (optional)
        session_id: Conversation/session identifier for durable observability
        force: If True, skip dangerous command check (use after user confirms)
        workdir: Working directory for this command (optional, uses session cwd if not set)
        pty: If True, use pseudo-terminal for interactive CLI tools (local backend only)
        notify_on_complete: If True and background=True, you'll be notified exactly once when the process exits. The right choice for almost every long task. MUTUALLY EXCLUSIVE with watch_patterns.
        watch_patterns: List of strings to watch for in background output. HARD rate limit: 1 notification per 15s per process. After 3 strike windows in a row, watch_patterns is disabled and the session is auto-promoted to notify_on_complete. Use ONLY for rare, one-shot mid-process signals on long-lived processes (server readiness, migration-done markers). NEVER use in loops/batch jobs — error patterns there will hit the strike limit and get disabled. MUTUALLY EXCLUSIVE with notify_on_complete — set one, not both.

    Returns:
        str: JSON string with output, exit_code, and error fields

    Examples:
        # Execute a simple command
        >>> result = terminal_tool(command="ls -la /tmp")

        # Run a background task
        >>> result = terminal_tool(command="python server.py", background=True)

        # With custom timeout
        >>> result = terminal_tool(command="long_task.sh", timeout=300)
        
        # Force run after user confirmation
        # Note: force parameter is internal only, not exposed to model API
    z+Rejected invalid terminal command value: %sr   r3  z&Invalid command: expected string, got rF   )r   r  rF   statusF)ensure_asciir   r   r  r  r  r  r  r  r  r  r  zbRemapping host/relative cwd override %r for %s backend (won't exist in sandbox). Using %r instead.r  Nr   z2timeout must be a positive number of seconds (got z).zForeground timeout zs exceeds the maximum of zNs. Use background=true with notify_on_complete=true for long-running commands.Tz*Creating new %s environment for task %s...r  r  rE  r>  r   r  z5Terminal tool disabled: environment creation failed (r8  disabledz %s environment ready for task %s)get_current_session_key)r   _HERMES_GATEWAYr  )_MAX_REFERENCED_SCRIPT_BYTES7contains_gateway_lifecycle_command_or_referenced_script!contains_launchctl_submit_commandr   zBlocked: launchctl submit/bootstrap registers a persistent KeepAlive job and is unsafe from inside the gateway process. Use Hermes cron for one-shot delayed work, or install an explicit LaunchAgent from a separate shell.)r   r2  r   r   script_pathr
   c                    dS 	 t          |                                           }|                                st                    |z  }|                                r||                                }t	          j        |j                  rO|j        k    rD|                                }t          |          k    rd|v rdS |
                    dd          S n# t          $ r Y nw xY w	                     ddz    dt          j        |                      }|                    d	d
          dk    r |                    dd          }|rd|v rdS |S n# t          $ r Y nw xY wdS )aT  Best-effort script read; uses env.execute only when local read fails.

                For local backends the script path is on the host filesystem. For
                SSH/Modal/Daytona the same path is remote; the local read misses, so we
                fall back to a bounded ``env.execute('head -c ... < path')`` read.
                N    r   r   r   zhead -c r   z < rM  r3  r   r   r    )r   r  is_absoluter`   ra   S_ISREGst_moderb   
read_bytesr   r   rf   executeshlexquoterC   )	r  
local_pathmetadatadatarT   r   r  r  	guard_cwds	         r   _read_script_in_envz*terminal_tool.<locals>._read_script_in_envD  s    ;4!%k!2!2!=!=!?!?J%1133 B%))__z%A
!))++ N#-??#4#4<(899 Nh>NRn>n>n#-#8#8#:#:D"4yy,HHH#*d?? ,04'+{{79{'M'M M    D [[8#?!#C 8 8"[558 8 F zz,33q88!'Hb!9!9! (f&6&6 $(4% 9 !   Dts1   B>C C 
C,+C,0A&E E 
E('E()r  read_remote_scripta  Blocked: command or referenced script cannot restart or stop the gateway from inside the gateway process. The gateway would kill this command before it could complete (SIGTERM propagates to child processes). Run `hermes gateway restart` from a separate shell outside the running gateway.z+Blocked dangerous workdir: %s (command: %s)r  blocked)detect_self_repo_git_mutationguard_active)r   r2  r   )FNz,Blocked self-repo git mutation (command: %s))r   approvedr  pending_approvalr   descriptionzcommand flaggedpattern_keysmart_deniedallow_permanent)
r   r  rF   r  approval_pendingr   r$  r%  r&  r'  zCommand denied: z?. Use the approval prompt to allow it, or rephrase the command.rq  user_approvedzflagged as dangerouszCommand required approval (z) and was approved by the user.smart_approvedzCommand was flagged (z&) and auto-approved by smart approval.zPTY disabled for this command because it expects piped stdin/EOF (for example gh auth login --with-token). For local background processes, call process(action='close') after writing so it receives EOF.rv  r  )r   r  r  r   env_varsuse_pty)r  r   r  r  r   zBackground process started)r   r  pidr  rF   rz   pty_noteu  background=true without notify_on_complete=true means this process runs SILENTLY — you will not be told when it exits. If this is a bounded task (test suite, build, CI poller, deploy, anything with a defined end), you almost certainly wanted notify_on_complete=true so the system pings you on exit. Re-launch with notify_on_complete=true, or call process(action='poll') / process(action='wait') yourself to learn the outcome. Only ignore this hint for genuine long-lived processes that never exit (servers, watchers, daemons).hintz
gh pr viewzgh pr checksz jq z| jqz$(jqstatusCheckRollupuR  This looks like a homebrewed CI poller built from `gh pr view --json statusCheckRollup` and/or `gh pr checks | jq`. That shape has burned us repeatedly in hermes-agent dev work (PRs #31329, #31448, #31695, #31709, #31745, #32264, #33131) — stdout buffering kills output capture, jq null-key edge cases silently exit the loop, conclusion-vs-status field confusion exits early with bogus all-green verdicts, TTY-only summary banners never appear when piped. Use the canonical snippets in the green-ci-policy skill instead: the exit-code-driven `gh pr checks $PR >/dev/null` (rc 0 = green, 8 = pending, else fail) for exit-on-first-fail behavior, or the column-2 awk-on-tabs poller (`awk -F"\t" "$2==\"pending\""`) for sharded matrices. Load skill_view(name='github/hermes-agent-dev', file_path='references/green-ci-policy.md') for the verbatim snippets. If you must roll a custom loop with rich structured output, write each tick to a known file (`tee -a /tmp/ci.log`) and rely on `process(action='log')` to read THAT file — do not rely on background-process stdout capture for line-buffered shell loops.z

)async_delivery_supportedr   r  u\  notify_on_complete / watch_patterns are not available in this session — it cannot receive an async completion after the turn ends (a one-shot runner such as `hermes -z`, a cron job, a Kanban worker, or a stateless HTTP endpoint). The process is running in the background; retrieve its result with process(action='poll') or process(action='wait').notify_unsupportedzjbackground proc %s: async delivery unsupported on this session; notify_on_complete/watch_patterns disabledHERMES_SESSION_PLATFORMHERMES_SESSION_CHAT_IDHERMES_SESSION_THREAD_IDHERMES_SESSION_USER_IDHERMES_SESSION_USER_NAMEHERMES_SESSION_MESSAGE_IDHERMES_SESSION_ID)r  r  r  zbackground proc %s: %swatch_patterns_ignoredr  )r  check_intervalr   r   chat_iduser_id	user_name	thread_id
message_idr  parent_session_idr  z$Failed to start background process: )r   r  rF   r   )clear_current_thread_interrupt)r  r  bounded_capture|   zCommand timed out after z secondsr   zfExecution error, retrying in %ds (attempt %d/%d) - Command: %s - Error: %s: %s - Task: %s, Backend: %szWExecution failed after %d retries - Command: %s - Error: %s: %s - Task: %s, Backend: %szCommand execution failed: r  cwd_observedr   rM  output_total_charsfull_output_pathrj  uu   

⚠️ Sudo authentication failed — cached password cleared. You will be prompted again on the next sudo command.)invoke_hooktransform_terminal_output)r   r   rM  r  r   )get_max_bytesg?z

... [OUTPUT TRUNCATED - z chars omitted out of z total] ...

)
strip_ansi)redact_terminal_output)annotate_failure)annotate_masked_successr   r   )encodingr   )write_text_exclusive)private	overwriter   zCOutput exceeded the capture window (head+tail shown). Full output (,z chars) saved to u]    — search it with search_files or page it with read_file instead of re-running the command.truncation_notez-spill redaction failed; dropping spill handlerY   )record_terminal_resultr   )r   r  r  r  r   kindr   canonical_command)r  rV  r   rW  verification_evidencez&verification evidence recording failed   z[Command interrupted].z, then interrupted.exit_code_meaningsudo_auth_failedsudo_cache_clearedTERMINAL_DEGRADED_MODEwarnfailzterminal_tool exception:
%szFailed to execute command: )r   r  rF   	tracebackr  zterminal backend degraded: %szdegraded-env eviction faileddegradedzTerminal backend degraded: )r   r  r  reason
retry_hintrF   )r   r   r&   r'   r  r  r  dumpsr4  r  r  rC   r  r  r-  r  r  r   FOREGROUND_MAX_TIMEOUTr  r  r  rz  r[   r{  r  r|  r   r  rp   r@  rB  rt  r  r   tools.approvalr	  r"   r   cron.lifecycle_guardr  r  r  ru   r  r   r   r   tools.self_repo_guardr   r!  rK   r   r   r  r  rw  spawn_localr  r  spawn_via_envr   r-  r   r1  r   watcher_platformwatcher_chat_idwatcher_user_idwatcher_user_namewatcher_thread_idwatcher_message_idrA  r  r  watcher_intervalpending_watchersr   r  r  rf   tools.interruptrB  r  r   r  rF   r  r   r   r   rx   r   hermes_cli.lifecyclerH  tools.tool_output_limitsrJ  r   r  tools.ansi_striprK  r   rL  rD   r  tools.terminal_hintsrM  rN  rk   realpathr   	read_texttools.spill_safetyrP  rd   unlinkrc   agent.verification_evidencerU  rstriprr  r#   ra  
format_excrc  _evict_environment_for_taskrd  )lr   r  r  r  r  r   r   r  r  r  r7   r   r  r  rC  r  r   remappeddefault_timeouteffective_timeoutguidance_existing_keyneeds_creationr  rD  r}  rE  r  rm   r	  r   r  r  guard_cwd_baser  workdir_errorr   r!  _self_repo_hit_self_repo_msgapproval_note_approved_runrz   descfallback_msgpty_disabled_reasoneffective_ptyrw  effective_cwdproc_sessionresult_data_gh_has_jq
_bad_shaper  canonical_hint	_async_ok_gse_gw_platform_gw_chat_id_gw_thread_id_gw_user_id_gw_user_name_gw_message_idconflict_notemax_retriesretry_countrT   command_cwdrB  execute_kwargsr  	wait_timer   rM  spill_total_charsspill_file_pathr\  r]  rn  rH  hook_resultshook_resultrJ  MAX_OUTPUT_CHARS
head_chars
tail_charsomittedtruncated_noticerK  rL  	exit_notefailure_hintrM  rN  result_dictpost_cwd_sp	raw_spillrP  rU  evidencedegraded_modera  tb_strr  r  r  sl                                                                                                            @@@r   terminal_toolr  ,
  s0   V@'3'' 
	#NN=W&   :Z$w--BXZZ!	 
 "# # # # !""*% 7w?? +733	 xMM.11KVN5KEE&&MM"566U&AT:UEE  MM-00IF=4IEE""MM/22Mf_6MEEEmmE""Oog&>&>O&- *&':: ***/I#/N/N*'/B||VE]HhB8  
 C + 7a<<PWPPP   $6  	g 	'4J*J*JFg F F)F F F    	'6w??H 'z !#%%	# #
 !&' ' ' ' 	  	& 	& &7:N%N%N!!!(VW8L-L-LggRV  (04	}-*=9!&!%	& 	& 	& 	& 	& 	& 	& 	& 	& 	& 	& 	& 	& 	& 	&"  =	e% ? ?$O;;9B9I9IO$56+,=>	? ? ? ? ? ? ? ? ? ? ? ? ? ? ?
  6e 6e / /->BV-V-V)))0^W@T5T5TggZ^ " %08<	}52=A)./ / / / / / / / / / / / / / / " *e=001333KK LhXijlkljlXmnnn /HPTYHYHY%<V%D%D%D_c
  (+>>> :&AAADH )
 (,#w.. ,fjj9KU.S.S,L #6%-"' #$5'1-=)5$5%-
# 
# 
# ' / / /#z&()+%@ \XY \ \ \& & '1+ + ). /  /  / / / / / /S6e 6e 6e 6e 6e 6e 6e 6eP/ # & &BI,->?<@IKK'89%& & & & & & & & & & & & & & & KK BHN_`bab`bNcdddm6e 6e 6e 6e 6e 6e 6e 6e 6e 6e 6e 6e 6e 6e 6ep  	;:::::--b999Lgm :>>+,,33         
 1099 'z !"F
 &
# 
# !&
' 
' 
' 
' -[99N%!(eT!:!:!Ac,*'!	  I5 5# 5 5 5 5 5 5 5 5n GF#6   '
 z !"F &# # !&' ' ' '  
	'-g66M 'L&tt}.CG.L.LN N Nz !#*'	# #
 !&' ' ' ' w       
 -'  I  <>>#--gyAAA" +NN
  
'B)'22   z !"+'	# #
 !&' ' ' ' 
 U '	e( 7 ? ?  H J' '<<))-???:"$%'!#"4,0#+<<	7#C#C'/||MCT'U'U'/||M2'F'F(0^U(K(K+3<<8I4+P+P' ' %*+ + + +  ||M3DEETt T T T  z !#%\\)\BB'	# #
 !&' ' ' ' ||O,, e||M3IJJ cd c c c $.// e||M3IJJ d d d d # 	/88 	!M    j	? @?????0'!	  Mw'w&&#3#?#? ') 1$/,3C,?,?!IT - $@ $ $LL $4#A#A ') 1$/ $B $ $L ;"./'+!"!  ! <.;K
+& B.AK
+  &8  	H  'T  0' 0'72On6OC')SVw->S&GBS  ,w6 -
  OG  "  #.??62#>#>= '8 CK 0Hv->>!/ $F+  2#5 2 2        %9;; (-2*)-<A$89P $$89 R(O    (,t,Er'J'J' *.$/G*L*LK,0D1KR,P,PM*.$/G*L*LK,0D1KR,P,PM-1T2Mr-R-RN<HL9;FL8;FL8=JL:=JL:>LL; >BT 3R> >L: 1T'+,>'?'?#1#J//1 1 1-
 ! JNN#;\_m\\\<IK 89 & * 6:L38<K 45
 $4 895(9@@*6/./+6(4(E'3'C'3'C)5)G)5)G*6*I261=1OB B    " Pj P26~2F2FL/4@4OK 01z+EBBBB ' ' 'z !#8BqBB # # !&' ' ' ' ' ' ' ' '' KKFK  1JJJJJJ..000,,,+"6 '$'$/!)	# # #K $5* ,0	& 	&N )S[CCNCCFF  + + + #AI I--#z&(),%[@Q%[%[%[+ + ).	 /  /  / / / / / / / #[00#q($%$4	  (P'0+{LabiLjLjlpqrlslsl|~  BS  U]^ ^ ^
9--- LL!z!,.CG.L.LdSTggN^`actv~@ @ @:"$%'!<Pa9IPPQPP" "' ' %*+ + + + + + + + +)+: (  K"11.AA K";UD0I0IJJJ ZZ"--FL!44J !'

+? @ @$jj);<<O *&(;;F;FCC!H" " " +F+H+HPT+T(+ ?S/T/T #F<<<<<<*{/#!)-3%      $0  K!+s33 !,     ?>>>>>,}6{{--- !1C!788
-
:
f++
2Z?;7 ; ;!&kk; ; ; !  ,/??&*BVV 433333Z''F <;;;;;HNV++FLLNNGDDDTVF -WjAAI  LQy(EEEEEE#3#3GZ#P#PLL  ( ( (#'LLL(q(LLLLLL#:#:7F#K#KLL  ( ( (#'LLL( !' K 9?28J8J>8Z8Zd73t444`d 7 70@0@X0O0OSUSZScScdghsdtdtSuSu0u0u),XK&     //C #wy Q QIGGGGGG
 )(..zz)/D/DgNN $"&(    9JK 456EK 23L(9NL L*L L L   122 !   LL!P[_L```_--446666"   	VNNNNNN11##)VWV8IVY(!    "*,,x"8"8 (V 4 4!)g!6!6-5\\:M-N-N	< <K 78  V V VEPTUUUUUV < $$)@F)J)J
 /<.B.B3.G.GJ_._K
++.;K
+ =3</0 3&2F# 726./! 94801:k>>>>% % % % 	":FCCIIKKQQSSF""))++FLL7@@@ :45VST5V5VWW8@@!  "# # # # # # # # # 	6AAA	H'0000 	H 	H 	HLL7$LGGGGG	Hz h,=18==
 
    	 	 	 	 	 	    %%''3V<<< z01Rq1R1RSS4V<<
 
    	 	 	 	 	 	sz  A1AF' 7E-AF' %-AF' -AF' AF' A
J."AF' .J22AF' 5J26AF' 2L5AF' LAF' L	AF' SAM)S)M-	-S0M-	1>S0A)PS
Q&$+Q!Q&SAF' !Q&&
S0(R$S$R(	(S+R(	,'SAF' S##AF' &S#'A/AF' B AF' AAF' 7A?AF' 7CAF' A
AF' BAF' 6Jl 
m)l=7m8AF' =m$AF' ''n AF' sAssAF' #A%sAF' A=s
sAF' sC)AF' ?7w7 6AF' 7
xAF' xCAF' {- ,AF' -{<9AF' ;{<<	AF' | AF' |(%AF' '|((	AF' 2B AF' 
AF' AF'  A&AA AAF' A&AB#A.!ABBAB#B
ABBAB#BABBAB#B AF' B"AB#B#AF' B'A4AD DAF' D&AEEAF' EAEEA!AF' F'AM6F2B*AK3IAM6I" AK3JAJJAK3J&AJ<J9AK3J;AJ<J<1AK3K-AM6K3AM6L A+AM1M+AM6M1AM6c                    t          |           h}| r|                    |            g }t          5  |D ]O}t                              |d          }t
                              |d           ||                    |           P	 ddd           n# 1 swxY w Y   |D ]C}	 |                                 # t          $ r t          
                    dd           Y @w xY wdS )a  Drop any cached environment for *task_id* (and its collapsed key).

    Used when a backend reports an infrastructure failure: keeping the dead
    env cached would make every subsequent call fail against a stale
    connection, defeating automatic recovery.
    Nz&cleanup of degraded environment failedTrY   )r  r  r  rz  r   r{  r   rz  rf   r&   rd   )r  r  evictedr  r  s        r   r  r  Z  sU    'w//0D G	 $ $ 	$ 	$C&**355CsD)))s###		$$ $ $ $ $ $ $ $ $ $ $ $ $ $ $  R R	RKKMMMM 	R 	R 	RLLADLQQQQQ	RR Rs$   ABBB!B66&CCc                  l   	 t                      } | d         }|dk    rdS |dk    r]ddlm}  |            }|st                              d           dS t          j        |d	gdd
t
          j                  }|j        dk    S |dk    r[t          j
        d          pt          j
        d          }|r/t          j        |dgdd
t
          j                  }|j        dk    S dS |dk    rH|                     d          r|                     d          st                              d           dS dS |dk    rwt          |                     d                    }|d         dk    rdS |d         dk    r|d         r*t                              dt          d                     dS |d         dk    r*t                              dt          d                     dS |d         dk    rEt                      rt                              d           nt                              d           dS t                      rt                              d           nt                              d            dS t          j                            d          t                              d"           dS dS |d#k    rt%          |           S |d$k    rdd%lm} dd&lm}  |d'          d!uS t                              d(|           dS # t.          $ r(}	t                              d)|	d*           Y d!}	~	dS d!}	~	ww xY w)+z8Check if all requirements for the terminal tool are met.r   rE  Tr   r   )find_dockerz?Docker executable not found in PATH or common install locationsFversionr  )capture_outputr  rG  r  	apptainerz	--versionr  r  r  zSSH backend selected but TERMINAL_SSH_HOST and TERMINAL_SSH_USER are not both set. Configure both or switch TERMINAL_ENV to 'local'.r  r  rS  rT  rV  rW  zModal backend selected with TERMINAL_MODAL_MODE=managed, but Nous Tool Gateway access is not currently available and no direct Modal credentials/config were found. %s Choose TERMINAL_MODAL_MODE=direct/auto to use direct Modal credentials.rX  rY  zhModal backend selected with TERMINAL_MODAL_MODE=managed, but the managed tool gateway is unavailable. %szModal backend selected with TERMINAL_MODAL_MODE=direct, but no direct Modal credentials/config were found. Configure Modal or choose TERMINAL_MODAL_MODE=managed/auto.zModal backend selected with TERMINAL_MODAL_MODE=direct, but no direct Modal credentials/config were found. Configure Modal or choose TERMINAL_MODAL_MODE=auto.zModal backend selected but no direct Modal credentials/config or managed tool gateway was found. Configure Modal, set up the managed gateway, or choose a different TERMINAL_ENV.z|Modal backend selected but no direct Modal credentials/config was found. Configure Modal or choose a different TERMINAL_ENV.NzFmodal is required for direct modal terminal backend: pip install modalr  r  )Daytonar=   DAYTONA_API_KEYzgUnknown TERMINAL_ENV '%s'. Use one of: local, docker, singularity, modal, daytona, vercel_sandbox, ssh.z&Terminal requirements check failed: %srY   )r4  r  r  r&   rF   rJ  rK  rL  rM  r  whichrC   r8  r   r   rG   rH   rI   rR   r  r  rJ   r>   rf   )
r7   r   r  r   rT   
executablerp  r  r>   rm   s
             r   check_terminal_requirementsr  r  s   m ""*%w4!!====== []]F ^___u^VY$7VW_i_qrrrF$))&&k22Qfl=6Q6QJ .#[(ARV`aisi{|||(A--5::j)) J1G1G Z   u4  26::l3K3KLLK-.);;t-.(::56 
!LL[ >5    !5v&)33LL:=5    !5 (H44133 @    8  
 !5133 
B    R   !5~''008efffu4)))5f===""''''''555555:/00<< LL7  
 5   =q4PPPuuuuush   L 2L .L AL $A
L 25L )<L '4L AL .AL 39L 0L L $L 
L3L..L3__main__zTerminal Tool Modulez2==================================================z
Current Configuration:z  Environment type: z  Docker image: r  z  Modal image: r  z  Working directory: z  Default timeout: sz  Lifetime: u;   
❌ Requirements not met. Please check the messages above.r   u   
✅ All requirements met!z
Available Tool:z=  - terminal_tool: Execute commands in sandboxed environmentsz
Usage Examples:z  # Execute a commandz*  result = terminal_tool(command='ls -la')z  z  # Run a background taskzE  result = terminal_tool(command='python server.py', background=True)z
Environment Variables:r  z  TERMINAL_ENV: rD  rE  z< (local/docker/singularity/modal/daytona/vercel_sandbox/ssh)z  TERMINAL_DOCKER_IMAGE: r  z  TERMINAL_SINGULARITY_IMAGE: r  r  z  TERMINAL_MODAL_IMAGE: r	  z  TERMINAL_DAYTONA_IMAGE: r
  z  TERMINAL_CWD: r  r   z  TERMINAL_SANDBOX_DIR: TERMINAL_SANDBOX_DIRz
/sandboxesz  TERMINAL_TIMEOUT: r  60z  TERMINAL_LIFETIME_SECONDS: r  r  )registryr  objectstringz The command to execute on the VM)r  r$  booleanu0  Run in the background, returning a session_id. Pair with notify_on_complete=true for anything with a defined end (tests, builds, deploys) — without it the process runs silently. Only servers/watchers/daemons that never exit should stay silent. Short commands: prefer foreground with a generous timeout.)r  r$  r   z3Max seconds to wait (default: 180, foreground max: u   ). Returns INSTANTLY when command finishes — set high for long tasks, you won't wait unnecessarily. Foreground timeout above z7s is rejected; use background=true for longer commands.)r  r$  minimumz^Working directory for this command (absolute path). Defaults to the session working directory.zRun in pseudo-terminal (PTY) mode for interactive CLI tools like Codex, Claude Code, or Python REPL. Only works with local and SSH backends. Default: false.u   With background=true: get exactly one notification when the process exits. The right choice for nearly every bounded long task — set it and keep working. MUTUALLY EXCLUSIVE with watch_patterns (watch_patterns is dropped when both are set).arrayr  u  Strings to watch for in background output. ONLY for rare one-shot mid-process signals on processes that never exit (e.g. ['Application startup complete'] on a server). NOT for end-of-run markers (use notify_on_complete) and NOT for per-iteration patterns like 'ERROR' in loops — rate-limited to 1 notification/15s; repeated over-firing auto-disables it and falls back to notify-on-exit. When in doubt, use notify_on_complete. MUTUALLY EXCLUSIVE with notify_on_complete.)r  r  r$  )r   r  r  r   r  r  r  )r  
propertiesrequired)r   r$  rf  c                    d| vrd| v rt          d          S t          |                     d          |                     dd          |                     d          |                    d          |                    d          |                     d	          |                     d
d          |                     dd          |                     d          	  	        S )Nr   codezterminal received a 'code' parameter, but it requires a shell command in 'command'. Use execute_code(code=...) for Python; for shell, retry as terminal(command=...).r  Fr  r  r  r   r  r  r  )	r   r  r  r  r  r   r  r  r  )r   r  rC   )argskws     r   _handle_terminalr  E  s     49
 
 	

 ##88L%00##y!!66,''##HHUE""88$8%@@xx 011
 
 
 
r   u   💻i )r   toolsetschemahandlercheck_fnemojimax_result_size_chars)r
   N)F)r   )r  )NNNr   N)r  r4   )	FNNNFNFFN)__doc__importlib.utilrG   r  loggingr"   r   r%  r  ra   r[   r   atexitr  rJ  pathlibr   typingr   r   r   r   utilsr   	getLoggerr  r&   r   r   rt  r   r   tools.registryr   tools.shell_heredocr   tools.environments.singularityr   tools.tool_backend_helpersr   r   r   r   r   r+   r  rf  r*  re   r,  r5   rK   r6   r  rR   rU   __annotations__r]   rp   rq   r  r   rE  rv   rx   r{   r   r   r   r   r   r   rg  r   r   r   r   r   	frozensetr   r   r   r   r   r   r   r  r   r(  tupler0  r@  r   rP  rg  rq  tools.environments.baserr  tools.environments.localrs  r]  rt  ra  tools.environments.sshru  rk  r  rv  r^  tools.environments.modalrw  rh   tools.environments.managed_modalrx  rg  tools.managed_tool_gatewayry  r  TERMINAL_TOOL_DESCRIPTIONrz  r{  r  r|  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r-  r  r  r  r4  r  r8  r@  rB  rt  r  r  r  r  r  r  r  r  r  r  registerr  r  r  r  compile
IGNORECASE	MULTILINEr  r  r  r  r  r  r  r  r  r  r  r  r  r7   exitdefault_imgr#   r   r   r   r  TERMINAL_SCHEMAr  rw   r   r   <module>r     s       D       				  				                    , , , , , , , , , , , , ! ! ! ! ! !		8	$	$Rs Rs R R R R = < < < < < < < % % % % % % : : : : : : < ; ; ; ; ;             
 	   8 0/%	   #9"8			# #  0 ? @# @$ @ @ @ @7tCH~ 7$ 7 7 7 7x ),u== 4 = = = & & &^ (* d38n ) ) )*IN,,   	!!9 9 94 4 4% % %     - - - - -,33 3 3 3 32 2 2 2 2 2% % % %     
	s 	t 	 	 	 	_DcN _t _ _ _ _ /4C Cs Cc C'+C8<C C C C  &Io66 ;c ;d ; ; ; ;s sTz    &      6  M M M M M M4Z!$	   (z3 z3s z3C z3 z3 z3 z3x	- 	-3 	-s 	-S 	- 	- 	- 	-=c =d = = = =!s !3 !5c? ! ! ! !H=$C =$E#s(O =$ =$ =$ =$@5# 5# 5 5 5 5pd    4b# b# b b b bJUS4Z UE#*cDj:P4Q U U U Ur ? > > > > > J J J J J J \ \ \ \ \ \ D D D D D D M M M M M M J J J J J J ` ` ` ` ` ` D D D D D D 




  (* d38n ) ) )#%S%Z  % % %IN	-/c9>)* / / /%y~''  
 " +Y^-- >;c3h >;D >; >; >; >;R 24 T#tCH~-. 3 3 3   "d38n ! ! !"IN$$ $HSM $ $$ $ $ $ $"	%# 	%8C= 	% 	% 	% 	%,3 ,4 , , , ,% %c3h % % % %P	.c 	. 	. 	. 	.$ &( DcN ' ' '&	(( 
MC 
M# 
MSW 
M 
M 
M 
Mc c    b4 b b b b  %9 & & &   	Uhsm 	U 	U 	U 	U 	U# ## # # # #LHSM d38n    ()4S> )HSM )hWZm ) ) ) )\ >AT] 
 
 
s 
s 
c 
 
 
 
 Dc D D D D$ : i _ _ _`` C D    2 %* !,V ,V ,V ,V^Bc3h B B B BJ$ 4S>    DcN t     $sCx. T    6 KO-1'026	}
 }
# }
c }
 }
c }
$(}
CG}
&*}
 "%}
 #+3-	}
 }
 }
 }
@;\ ;\S ;\ ;\ ;\ ;\|  $ $ $  UC U U U UQ QXc] Q Q Q Qh4s 4t 4 4 4 44  6 6; AX AX AX AXd AX AX AX AXHG G G0       " 	'OTEH	!>XP+,& & DcN    c cDj    DL# L# L#* L L L L^# $     (RZDbmVXVbFb   'BJx00 (bj);<< 3 3    4 BJRTVTabbBJ+R];;BJ "-00BJ "-00BJ~r}--BJ~r}--BJ..BJ6FF	#      $S $S4Z $ $ $ $N 	
    > "&"%# %# %#c]%# %# #	%#
 sm%# 	%# %# %# %#T !! $!$*.k kkk c]k c]	k
 k k c]k 
k k T#Y'k 	k k k k\!R# R4 R R R R0oT o o o od z	E
 !!!	E(OOO_F	E
$%%%	E
5
!3
5
5666	E
5VN3
5
5666	E
3F=1
3
3444	E
1&-
1
1222	E
4y 1
4
4
4555	E
6 23
6
6
6777&&(( LMMM	E
'(((	E
	E
IJJJ	E
	E
!"""	E
6777	E$KKK	E
%&&&	E
QRRR	E
$%%%>K	E	F29^W--	F 	F 	F  
 
E
Wibi0G&U&U
W
WXXX	E
o9295QSl_jSlSl+m+m
o
oppp	E
UYRY/E{%S%S
U
UVVV	E
Yyry1I;'W'W
Y
YZZZ	E
HYRY~||~~FF
H
HIII<<<<<<	E
_YRY/E$$&&G\G\G\%]%]
_
_```	E
F+=t!D!D
F
FGGG	E
Y)")4OQV*W*W
Y
YZZZ $ # # # # # , !A 
 "  R   "  |Uk   |   |  mC   |   |   |  ! 
 "  ~   "  S # #   (+  y ;"
 "
F KK& &* *Z  2  	(
!     r   