
    g3fiz7                       d Z ddlm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mZ ddlmZmZ ddlmZ 	 ddlZdZ	 	 	 	 	 	 	 	 	 	 	 	 ddZe	j,                  rddl
mZmZ ddlmZ e G d	 d
ej.                               Ze G d de             Ze G d de             Ze G d de             Zg dZy# e$ r dZY w xY w)z7Execution policies for the persistent shell middleware.    )annotationsN)MappingSequence)	dataclassfield)Pathzlangchain-shell-c                   t        j                  t        |       t         j                  t         j                  t         j                  |dddd|||      S )NTzutf-8replace   )stdinstdoutstderrcwdtextencodingerrorsbufsizeenv
preexec_fnstart_new_session)
subprocessPopenlistPIPE)commandr   r   r   r   s        d/var/www/auto_recruiter/arenv/lib/python3.12/site-packages/langchain/agents/middleware/_execution.py_launch_subprocessr      sK     Woo+     c                      e Zd ZU dZdZded<   dZded<   dZded<   dZd	ed
<   dZ	ded<   ddZ
ej                  	 	 	 	 	 	 	 	 dd       Zy)BaseExecutionPolicya  Configuration contract for persistent shell sessions.

    Concrete subclasses encapsulate how a shell process is launched and constrained.

    Each policy documents its security guarantees and the operating environments in
    which it is appropriate. Use `HostExecutionPolicy` for trusted, same-host execution;
    `CodexSandboxExecutionPolicy` when the Codex CLI sandbox is available and you want
    additional syscall restrictions; and `DockerExecutionPolicy` for container-level
    isolation using Docker.
    g      >@floatcommand_timeoutstartup_timeoutg      $@termination_timeoutd   intmax_output_linesN
int | Nonemax_output_bytesc                <    | j                   dk  rd}t        |      y )Nr   z"max_output_lines must be positive.)r'   
ValueErrorselfmsgs     r   __post_init__z!BaseExecutionPolicy.__post_init__I   s$      A%6CS/! &r   c                    y)z$Launch the persistent shell process.N )r-   	workspacer   r   s       r   spawnzBaseExecutionPolicy.spawnN   s    r   returnNoner2   r   r   Mapping[str, str]r   Sequence[str]r5   subprocess.Popen[str])__name__
__module____qualname____doc__r"   __annotations__r#   r$   r'   r)   r/   abcabstractmethodr3   r1   r   r   r    r    6   s    	 "OU!!OU!!%%c#'j'"
 	3 3 	3
 3 
3 3r   r    c                       e Zd ZU dZdZded<   dZded<   dZded<    ed	d	d	
      Z	ded<   d fdZ
	 	 	 	 	 	 	 	 ddZddZddZedd       Z xZS )HostExecutionPolicya  Run the shell directly on the host process.

    This policy is best suited for trusted or single-tenant environments (CI jobs,
    developer workstations, pre-sandboxed containers) where the agent must access the
    host filesystem and tooling without additional isolation. Enforces optional CPU and
    memory limits to prevent runaway commands but offers **no** filesystem or network
    sandboxing; commands can modify anything the process user can reach.

    On Linux platforms resource limits are applied with `resource.prlimit` after the
    shell starts. On macOS, where `prlimit` is unavailable, limits are set in a
    `preexec_fn` before `exec`. In both cases the shell runs in its own process group
    so timeouts can terminate the full subtree.
    Nr(   cpu_time_secondsmemory_bytesTboolcreate_process_groupF)initreprdefault_limits_requestedc                \   t         |           | j                  | j                  dk  rd}t        |      | j                  | j                  dk  rd}t        |      t        d | j                  | j                  fD              | _        | j                  rt        d}t        |      y y )Nr   z.cpu_time_seconds must be positive if provided.*memory_bytes must be positive if provided.c              3  $   K   | ]  }|d u 
 y wNr1   ).0values     r   	<genexpr>z4HostExecutionPolicy.__post_init__.<locals>.<genexpr>w   s      %
"'E%
s   zHostExecutionPolicy cpu/memory limits require the Python 'resource' module. Either remove the limits or run on a POSIX platform.)	superr/   rD   r+   rE   anyrK   resourceRuntimeErrorr-   r.   	__class__s     r   r/   z!HostExecutionPolicy.__post_init__o   s      ,1F1F!1KBCS/!(T->->!-C>CS/!!$ %
,0,A,A4CTCT+U%
 "
 !!h&6G  s## '7!r   c                   t        t        |      ||| j                         | j                        }| j	                  |       |S )Nr   r   r   r   )r   r   _create_preexec_fnrG   _apply_post_spawn_limits)r-   r2   r   r   processs        r   r3   zHostExecutionPolicy.spawn   sE     %M..0"77
 	%%g.r   c                N      j                   r j                         ry d fd}|S )Nc                    j                   <j                   j                   f} t        j                  t        j                  |        j                  j                  j                  f} t        t        d      r%t        j                  t        j                  |        y t        t        d      r%t        j                  t        j                  |        y y y )N	RLIMIT_ASRLIMIT_DATA)rD   rU   	setrlimit
RLIMIT_CPUrE   hasattrr`   ra   )limitr-   s    r   
_configurez:HostExecutionPolicy._create_preexec_fn.<locals>._configure   s    $$0..0E0EF""8#6#6>  ,**D,=,=>8[1&&x'9'95AX}5&&x';';UC 6	 -r   r4   )rK   _can_use_prlimit)r-   rf   s   ` r   r[   z&HostExecutionPolicy._create_preexec_fn   s(    %%)>)>)@		D r   c                T   | j                   r| j                         sy t        y |j                  }|y 	 t	        j
                  dt              j                  }| j                  . ||t        j                  | j                  | j                  f       | j                  k| j                  | j                  f}t        t        d      r ||t        j                  |       y t        t        d      r ||t        j                  |       y y y # t        $ r}d}t        |      |d }~ww xY w)N
typing.Anyr`   ra   z,Failed to apply resource limits via prlimit.)rK   rg   rU   pidtypingcastprlimitrD   rc   rE   rd   r`   ra   OSErrorrV   )r-   r]   rj   rm   re   excr.   s          r   r\   z,HostExecutionPolicy._apply_post_spawn_limits   s   %%T-B-B-Dkk;	-kk,9AAG$$0X0043H3H$J_J_2`a  ,**D,=,=>8[1C!3!3U;X}5C!5!5u= 6	 -  	-@Cs#,	-s   B*D  (D 	D'D""D'c                 x    t         d uxr1 t        t         d      xr t        j                  j	                  d      S )Nrm   linux)rU   rd   sysplatform
startswithr1   r   r   rg   z$HostExecutionPolicy._can_use_prlimit   s7     D  1),1''0	
r   r4   r7   )r5    typing.Callable[[], None] | None)r]   r:   r5   r6   )r5   rF   )r;   r<   r=   r>   rD   r?   rE   rG   r   rK   r/   r3   r[   r\   staticmethodrg   __classcell__rX   s   @r   rC   rC   Y   s     $(j'#L*#!%$%#UEJtJ$$  	
  
""-, 
 
r   rC   c                      e Zd ZU dZdZded<   dZded<    ee      Z	d	ed
<   	 	 	 	 	 	 	 	 ddZ
ddZddZddZedd       Zy)CodexSandboxExecutionPolicya  Launch the shell through the Codex CLI sandbox.

    Ideal when you have the Codex CLI installed and want the additional syscall and
    filesystem restrictions provided by Anthropic's Seatbelt (macOS) or Landlock/seccomp
    (Linux) profiles. Commands still run on the host, but within the sandbox requested by
    the CLI. If the Codex binary is unavailable or the runtime lacks the required
    kernel features (e.g., Landlock inside some containers), process startup fails with a
    `RuntimeError`.

    Configure sandbox behavior via `config_overrides` to align with your Codex CLI
    profile. This policy does not add its own resource limits; combine it with
    host-level guards (cgroups, container resource limits) as needed.
    codexstrbinaryautoz(typing.Literal['auto', 'macos', 'linux']rs   )default_factoryzMapping[str, typing.Any]config_overridesc               D    | j                  |      }t        |||d d      S NFrZ   )_build_commandr   )r-   r2   r   r   full_commands        r   r3   z!CodexSandboxExecutionPolicy.spawn   s0     **73!#
 	
r   c           	     J   | j                         }| j                         }|d|g}t        t        | j                        j                               D ],  \  }}|j                  d| d| j                  |       g       . |j                  d       |j                  |       |S )Nsandboxz-c=z--)	_resolve_binary_determine_platformsorteddictr   itemsextend_format_overrideappend)r-   r   r}   platform_argr   keyrQ   s          r   r   z*CodexSandboxExecutionPolicy._build_command   s    %%'//1#)9l"C d&;&;!<!B!B!DE 	QJC#a0E0Ee0L/M'N OP	QD!G$r   c                |    t        j                  | j                        }|d}t        || j                  z        |S )NzQCodex sandbox policy requires the '%s' CLI to be installed and available on PATH.shutilwhichr}   rV   r-   pathr.   s      r   r   z+CodexSandboxExecutionPolicy._resolve_binary   s<    ||DKK(<c  sT[[011r   c                    | j                   dk7  r| j                   S t        j                   j                  d      ryt        j                   dk(  ryd}t        |      )Nr~   rq   darwinmacoszYCodex sandbox policy could not determine a supported platform; set 'platform' explicitly.)rs   rr   rt   rV   r,   s     r   r   z/CodexSandboxExecutionPolicy._determine_platform   sS    ==F"== <<""7+<<8#) 	 3r   c                b    	 t        j                  |       S # t        $ r t        |       cY S w xY wrO   )jsondumps	TypeErrorr|   )rQ   s    r   r   z,CodexSandboxExecutionPolicy._format_override  s/    	::e$$ 	u:	s    ..Nr7   )r   r9   r5   	list[str]r5   r|   )rQ   ri   r5   r|   )r;   r<   r=   r>   r}   r?   rs   r   r   r   r3   r   r   r   rv   r   r1   r   r   rz   rz      s     FC9?H6?16t1L.L
 
 	

 
 

    r   rz   c                       e Zd ZU dZdZded<   dZded<   dZded	<   d
Zded<   dZ	ded<   dZ
ded<   dZded<   dZded<   d
Zded<   dZded<   d fdZ	 	 	 	 	 	 	 	 ddZ	 	 	 	 	 	 	 	 ddZedd       Zd dZ xZS )!DockerExecutionPolicyan  Run the shell inside a dedicated Docker container.

    Choose this policy when commands originate from untrusted users or you require
    strong isolation between sessions. By default the workspace is bind-mounted only
    when it refers to an existing non-temporary directory; ephemeral sessions run
    without a mount to minimise host exposure. The container's network namespace is
    disabled by default (`--network none`) and you can enable further hardening via
    `read_only_rootfs` and `user`.

    The security guarantees depend on your Docker daemon configuration. Run the agent on
    a host where Docker is locked down (rootless mode, AppArmor/SELinux, etc.) and
    review any additional volumes or capabilities passed through ``extra_run_args``. The
    default image is `python:3.12-alpine3.19`; supply a custom image if you need
    preinstalled tooling.
    dockerr|   r}   zpython:3.12-alpine3.19imageTrF   remove_container_on_exitFnetwork_enabledNzSequence[str] | Noneextra_run_argsr(   rE   ztyping.Any | NonerD   z
str | Nonecpusread_only_rootfsuserc                   t         |           | j                  | j                  dk  rd}t        |      | j                  d}t        |      | j                  '| j                  j                         sd}t        |      | j                  '| j                  j                         sd}t        |      t        | j                  xs d      | _
        y )Nr   rM   zxDockerExecutionPolicy does not support cpu_time_seconds; configure CPU limits using Docker run options such as '--cpus'.z.cpus must be a non-empty string when provided.z.user must be a non-empty string when provided.r1   )rS   r/   rE   r+   rD   rV   r   stripr   tupler   rW   s     r   r/   z#DockerExecutionPolicy.__post_init__+  s    (T->->!-C>CS/!  ,=  s##99 ):BCS/!99 ):BCS/!#D$7$7$=2>r   c                   | j                  |||      }t        j                  j                         }t	        |||d d      S r   )r   osenvironcopyr   )r-   r2   r   r   r   host_envs         r   r3   zDockerExecutionPolicy.spawn>  sD     **9c7C::??$!#
 	
r   c                   | j                         }|ddg}| j                  r|j                  d       | j                  s|j	                  ddg       | j
                  &|j	                  dt        | j
                        g       | j                  |      r7t        |      }|j	                  d| d| g       |j	                  d	|g       n|j	                  d	d
g       | j                  r|j                  d       |j                         D ]  \  }}|j	                  d| d| g        | j                  |j	                  d| j                  g       | j                  |j	                  d| j                  g       | j                  r|j	                  | j                         |j                  | j                         |j	                  |       |S )Nrunz-iz--rmz	--networknonez--memoryz-v:z-w/z--read-onlyz-er   z--cpusz--user)r   r   r   r   r   rE   r|   _should_mount_workspacer   r   r   r   r   r   )	r-   r2   r   r   r}   r   	host_pathr   rQ   s	            r   r   z$DockerExecutionPolicy._build_commandO  s    %%'#)5$"7(('##f 56(S1B1B-C DE''	2II)Ai['A BCy 12s,  .))+ 	:JC#aw'7 89	:99 499 5699 499 56 3 34DJJ'G$r   c                B    | j                   j                  t               S rO   )namert   SHELL_TEMP_PREFIX)r2   s    r   r   z-DockerExecutionPolicy._should_mount_workspaceq  s    >>,,->???r   c                |    t        j                  | j                        }|d}t        || j                  z        |S )NzTDocker execution policy requires the '%s' CLI to be installed and available on PATH.r   r   s      r   r   z%DockerExecutionPolicy._resolve_binaryu  s>    ||DKK(<*  sT[[011r   r4   r7   )r2   r   r   r8   r   r9   r5   r   )r2   r   r5   rF   r   )r;   r<   r=   r>   r}   r?   r   r   r   r   rE   rD   r   r   r   r/   r3   r   rv   r   r   rw   rx   s   @r   r   r     s      FC)E3)%)d)!OT!+/N(/#L*#*.'.D*"d"D*?&
 
 	

 
 

"     	 
 
 D @ @r   r   )r    rz   r   rC   )r   r9   r   r8   r   r   r   ru   r   rF   r5   r:   )r>   
__future__r   r@   r   r   r   r   rr   rk   collections.abcr   r   dataclassesr   r   pathlibr   rU   ImportErrorr   r   TYPE_CHECKINGABCr    rC   rz   r   __all__r1   r   r   <module>r      s'   = " 
  	   
  - ( 
 '  
 
	
 1  0 
1 3#'' 3 3D e
- e
 e
P H"5 H HV n/ n nb]  Hs   B; ;CC