
    OKi}                       S r SSKJr  SSKrSSKrSSKrSSKrSSKrSSKrSSK	r	SSK
r
SSKrSSKrSSKrSSKJrJr  SSKJr  SSKJrJrJrJrJr  SSKJr  SSKJr  SS	KJr  SS
KJ r   SSK!J"r"J#r#  SSK$J%r%  SSK&J'r'J(r(  SSK)J*r*J+r+J,r,J-r-J.r.  SSK/J0r0J1r1J2r2J3r3  SSK4J5r5J6r6J7r7J8r8J9r9  SSK:J;r;J<r<  \(       a  SSK=J>r>J?r?  SSK@JArA  \R                  " \C5      rDSrESrFSrG        S'S jrH\ " S S5      5       rI " S S\6\9   5      rJ\" SS9 " S S 5      5       rK " S! S5      rL " S" S#\"5      rM " S$ S%\5\J\9   \7\94   5      rN/ S&QrOg)(z:Middleware that exposes a persistent shell tool to agents.    )annotationsN)	dataclassfield)Path)TYPE_CHECKING	AnnotatedAnyLiteralcast)ToolMessage)run_in_executor)ToolException)UntrackedValue)	BaseModelmodel_validator)SkipJsonSchema)NotRequiredoverride)SHELL_TEMP_PREFIXBaseExecutionPolicyCodexSandboxExecutionPolicyDockerExecutionPolicyHostExecutionPolicy)PIIDetectionErrorPIIMatchRedactionRuleResolvedRedactionRule)AgentMiddleware
AgentStateContextTPrivateStateAttr	ResponseT)ToolRuntimetool)MappingSequence)Runtime__LC_SHELL_DONE__aG  Execute a shell command inside a persistent session. Before running a command, confirm the working directory is correct (e.g., inspect with `ls` or `pwd`) and ensure any parent directories exist. Prefer absolute paths and quote paths containing spaces, such as `cd "/path/with spaces"`. Chain multiple commands with `&&` or `;` instead of embedding newlines. Avoid unnecessary `cd` usage unless explicitly required so the session remains stable. Outputs may be truncated when they become very large, and long running commands will be terminated once their configured timeout elapses.shellShellSessionc                   [         R                  " [        5         U R                  U5        S S S 5        Ub4  [         R                  " [        5         UR	                  5         S S S 5        g g ! , (       d  f       NF= f! , (       d  f       g = fN)
contextlibsuppress	Exceptionstopcleanup)sessiontempdirtimeouts      h/var/www/html/dynamic-report/venv/lib/python3.13/site-packages/langchain/agents/middleware/shell_tool.py_cleanup_resourcesr6   G   s`     
		Y	'W 
(  +OO ,+  
(	' ,+s   A-A>-
A;>
Bc                  Z    \ rS rSr% SrS\S'   S\S'   S\S'   \" S	S	S
9rS\S'   SS jrSr	g)_SessionResourcesQ   z&Container for per-run shell resources.r*   r2   'tempfile.TemporaryDirectory[str] | Noner3   r   policyF)initreprzweakref.finalize	finalizerc                    [         R                  " U [        U R                  U R                  U R
                  R                  5      U l        g r,   )weakreffinalizer6   r2   r3   r;   termination_timeoutr>   selfs    r5   __post_init___SessionResources.__post_init__Z   s5     ))LLLLKK++
    )r>   NreturnNone)
__name__
__module____qualname____firstlineno____doc____annotations__r   r>   rE   __static_attributes__ rG   r5   r8   r8   Q   s.    044"'U"?I?
rG   r8   c                  $    \ rS rSr% SrS\S'   Srg)ShellToolStated   zAgent state extension for tracking shell session resources.

Type Parameters:
    ResponseT: The type of the structured response. Defaults to `Any`.
zRNotRequired[Annotated[_SessionResources | None, UntrackedValue, PrivateStateAttr]]shell_session_resourcesrR   NrK   rL   rM   rN   rO   rP   rQ   rR   rG   r5   rT   rT   d   s     rG   rT   T)frozenc                  `    \ rS rSr% SrS\S'   S\S'   S\S'   S\S	'   S\S
'   S\S'   S\S'   Srg)CommandExecutionResultp   z)Structured result from command execution.stroutput
int | None	exit_codebool	timed_outtruncated_by_linestruncated_by_bytesinttotal_linestotal_bytesrR   NrW   rR   rG   r5   rZ   rZ   p   s-    3KOrG   rZ   c                      \ rS rSrSr          SS jrSS jrSS jrSS jrSS jr	        SS jr
SS	 jrSS
 jrSS jrSS jr S       SS jjr\SS j5       rSrg)r*   }   zDPersistent shell session that supports sequential command execution.c                    Xl         X l        X0l        [        U5      U l        S U l        S U l        [        R                  " 5       U l	        [        R                  " 5       U l        S U l        S U l        SU l        g )NF)
_workspace_policy_commanddict_environment_process_stdinqueueQueue_queue	threadingLock_lock_stdout_thread_stderr_thread_terminated)rD   	workspacer;   commandenvironments        r5   __init__ShellSession.__init__   sa     $ -6:;@;;=^^%
7;7; rG   c                J   U R                   (       a  U R                   R                  5       c  gU R                  R                  U R                  U R
                  U R                  S9U l         U R                   R                  b.  U R                   R                  b  U R                   R                  c  Sn[        U5      eU R                   R                  U l        SU l        [        R                  " 5       U l        [         R"                  " U R$                  U R                   R                  S4SS9U l        [         R"                  " U R$                  U R                   R                  S4SS9U l        U R&                  R+                  5         U R(                  R+                  5         g)	z|Start the shell subprocess and reader threads.

Raises:
    RuntimeError: If the shell session pipes cannot be initialized.
N)rz   envr{   z)Failed to initialize shell session pipes.FstdoutT)targetargsdaemonstderr)ro   pollrk   spawnrj   rn   rl   stdinr   r   RuntimeErrorrp   ry   rq   rr   rs   rt   Thread_enqueue_streamrw   rx   startrD   msgs     r5   r   ShellSession.start   sD    ==T]]//19**oo!!MM + 
 MM'}}##+}}##+=Cs##mm)) kkm'..''--&&1

 (..''--&&1

 	!!#!!#rG   c                n    U R                  U R                  R                  5        U R                  5         g)zRestart the shell process.N)r0   rk   rB   r   rC   s    r5   restartShellSession.restart   s!    		$,,223

rG   c                r   U R                   (       d  gU R                   R                  5       cG  U R                  (       d6   U R                  R	                  S5        U R                  R                  5          U R                   R                  US9c  U R                  5         SU l        [        R                  " [         5         U R                  R#                  5         SSS5        SU l         g! [        [        4 a    [        R                  SSS9   Nf = f! [        R                   a    U R                  5          Nf = f! , (       d  f       Nj= f! SU l        [        R                  " [         5         U R                  R#                  5         SSS5        SU l         f ! , (       d  f       SU l         f = f= f)zStop the shell subprocess.Nzexit
z8Failed to write exit command; terminating shell session.Texc_infor4   )ro   r   ry   rp   writeflushBrokenPipeErrorOSErrorLOGGERdebugwait_kill_process
subprocessTimeoutExpiredr-   r.   r/   close)rD   r4   s     r5   r0   ShellSession.stop   sG   }}=='0@0@!!(+!!#		!}}!!'!2:""$  $D$$Y/!!# 0 DM $W- N!   (( 	! 	! 0/  $D$$Y/!!# 0 DM 0/ DMsZ    5C, 6*D E ,$DD$D=:E <D==E  
E"F63FF6
F3(F6c                  U R                   (       a  U R                   R                  5       b  Sn[        U5      e[         [        R
                  " 5       R                   3n[        R                  " 5       U-   nU R                     U R                  5         UR                  S5      (       a  UOU S3n U R                  R                  U5        U R                  R                  SU S35        U R                  R                  5         U R%                  XEU5      sSSS5        $ ! [        [         4 a    U R#                  U5      s sSSS5        $ f = f! , (       d  f       g= f)z*Execute a command in the persistent shell.NzShell session is not running.
zprintf 'z
 %s\n' $?
)ro   r   r   _DONE_MARKER_PREFIXuuiduuid4hextime	monotonicrv   _drain_queueendswithrp   r   r   r   r   _collect_output_after_exit_collect_output)rD   r{   r4   r   markerdeadlinepayloads          r5   executeShellSession.execute   s   }} 2 2 4 @1Cs##'()9)9(:;>>#g-ZZ!(!1!1$!7!7gy^GA!!'*!!HVHL"AB!!# '''B Z $W- A 66x@@ ZA Zs1   .E4AD#E#!EEEE
E!c           
        / nSnSnSnSnS n	Sn
 U[         R                  " 5       -
  nUS::  a  Sn
GO` U R                  R                  US9u  pUc  MD  US:X  a[  UR                  U5      (       aE  UR                  S5      u    pU R                  UR                  5       5      n	U R                  XB5        OUS-  nUR                  SS	5      nU[        U5      -  nXPR                  R                  :  a  SnM  U R                  R                  b  X`R                  R                  :  a  SnGM  US
:X  aM  UR!                  S5      nUR#                  SU 35        UR%                  S5      (       a  UR#                  S5        OUR#                  U5        GM  U
(       a5  [&        R)                  SU5        U R+                  5         [-        SS SUUUUS9$ SR/                  U5      n[-        UU	SUUUUS9$ ! [        R
                   a    Sn
 Mu  f = f)Nr   FTr   r       utf-8replacer   r   	[stderr] z?Command timed out after %.2f seconds; restarting shell session. r]   r_   ra   rb   rc   re   rf   )r   r   rs   getrq   Empty
startswith	partition	_safe_intstrip_drain_remaining_stderrencodelenrk   max_output_linesmax_output_bytesrstripappendr   r   warningr   rZ   join)rD   r   r   r4   	collectedre   rf   rb   rc   r_   ra   	remainingsourcedata_statusencodedstrippedr]   s                      r5   r   ShellSession._collect_output   s     "	"" $		 4>>#33IA~ 	#{{yA
 |!doof&=&=#~~c21 NN6<<>:	 ,,YA1Kkk'95G3w<'K\\:::%)" --9,,"?"??%)"!;;t,  9XJ!78==&&$$T*  &Y \ NNQ LLN)#5#5''  #%11##
 	
q ;;  	s   G. .HHc           
     j   / nSnSnSnSnSn[        [        R                  " 5       U-   U5      n U[        R                  " 5       -
  n	U	S::  a  O U R                  R	                  U	S9u  pUc  MA  US-  nUR                  SS	5      nU[        U5      -  nX0R                  R                  :  a  SnM  U R                  R                  b  X@R                  R                  :  a  SnM  U
S
:X  aM  UR                  S5      nUR                  SU 35        UR                  S5      (       a  UR                  S5        OUR                  U5        GM  SnU R                  (       a  U R                  R!                  5       nSR#                  U5      n[%        UUSUUUUS9$ ! [
        R                   a     Md  f = f)a\  Collect output after the shell exited unexpectedly.

Called when a `BrokenPipeError` occurs while writing to stdin, indicating the
shell process terminated (e.g., due to an 'exit' command).

Args:
    deadline: Absolute time by which collection must complete.

Returns:
    `CommandExecutionResult` with collected output and the process exit code.
r   Fg?Tr   Nr   r   r   r   r   r   r   r   )minr   r   rs   r   rq   r   r   r   rk   r   r   r   r   r   ro   r   r   rZ   )rD   r   r   re   rf   rb   rc   drain_timeoutdrain_deadliner   r   r   r   r   r_   r]   s                   r5   r   'ShellSession._collect_output_after_exitG  s     "	"" T^^-=xH&)99IA~#{{yA |1Kkk'95G3w<'K\\:::%)" --9,,"?"??%)"!;;t,  9XJ!78==&&$$T*  &E J !%	==**,I#%11##
 	
I ;; s   F F21F2c                   U R                   (       d  g [        [        S5      (       aq  [        R                  " [
        5         [        R                  " [        R                  " U R                   R                  5      [        R                  5        S S S 5        g [        R                  " [
        5         U R                   R                  5         S S S 5        g ! , (       d  f       g = f! , (       d  f       g = f)Nkillpg)ro   hasattrosr-   r.   ProcessLookupErrorr   getpgidpidsignalSIGKILLkillrC   s    r5   r   ShellSession._kill_process  s    }}2x  $$%78		"**T]]%6%67H 98 $$%78""$ 98 98 98s   AC3C(
C%(
C6c                    [        UR                  S5       H  nU R                  R                  X#45        M!     U R                  R                  US 45        g )Nr   )iterreadliners   put)rD   streamlabellines       r5   r   ShellSession._enqueue_stream  s=    "-DKKOOUM* .&rG   c                r      U R                   R                  5         M  ! [        R                   a     g f = fr,   )rs   
get_nowaitrq   r   rC   s    r5   r   ShellSession._drain_queue  s7    &&(  ;; s    66c                   [        [        R                  " 5       U-   U5      n U[        R                  " 5       -
  nUS::  a  g U R                  R	                  US9u  pgUb  US:w  a  MG  UR                  S5      nUR                  SU 35        UR                  S5      (       a  UR                  S5        M  ! [
        R                   a     gf = f)a  Drain any stderr output that arrived concurrently with the done marker.

The stdout and stderr reader threads run independently. When a command writes to
stderr just before exiting, the stderr output may still be in transit when the
done marker arrives on stdout. This method briefly polls the queue to capture
such output.

Args:
    collected: The list to append collected stderr lines to.
    deadline: The original command deadline (used as an upper bound).
    drain_timeout: Maximum time to wait for additional stderr output.
r   r   Nr   r   r   )
r   r   r   rs   r   rq   r   r   r   r   )	rD   r   r   r   r   r   r   r   r   s	            r5   r   $ShellSession._drain_remaining_stderr  s     T^^-=xH&)99IA~#{{yA |v1{{4(Hy
34}}T""  &  ;; s   B8 8CCc                    [         R                  " [        5         [        U 5      sS S S 5        $ ! , (       d  f       g = fr,   )r-   r.   
ValueErrorrd   )values    r5   r   ShellSession._safe_int  s&      ,u: -,,s   0
>)rl   rn   rv   rk   ro   rs   rx   rp   rw   ry   rj   N)
rz   r   r;   r   r{   tuple[str, ...]r|   zMapping[str, str]rI   rJ   rH   )r4   floatrI   rJ   )r{   r\   r4   r   rI   rZ   )r   r\   r   r   r4   r   rI   rZ   )r   r   rI   rZ   )r   r	   r   r\   rI   rJ   )g?)r   z	list[str]r   r   r   r   rI   rJ   )r   r\   rI   r^   )rK   rL   rM   rN   rO   r}   r   r   r0   r   r   r   r   r   r   r   staticmethodr   rQ   rR   rG   r5   r*   r*   }   s    N!! $! !	!
 '! 
!&%$N
!4C.U
U
 U
 	U

 
 U
nH
T	%'
 MQ'"'.3'DI'	'>  rG   c                  f    \ rS rSr% SrSrS\S'    SrS\S'    SrS\S	'    \	" S
S9SS j5       r
Srg)_ShellToolInputi  z+Input schema for the persistent shell tool.N
str | Noner{   zbool | Noner   z Annotated[Any, SkipJsonSchema()]runtimeafter)modec                    U R                   c  U R                  (       d  Sn[        U5      eU R                   b  U R                  (       a  Sn[        U5      eU $ )Nz2Shell tool requires either 'command' or 'restart'.z+Specify only one of 'command' or 'restart'.)r{   r   r   r   s     r5   validate_payload _ShellToolInput.validate_payload  sE    <<FCS/!<<#?CS/!rG   rR   )rI   r   )rK   rL   rM   rN   rO   r{   rP   r   r   r   r   rQ   rR   rG   r5   r   r     sH    5GZ'G[/04G-4 '" #rG   r   c            
        ^  \ rS rSrSr\r SSSSSS\SSS.                   SU 4S jjjjr\	    SS j5       r
\	    SS j5       r\	SS j5       r\      SS	 j5       r      SS
 jr\SS j5       r      SS jrSS jrSS jrSS jrSS jrS S jr        S!S jrSS.         S"S jjrSrU =r$ )#ShellToolMiddlewarei  u  Middleware that registers a persistent shell tool for agents.

The middleware exposes a single long-lived shell session. Use the execution policy
to match your deployment's security posture:

* `HostExecutionPolicy` – full host access; best for trusted environments where the
    agent already runs inside a container or VM that provides isolation.
* `CodexSandboxExecutionPolicy` – reuses the Codex CLI sandbox for additional
    syscall/filesystem restrictions when the CLI is available.
* `DockerExecutionPolicy` – launches a separate Docker container for each agent run,
    providing harder isolation, optional read-only root filesystems, and user
    remapping.

When no policy is provided the middleware defaults to `HostExecutionPolicy`.
N)startup_commandsshutdown_commandsexecution_policyredaction_rulestool_description	tool_nameshell_commandr   c               <  >^  [         TT ]  5         U(       a  [        U5      OST l        UT l        T R                  U5      T l        T R                  U	5      T l        Ub  UT l	        O[        5       T l	        U=(       d    Sn
[        S U
 5       5      T l        T R                  U5      T l        T R                  U5      T l        U=(       d    [         n[#        T R                  [$        US9SSS.       SU 4S jjj5       nUT l        T R&                  /T l        g)	a  Initialize an instance of `ShellToolMiddleware`.

Args:
    workspace_root: Base directory for the shell session.

        If omitted, a temporary directory is created when the agent starts and
        removed when it ends.
    startup_commands: Optional commands executed sequentially after the session
        starts.
    shutdown_commands: Optional commands executed before the session shuts down.
    execution_policy: Execution policy controlling timeouts, output limits, and
        resource configuration.

        Defaults to `HostExecutionPolicy` for native execution.
    redaction_rules: Optional redaction rules to sanitize command output before
        returning it to the model.

        !!! warning
            Redaction rules are applied post execution and do not prevent
            exfiltration of secrets or sensitive data when using
            `HostExecutionPolicy`.

    tool_description: Optional override for the registered shell tool
        description.
    tool_name: Name for the registered shell tool.

        Defaults to `"shell"`.
    shell_command: Optional shell executable (string) or argument sequence used
        to launch the persistent session.

        Defaults to an implementation-defined bash command.
    env: Optional environment variables to supply to the shell session.

        Values are coerced to strings before command execution. If omitted, the
        session inherits the parent process environment.
NrR   c              3  @   #    U  H  oR                  5       v   M     g 7fr,   )resolve).0rules     r5   	<genexpr>/ShellToolMiddleware.__init__.<locals>.<genexpr>7  s      I
',tLLNNus   )args_schemadescriptionFr{   r   c                t   > TR                  U R                  5      nTR                  UXS.U R                  S9$ )Nr  )tool_call_id)_get_or_create_resourcesstate_run_shell_toolr  )r   r{   r   	resourcesrD   s       r5   
shell_tool0ShellToolMiddleware.__init__.<locals>.shell_tool@  sC     55gmmDI''#8$11 (  rG   )r   z!ToolRuntime[None, ShellToolState]r{   r   r   r`   rI   ToolMessage | str)superr}   r   _workspace_root
_tool_name_normalize_shell_command_shell_command_normalize_envrn   _execution_policyr   tuple_redaction_rules_normalize_commands_startup_commands_shutdown_commandsDEFAULT_TOOL_DESCRIPTIONr$   r   _shell_tooltools)rD   workspace_rootr  r  r  r  r  r  r	  r   rulesr  r  	__class__s   `            r5   r}   ShellToolMiddleware.__init__  s.   b 	7EtN34#";;MJ //4'%5D"%8%:D"%2CH I
',I
 D
 "&!9!9:J!K"&":":;L"M 'B*B	doo?	T #'!		6	  	 		
 	 
U	 &&&'
rG   c                P    U c  g[        U [        5      (       a  U 4$ [        U 5      $ )NrR   )
isinstancer\   r$  )commandss    r5   r&  'ShellToolMiddleware._normalize_commandsQ  s,     h$$;XrG   c                |    U c  g[        U [        5      (       a  U 4O
[        U 5      nU(       d  Sn[        U5      eU$ )N)z	/bin/bashz1Shell command must contain at least one argument.)r1  r\   r$  r   )r	  
normalizedr   s      r5   r   ,ShellToolMiddleware._normalize_shell_command[  sA      !)3M3)G)Gm%US`Ma
ECS/!rG   c                    U c  g 0 nU R                  5        H4  u  p#[        U[        5      (       d  Sn[        U5      e[        U5      X'   M6     U$ )Nz+Environment variable names must be strings.)itemsr1  r\   	TypeError)r   r5  keyr   r   s        r5   r"  "ShellToolMiddleware._normalize_envg  sP    ;%'
))+JCc3''Cn$!%jJO	 &
 rG   c                ,    U R                  U5      nSU0$ )zStart the shell session and run startup commands.

Args:
    state: The current agent state.
    runtime: The runtime context.

Returns:
    Shell session resources to be stored in the agent state.
rV   )r  rD   r  r   r  s       r5   before_agent ShellToolMiddleware.before_agents  s     11%8	)955rG   c                L   #    [        SU R                  X5      I Sh  vN $  N7f)zAsync start the shell session and run startup commands.

Args:
    state: The current agent state.
    runtime: The runtime context.

Returns:
    Shell session resources to be stored in the agent state.
N)r   r>  rD   r  r   s      r5   abefore_agent!ShellToolMiddleware.abefore_agent  s"      %T4+<+<eMMMMs   $"$c                    UR                  S5      n[        U[        5      (       d  g U R                  UR                  5        UR                  5         g! UR                  5         f = f)zDRun shutdown commands and release resources when an agent completes.rV   N)r   r1  r8   _run_shutdown_commandsr2   r>   r=  s       r5   after_agentShellToolMiddleware.after_agent  sV     II78	)%677	"''	(9(9:!I!s   A A'c                ,   #    U R                  X5      $ 7f)zJAsync run shutdown commands and release resources when an agent completes.)rF  rA  s      r5   aafter_agent ShellToolMiddleware.aafter_agent  s      //s   c                    UR                  S5      n[        U[        5      (       a  U$ U R                  5       nU[	        SU5      S'   U$ )a  Get existing resources from state or create new ones if they don't exist.

This method enables resumability by checking if resources already exist in the state
(e.g., after an interrupt), and only creating new resources if they're not present.

Args:
    state: The agent state which may contain shell session resources.

Returns:
    Session resources, either retrieved from state or newly created.
rV   dict[str, Any])r   r1  r8   _create_resourcesr   )rD   r  r  new_resourcess       r5   r  ,ShellToolMiddleware._get_or_create_resources  sN     II78	i!233..0CPu%&?@rG   c                ^   U R                   nS nUc.  [        R                  " [        S9n[	        UR
                  5      nOUnUR                  SSS9  [        UU R                  U R                  U R                  =(       d    0 5      n UR                  5         [        R                  SU5        U R                  U5        [)        XBU R                  S9$ ! [         aO    [        R!                  S5        UR#                  U R                  R$                  5        Ub  UR'                  5         e f = f)N)prefixT)parentsexist_okzStarted shell session in %sz5Starting shell session failed; cleaning up resources.)r2   r3   r;   )r  tempfileTemporaryDirectoryr   r   namemkdirr*   r#  r!  rn   r   r   info_run_startup_commandsBaseException	exceptionr0   rB   r1   r8   )rD   rz   r3   workspace_pathr2   s        r5   rM  %ShellToolMiddleware._create_resources  s   ((	;?119JKG!',,/N&N   =""#	
		MMOKK5~F&&w/ !$J`J`aa  	TULL//CCD"!	s   7C AD,c                   U R                   (       d  g U R                    Hd  nUR                  X R                  R                  S9nUR                  (       d  UR
                  S;  d  MI  SU SUR
                   3n[        U5      e   g )Nr      Nr   zStartup command 'z' failed with exit code )r'  r   r#  startup_timeoutra   r_   r   )rD   r2   r{   resultr   s        r5   rY  )ShellToolMiddleware._run_startup_commands  su    %%--G__W6L6L6\6\_]FF$4$4I$E)'2J6K[K[J\]"3''	 .rG   c           	        U R                   (       d  g U R                    H  n UR                  X R                  R                  S9nUR                  (       a  [
        R                  SU5        MP  UR                  S;  a"  [
        R                  SX#R                  5        M  M     g ! [        [        [        4 a   n[
        R                  SX$SS9   S nAM  S nAff = f)Nr   z Shutdown command '%s' timed out.r_  z%Shutdown command '%s' exited with %s.z'Failed to run shutdown command '%s': %sTr   )r(  r   r#  command_timeoutra   r   r   r_   r   r   r   )rD   r2   r{   ra  excs        r5   rE  *ShellToolMiddleware._run_shutdown_commands  s    &&..G :P:P:`:`a##NN#EwO%%Y6NN?JZJZ 7 / !-9 =wVZ  s   A
B&/0B&&C;CCc                    0 nUnU R                    HJ  nUR                  U5      u  p5U(       d  M  UR                  UR                  / 5      R	                  U5        ML     X24$ )z3Apply configured redaction rules to command output.)r%  apply
setdefaultpii_typeextend)rD   contentmatches_by_typeupdatedr  matchess         r5   _apply_redactions%ShellToolMiddleware._apply_redactions  s\    57))D#zz'2Gw**4=="=DDWM * ''rG   c          
     L   UR                   nUR                  S5      (       aI  [        R                  S5         UR	                  5         U R                  U5        SnU R                  XsSS9$ UR                  S5      nU(       a  [        U[        5      (       d  S	n[        U5      e[        R                  S
U5        UR                  XR                  R                  S9n	U	R                  (       a2  U R                  R                  n
SU
S S3nU R                  UUSSS S.S9$  U R!                  U	R"                  5      u  pU=(       d    SnU	R.                  (       a7  UR1                  5        SU R                  R2                   SU	R4                   S3nU	R6                  (       aN  U R                  R8                  b7  UR1                  5        SU R                  R8                   SU	R:                   S3nU	R*                  S;  a"  UR1                  5        SU	R*                   3nSnOSnSU	R*                  U	R.                  U	R6                  U	R4                  U	R:                  US.nU R                  UUUUS9$ ! [         a(  n[        R                  S5        Sn[        U5      UeS nAff = f! [$         ap  n[        R'                  SUR(                  5        SUR(                   S3nU R                  UUSSU	R*                  UR(                  UR,                  0S.S9s S nA$ S nAff = f) Nr   z$Restarting shell session on request.z=Restarting shell session failed; session remains unavailable.z Failed to restart shell session.zShell session restarted.success)r   r{   zDShell tool expects a 'command' string when restart is not requested.zExecuting shell command: %sr   zError: Command timed out after z.1fz	 seconds.errorT)ra   r_   )r   artifactz+Blocking command output due to detected %s.zOutput blocked: detected .F)ra   r_   ro  z<no output>z

... Output truncated at z lines (observed z).z bytes (observed r_  z

Exit code: )ra   r_   rb   rc   re   rf   redaction_matches)r2   r   r   rX  r   rY  rZ  r[  r   _format_tool_messager1  r\   r   r#  rd  ra   rp  r]   r   r   rj  r_   ro  rb   r   r   re   rc   r   rf   )rD   r  r   r  r2   errr   messager{   ra  timeout_secondssanitized_outputro  rt  final_statusru  s                   r5   r  #ShellToolMiddleware._run_shell_tool  s6    ##;;y!!KK>?2!**73
 1G,,W9,UU++i(j#66XC$$17;2H2H2X2XY"44DDO77LIVG,,!%!%	 -  	(,(>(>v}}(M% ,<}$$#**,- .++/+A+A+R+R*S T#//04 
 $$)?)?)P)P)\#**,- .++/+A+A+R+R*S T#//04  9,"2"9"9";!<OFL\L\K]^8?L$L ))"(";";"(";";!--!--!(
 ((	 ) 
 	
U ! 2  !`a8#C(c12< ! 	NNH%..Y1%..1ACG,,!&!'!1!1 %>	 - 	 		s6   !I4 #J) 4
J&>#J!!J&)
L#3A%LL#L#)ru  c               P    U=(       d    0 nUc  U$ [        UUU R                  UUS9$ )N)rl  r  rV  r   ru  )r   r  )rD   rl  r  r   ru  s        r5   rx  (ShellToolMiddleware._format_tool_messageX  s8     >rN%
 	
rG   )
rn   r#  r%  r!  r*  r(  r'  r  r  r+  r,   )r,  zstr | Path | Noner  (tuple[str, ...] | list[str] | str | Noner  r  r  zBaseExecutionPolicy | Noner  z6tuple[RedactionRule, ...] | list[RedactionRule] | Noner  r   r  r\   r	  Sequence[str] | str | Noner   Mapping[str, Any] | NonerI   rJ   )r2  r  rI   r   )r	  r  rI   r   )r   r  rI   zdict[str, str] | None)r  ShellToolState[ResponseT]r   Runtime[ContextT]rI   dict[str, Any] | None)r  r  r   r  rI   rJ   )r  r  rI   r8   )rI   r8   )r2   r*   rI   rJ   )rl  r\   rI   z%tuple[str, dict[str, list[PIIMatch]]])r  r8   r   rL  r  r   rI   r	   )
rl  r\   r  r   r   zLiteral['success', 'error']ru  r  rI   r  )rK   rL   rM   rN   rO   rT   state_schemaSHELL_TOOL_NAMEr}   r   r&  r   r"  r   r>  rB  rF  rI  r  rM  rY  rE  rp  r  rx  rQ   __classcell__)r.  s   @r5   r  r    s     "L -1S( FJFJ7;RV'+(48(,S()S( C	S(
 DS( 5S( PS( %S( S( 2S( &S( 
S( S(j :	  	1			 	 	 	 6.69J6	6 6N.N9JN	N 	" 	"0.09J0	0*b:("(]
$]
  ]

 !]
 
]
J +/

 !

 ,
 (
 

 
rG   r  )r   r   r   r   r  )r2   r*   r3   r:   r4   r   rI   rJ   )PrO   
__future__r   r-   loggingr   rq   r   r   rT  rt   r   r   r@   dataclassesr   r   pathlibr   typingr   r   r	   r
   r   langchain_core.messagesr   langchain_core.runnablesr   langchain_core.tools.baser   "langgraph.channels.untracked_valuer   pydanticr   r   pydantic.json_schemar   typing_extensionsr   r   &langchain.agents.middleware._executionr   r   r   r   r   &langchain.agents.middleware._redactionr   r   r   r   !langchain.agents.middleware.typesr   r   r    r!   r"   langchain.toolsr#   r$   collections.abcr%   r&   langgraph.runtimer'   	getLoggerrK   r   r   r)  r  r6   r8   rT   rZ   r*   r   r  __all__rR   rG   r5   <module>r     sP   @ "   	         (  ? ? / 4 3 = / / 3    .1) 
		8	$) Q  $KV[	 
 
 
$	Z	* 	 $	 	 	N Nb
i 6@
/.*CXy*XY @
FrG   