+
    /pÐjÉ5  ã                   óˆ  a € R) t(0 t R t^ RIt^ RIt^ RIt^ RIt^ RIt^ RIt^ RIH	t	 ^ RI
HtHtHt ^ RIHt ^ RIHtHtHt ^ RIHt ]P,                  ! R4      tRR	R
R/t] ^ k RtR tR tR R ltRR/R R lltRRRR/R R lltR R ltR R lt R*R R llt!R R lt"R+R  R! llt#R" R# lt$R$ t%RR/R% R& llt&R' R( lt'R# ),a¤  Sandbox lifecycle for the terminal tool: idle reaping, teardown, manual/atexit
cleanup, and the lazy ensure_task_env bring-up. The env cache dicts and locks
stay in tools.terminal_tool (tests patch them there) and are read through it
at call time.

Split out of ``tools/terminal_tool.py``; every public/patched name is re-imported there,
so ``tools.terminal_tool.<name>`` keeps resolving (and monkeypatching) as before.
N)ÚPath)ÚAnyÚDictÚOptional)Ú_get_scratch_dir)Ú_container_config_from_configÚ_local_config_from_configÚ_ssh_config_from_config)Ú_quietztools.terminal_toolÚ	timestampg        ÚresultFg     Àr@c                  ó^   € \         P                   ! \        \        4       R ,          4      4      # )zhermes-*)ÚglobÚstrr   © ó    Ú,/opt/hermes/tools/terminal_tool_lifecycle.pyÚ_scratch_pathsr   %   s   € Ü�9Š9”SÔ)Ó+¨jÕ8Ó9Ó:Ð:r   c            	     óÆ  € ^ RI Hp  \        P                  ! 4       \        R,          ,
          \
        8  d   \        R,          #  ^ p\        4        F  p\        V4      P                  R4       F^  pVP                  4       '       g   K  \        RV\        R7      ;_uu_ 4        WP                  4       P                  ,          pRRR4       K`  	  K�  	  VR,          pW@8„  pV'       d   \        P                  RW@4       \        P                  ! 4       \        R&   V\        R&   V#   + '       g   i     KÉ  ; i  \          d    \        P#                  R	R
R7        R# i ; i)zNTrue when hermes scratch dirs exceed the warning threshold (cached, advisory).)ÚDISK_USAGE_WARNING_THRESHOLD_GBr   r   Ú*zCould not stat file %s©ÚexcNz\Disk usage (%.1fGB) exceeds threshold (%.0fGB). Consider running cleanup_all_environments().zDisk usage warning check failedT©Úexc_infoFi   @)Útools.terminal_toolr   ÚtimeÚ	monotonicÚ_disk_usage_cacheÚ_DISK_USAGE_CACHE_TTLr   r   ÚrglobÚis_filer
   ÚOSErrorÚstatÚst_sizeÚloggerÚwarningÚ	ExceptionÚdebug)r   Útotal_bytesÚpathÚfÚtotal_gbÚexceededs         r   Ú_check_disk_usage_warningr.   )   s  € åCÜ‡~‚~ÓÔ+¨KÕ8Õ8Ô;PÔPÜ  Õ*Ð*ðØˆÜ"Ö$ˆDÜ˜$“Z×%Ñ% cÖ*�Ø—9‘9—;”;ÜÐ 8¸!Ä×IÖIØ#§v¡v£x×'7Ñ'7Õ7˜÷ JÑIó +ñ %ð
  )Õ,ˆØÑ=ˆßÜ�N‰NÐyØ#ôFä)-¯ªÓ)9Ô˜+Ñ&Ø&.Ô˜(Ñ#Øˆ÷ J×IÐIûô ô ä�‰Ð6ÀˆÔFÚðús1   Á?D: Â	D: Â#!D&	ÃA!D: Ä&D7Ä1	D: Ä:"E ÅE c                ó¤   € V ^8„  d   QhR\         \        \        3,          R\        R\        R\        R\        R\        R\        \        ,          /# )é   ÚconfigÚenv_typeÚimageÚcwdÚtimeoutÚtask_idÚhost_cwd)Údictr   r   Úintr   )Úformats   "r   Ú__annotate__r;   C   sP   € ÷ ñ Ü””c��NðÜ&)ðÜ58ðÜ?BðÜMPðäðä$¤S�Mñr   c               ó°   € ^ RI Hp ^ RIHp T! YY4VR8X  d   \	        V 4      MRV! V4      '       d   \        V 4      MRVR8X  d   \        V 4      MRWVR7	      # )z­``_create_environment`` with the ssh/local/container kwargs shaped from *config*
(shared by the terminal tool, the file tools and the lazy :func:`ensure_task_env` bring-up).)Ú_create_environment)Ú_is_container_backendÚsshNÚlocal)	r2   r3   r4   r5   Ú
ssh_configÚcontainer_configÚlocal_configr6   r7   )Útools.terminal_tool_backendsr=   Útools.terminal_tool_configr>   r	   r   r   )	r1   r2   r3   r4   r5   r6   r7   r=   r>   s	   &&$$$$$  r   Ú_create_configured_envrF   C   s[   € õ AÝ@ÙØ¨CØ6>À%Ô6GÔ*¨6Ô2ÈTá5JÈ8×5TÒ5TÔ)¨&Ô1ÐZ^à:BÀgÔ:MÔ.¨vÔ6ÐSWØôð r   Úforce_removec                óJ   € V ^8„  d   QhR\         R\        \        ,          RR/# )r0   ÚenvrG   ÚreturnN)r   r   Úbool)r:   s   "r   r;   r;   V   s%   € ÷ ñ ”cð ¬H´T­Nð Àdñ r   c               ól  € \        V R4      '       dZ   VeD   R\        P                  ! V P                  4      P                  9   d   V P                  VR7       R# V P                  4        R# \        V R4      '       d   V P                  4        R# \        V R4      '       d   V P                  4        R# R# )ai  Tear down one environment via cleanup()/stop()/terminate(), whichever it has.

``force_remove`` is forwarded to ``cleanup()`` only when given and the backend's
signature accepts it (``DockerEnvironment``, issue #20561; other backends don't).
Shared by ``cleanup_vm``, the idle reaper and the prompt-time backend probe so
the signature check lives in one place.
ÚcleanupNrG   ©rG   ÚstopÚ	terminate)ÚhasattrÚinspectÚ	signaturerM   Ú
parametersrO   rP   )rI   rG   s   &$r   Ú_cleanup_envrU   V   s{   € ô ˆs�I×ÒØÒ#¨¼'×:KÒ:KÈCÏKÉKÓ:X×:cÑ:cÔ(cØ�K‰K \ˆKÖ2à�K‰KŽMÜ	��f×	Ò	Ø�‰Ž
Ü	��k×	"Ò	"Ø�‰Žñ 
#r   Údone_msgz,Cleaned up inactive environment for task: %sc          
      ób   € V ^8„  d   QhR\         R\        R\        \        ,          R\        RR/# )r0   rI   r6   rG   rV   rJ   N)r   r   r   rK   )r:   s   "r   r;   r;   i   s@   € ÷ Xñ X”sð X¤Sð X¼8ÄD½>ð XÔ\_ð Xð  VZñ Xr   c               ó.  €  \        WR7       \        P                  W14       R#   \         de   p\	        T4      pRT9   g   RTP                  4       9   d   \        P                  RT4        Rp?R# \        P                  RY4        Rp?R# Rp?ii ; i)ut   ``_cleanup_env`` plus outcome logging. A 404/"not found" error means the
sandbox is already gone â€” logged at info.rN   Ú404z	not foundz*Environment for task %s already cleaned upz-Error cleaning up environment for task %s: %sN)rU   r%   Úinfor'   r   Úlowerr&   )rI   r6   rG   rV   ÚeÚ	error_strs   &&$$  r   Ú_teardown_envr^   i   sq   € ðXÜ�SÕ4Ü�‰�HÖ&øÜô XÜ˜“Fˆ	Ø�IÔ °	·±Ó0AÔ!AÜ�K‰KÐDÀg×NÒNä�N‰NÐJÈG×WÒWûðXús   ‚!% ¥B°=BÁ3BÂBc                ó(   € V ^8„  d   QhR\         RR/# ©r0   r6   rJ   N©r   )r:   s   "r   r;   r;   w   s   € ÷ ñ ¤3ð ¨4ñ r   c                óH   €  ^ RI Hp V! V 4       R#   \         d     R# i ; i)zZInvalidate the file_ops cache entry so ShellFileOperations can't reference a dead sandbox.)Úclear_file_ops_cacheN)Útools.file_toolsrc   ÚImportError)r6   rc   s   & r   Ú_clear_file_ops_cacherf   w   s$   € ðÝ9Ù˜WÖ%øÜô Úðús   ‚ ’! !c                ó$   € V ^8„  d   QhR\         /# ©r0   r6   ra   )r:   s   "r   r;   r;   €   s   € ÷ ñ œSñ r   c                ó(  € ^ RI HpHpHpHpHp V;_uu_ 4        VP                  V R4      pVP                  V R4       RRR4       V;_uu_ 4        VP                  V R4       RRR4       X#   + '       g   i     L7; i  + '       g   i     X# ; i)uò   Pop *task_id* from the env cache, activity map and creation locks; return
the env (or None). Callers run the (slow) teardown OUTSIDE the lock â€”
Modal/Docker teardown can block 10-15s and would stall every concurrent
terminal/file tool call.©Ú_active_environmentsÚ_creation_locksÚ_creation_locks_lockÚ	_env_lockÚ_last_activityN)r   rk   rl   rm   rn   ro   Úpop)r6   rk   rl   rm   rn   ro   rI   s   &      r   Ú_unregister_envrq   €   sr   € ÷
õ ÷ 
ŠØ"×&Ñ& w°Ó5ˆØ×Ñ˜7 DÔ)÷ 
÷ 
Ò	Ø×Ñ˜G TÔ*÷ 
à€J÷ 
�ú÷ 
Ö	à€Jús   ™%A-ÁB Á-A=	Â B	c                ó$   € V ^8„  d   QhR\         /# )r0   Úlifetime_seconds)r9   )r:   s   "r   r;   r;   ‘   s   € ÷ (ñ (¬Sñ (r   c           
     ó  € ^ RI HpHpHpHpHp \        P                  ! 4       p ^ RIHp \        VP                  4       4       F   pVP                  V4      '       g   K  WeV&   K"  	  T;_uu_ 4        \        VP                  4       4       U	U
u. uF  w  ršWj,
          V 8”  g   K  V	NK  	  pp	p
V U	u. uF  q™VP                  V	R4      3NK  	  pp	V F  p	VP                  V	R4       K  	  T;_uu_ 4        V F  p	VP                  V	R4       K  	  RRR4       RRR4       X F!  w  r�Vf   K  \        V4       \!        WØ4       K#  	  R#   \         d     Lïi ; iu up
p	i u up	i   + '       g   i     L]; i  + '       g   i     Lh; i)zOClean up environments that have been inactive for longer than lifetime_seconds.rj   )Úprocess_registryN)r   rk   rl   rm   rn   ro   r   Útools.process_registryru   ÚlistÚkeysÚhas_active_processesre   Úitemsrp   rf   r^   )rs   rk   rl   rm   rn   ro   Úcurrent_timeru   r6   ÚtÚlastÚstaleÚenvs_to_stoprI   s   &             r   Ú_cleanup_inactive_envsr€   ‘   sE  € ÷õ ô —9’9“;€LðÝ;Ü˜N×/Ñ/Ó1Ö2ˆGØ×4Ñ4°W×=Ô=Ø*6˜wÓ'ñ 3÷ 
ŠÜ"& ~×';Ñ';Ó'=Ô">ÔiÑ">‘w�qÀ,ÕBUÐXhÑBh—�Ñ">ˆÑiÙHMÓNÉÀ1Ð0×4Ñ4°Q¸Ó=Ó>ÉˆÐNÛˆAØ×Ñ˜q $Ö'ñ ç!Ò!Û�Ø×#Ñ# A tÖ,ñ ÷ "÷ 
ó %‰ˆØŒ?Ü! 'Ô*Ü˜#Ö'ó %øô ô Ùðüó jùÚN÷ "×!ú÷ 
�ús_   ¥6E
 Á E
 Á2E9ÂE
Â%E
Â+E9Â2E!Ã'E9Ã5E&	ÄE9Å
EÅEÅE9Å&E6Å1E9Å9F		c                ó$   € V ^8„  d   QhR\         /# rh   ra   )r:   s   "r   r;   r;   ²   s   € ÷ Uñ UœCñ Ur   c                óÌ   € ^ RI HpHpHp V! V 4      pT;_uu_ 4        VP	                  V4      ;'       g    VP	                  V 4      uuRRR4       #   + '       g   i     R# ; i)z9Return the active BaseEnvironment for *task_id*, or None.)rk   rn   Ú_resolve_container_task_idN)r   rk   rn   rƒ   Úget)r6   rk   rn   rƒ   Úlookups   &    r   Úget_active_envr†   ²   sE   € ç_Ñ_Ù'¨Ó0€Fß	ŠØ#×'Ñ'¨Ó/×TÐTÐ3G×3KÑ3KÈGÓ3T÷ 
��‹ús   �*AÁA#	c                ó:   € V ^8„  d   QhR\         \        ,          /# rh   ©r   r   )r:   s   "r   r;   r;   º   s   € ÷ ?ñ ?œX¤c�]ñ ?r   c                óê  € ^ RI HpHpHpHpHpHpHpHpH	p	H
p
Hp V! 4       pVR,          pVR8X  d   R# V! V 4      p\        V4      pVe-   V;_uu_ 4        \        P                  ! 4       Wn&   RRR4       V# V	! WÛ! V 4      V4      pV
! 4        V;_uu_ 4        VP                  V\        P                   ! 4       4      pRRR4       X;_uu_ 4        \        V4      pVe   VuuRRR4       #  \#        WÍVVR,          VR,          VV! WÀ4      R7      pT;_uu_ 4        TY&   \        P                  ! 4       Yn&   RRR4       \&        P+                  R
YÞR	,          4       TuuRRR4       #   + '       g   i     T# ; i  + '       g   i     LÇ; i  \$         d2   p\&        P)                  RYÞR	,          T4        Rp?RRR4       R# Rp?ii ; i  + '       g   i     LŸ; i  + '       g   i     R# ; i)ub  Lazily create and cache the sandbox env for *task_id* if none is active.

Lets non-terminal callers (``tools.image_source`` reading container-only
paths) bring the sandbox up on demand with the same machinery as the
terminal tool. No-op on local. Returns the env, or ``None`` when local or
when creation fails (best-effort; the caller's fail-closed path stays intact).

: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.
)rk   rl   rm   rn   Ú_get_env_configro   rƒ   Ú_resolve_task_host_cwdÚ_select_imageÚ_start_cleanup_threadÚresolve_task_overridesr2   r@   Nr4   r5   )r3   r4   r5   r6   r7   z/Lazy %s environment init failed for task %s: %s:Né   Nz-%s environment lazily initialized for task %s)r   rk   rl   rm   rn   rŠ   ro   rƒ   r‹   rŒ   r�   rŽ   r†   r   Ú
setdefaultÚ	threadingÚLockrF   r'   r%   r&   rZ   )r6   rk   rl   rm   rn   rŠ   ro   rƒ   r‹   rŒ   r�   rŽ   r1   r2   Úeffective_task_idÚexistingr3   Ú	task_lockÚnew_envr   s   &                   r   Úensure_task_envr—   º   s¢  € ÷÷ ÷ ñ ñ
 Ó€FØ�jÕ!€HØ�7ÔÙá2°7Ó;ÐäÐ/Ó0€HØÒßŠYÜ04·	²	³ˆNÑ-÷ àˆá˜(Ð$:¸7Ó$CÀVÓL€EáÔç	Ò	Ø#×.Ñ.Ð/@Ä)Ç.Â.ÓBRÓSˆ	÷ 
÷ 
ŠÜ!Ð"3Ó4ˆØÒØ÷ 
Šð	Ü,Ø¨°6¸%µ=Ø˜yÕ)Ð3DÙ/°Ó@ôˆG÷ ŠYØ6=Ð Ñ3Ü04·	²	³ˆNÑ-÷ ô 	�‰Ø;Ø¨Õ+ô	
ð ÷1 
Š÷ ŽYàˆú÷ 
×	ûô ô 	Ü�N‰NØAØ¨BÕ/°ôó ÷ 
‰ûð	ú÷ �Yú÷# 
�ˆúsf   ÁE(Â&E<ÃG!Ã,%FÄ
G!ÄG	Ä7&G!Å(E9	Å<F	ÆGÆGÆ8G!ÇGÇG!ÇGÇG!Ç!G2	c                ó0   € V ^8„  d   QhR\         R\        /# )r0   r6   rJ   ©r   rK   )r:   s   "r   r;   r;   ü   s   € ÷ ^ñ ^œsð ^¤tñ ^r   c                óz   € \        V 4      pVf   R# \        \        VRR4      ;'       g    \        VRR4      4      # )u£  True if *task_id*'s active env persists across turns.

The agent loop skips per-turn teardown for these (persistent docker,
daytona, modal, â€¦); non-persistent backends are torn down at end of turn
to prevent leakage, and the idle reaper handles the rest. Session-scoped
docker containers count as persistent HERE: their lifetime is the session
(removed by ``AIAgent.close()`` â†’ ``cleanup_vm`` and the idle reaper).
FÚ_session_scopedÚ_persistent)r†   rK   Úgetattr)r6   rI   s   & r   Úis_persistent_envrž   ü   s=   € ô ˜Ó
!€CØ
‚{ÙÜ”˜Ð.°Ó6×\Ð\¼'À#À}ÐV[Ó:\Ó]Ð]r   c            	     ó"  € ^ RI Hp  ^ RIHp V ! 4        ^ p\	        VP                  4       4       F  p \        V4       V^,          pK  	  \        4        FT  p\        RV\        R7      ;_uu_ 4        \        P                  ! VRR	7       \        P                  R
V4       RRR4       KV  	  V^ 8”  d   \        P                  RV4       V#   \         d$   p\        P                  RY4RR7        Rp?KÆ  Rp?ii ; i  + '       g   i     K¹  ; i)zBClean up ALL active environments (process exit). Use with caution.)Úkill_live_foreground_processes)rk   zError cleaning %s: %sTr   Nz!Failed to remove orphaned path %sr   )Úignore_errorszRemoved orphaned: %szCleaned %d environments)Útools.environments.baser    r   rk   rw   rx   Ú
cleanup_vmr'   r%   Úerrorr   r
   r"   ÚshutilÚrmtreerZ   )r    rk   Úcleanedr6   r\   r*   s         r   Úcleanup_all_environmentsr¨     sÜ   € åFÝ8á"Ô$Ø€GÜÐ,×1Ñ1Ó3Ö4ˆð	MÜ�wÔØ�q�LŠGñ 5ô Ö ˆÜÐ7¸Ä7×KÖKÜ�MŠM˜$¨dÕ3Ü�K‰KÐ.°Ô5÷ LÑKñ !ð
 �„{Ü�‰Ð-¨wÔ7Ø€Nøô ô 	MÜ�L‰LÐ0°'ÀtˆL×LÒLûð	Mú÷
 L×KÐKús#   ³CÁ2/C=ÃC:ÃC5Ã5C:Ã=Dc                ó0   € V ^8„  d   QhR\         R\        /# )r0   r6   rG   r™   )r:   s   "r   r;   r;   $  s   € ÷ ñ œð ¬dñ r   c               óZ   € \        V 4      p\        V 4       Vf   R# \        W VRR7       R# )u¢  Manually clean up a specific environment by task_id.

*force_remove* is forwarded to backends that accept it (currently only
``DockerEnvironment``). Default False matches session-lifecycle semantics:
callers (``AIAgent.close()`` on TUI/gateway session teardown, the per-turn
cleanup of non-persistent envs) must honor the user's persist-mode
preference â€” stopping the container here would break the "ONE long-lived
container shared across sessions" contract. Pass ``force_remove=True``
only for user-initiated teardown. The idle reaper calls ``env.cleanup()``
directly, so persist-mode idle envs are likewise no-op'd; only the orphan
reaper at next startup reclaims them.
Nz,Manually cleaned up environment for task: %s)rG   rV   )rq   rf   r^   )r6   rG   rI   s   &$ r   r£   r£   $  s.   € ô ˜'Ó
"€CÜ˜'Ô"Ø
‚{ÙÜØ <Ø?÷r   c                ó>   € V ^8„  d   QhR\         \        ,          RR/# r`   rˆ   )r:   s   "r   r;   r;   ;  s   € ÷ ñ ¬´#­ð ¸4ñ r   c                óÌ  € ^ RI HpHpHpHp V! V 4      0pV '       d   VP                  V 4       . pT;_uu_ 4        V F>  pVP                  VR4      pVP                  VR4       Vf   K-  VP                  V4       K@  	  RRR4       V F/  p\        R4      ;_uu_ 4        VP                  4        RRR4       K1  	  R#   + '       g   i     LG; i  + '       g   i     KY  ; i)zˆDrop any cached env for *task_id* (and its collapsed key) after an
infrastructure failure, so later calls don't reuse a dead connection.)rk   rn   ro   rƒ   Nz&cleanup of degraded environment failed)
r   rk   rn   ro   rƒ   Úaddrp   Úappendr
   rM   )	r6   rk   rn   ro   rƒ   rx   ÚevictedÚkeyrI   s	   &        r   Ú_evict_environment_for_taskr±   ;  s³   € ÷ó ñ ' wÓ/Ð0€DßØ�‰�ÔØ€Gß	ŠÛˆCØ&×*Ñ*¨3°Ó5ˆCØ×Ñ˜s DÔ)ØŒØ—‘˜sÖ#ñ	 ÷ 
ó ˆÜÐ<×=Õ=Ø�K‰KŒM÷ >Ñ=ó ÷ 
�ú÷ >×=Ð=ús   »+B?Á+B?Â CÂ?C	ÃC#c                ó@   € V ^8„  d   Qh/ ^ \         9   d
   \        ;R&   # )r0   r   )Ú__conditional_annotations__r8   )r:   s   "r   r;   r;      s   € ÷ ñ ÷> >Ò =”4Ñ =ò?r   )i,  )N))r³   Ú__doc__r   ÚloggingrR   r¥   r‘   r   Úpathlibr   Útypingr   r   r   Útools.environments.singularityr   rD   r   r   r	   rE   r
   Ú	getLoggerr%   r   r   r   r.   rF   rU   r^   rf   rq   r€   r†   r—   rž   r¨   r£   r±   r;   )r³   s   @r   Ú<module>rº      sÕ   øðöó Û Û Û Û Û Ý ß &Ñ &Ý ;÷ñ õ
 .ð 
×	Ò	Ð0Ó	1€ð
 '¨¨X°uÐ=Ð Ó =àÐ ò;òõ4ð&¸T÷ ð&XÈDð Xð  cQ÷ Xõõ÷"(õBU÷?õD^òð2°U÷ ÷.r   