
    
i62                        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m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 ddZddZddZ G d deee         eef                   ZdgZdS )zFile search middleware for Anthropic text editor and memory tools.

This module provides Glob and Grep search tools that operate on files stored
in state or filesystem.
    )annotationsN)suppress)datetimetimezone)Path)Literal)tool)AgentMiddleware
AgentStateContextT	ResponseTpatternstrreturnlist[str] | Nonec                l    d| v rd| vrdS g d	fd	  |            n# t           $ r Y dS w xY wS )
z=Expand brace patterns like `*.{py,pyi}` into a list of globs.}{Ncurrentr   r   Nonec                ^   |                      d          }|dk    r                    |            d S |                      d|          }|dk    rt          | d |         }| |dz   d          }| |dz   |         }|st          |                    d          D ]} ||z   |z              d S )Nr   r      ,)findappend
ValueErrorsplit)	r   startendprefixsuffixinneroption_expandexpandeds	          C:\Users\Dell Inspiron 16\Desktop\tws\AgrotaPowerBi\back-agrota-powerbi\mcp-client-agrota\venv\Lib\site-packages\langchain/agents/middleware/file_search.pyr%   z)_expand_include_patterns.<locals>._expand   s    S!!B;;OOG$$$Fll3&&"99%q#	C( 	kk#&& 	. 	.FGFVOf,----	. 	.    )r   r   r   r   )r   )r   r%   r&   s    @@r'   _expand_include_patternsr)      s    
g~~#W,,tH. . . . . . .&   tt Os   # 
11boolc                      sdS t           fddD                       rdS t                     }|dS 	 |D ](}t          j        t	          j        |                     )n# t          j        $ r Y dS w xY wdS )z/Validate glob pattern used for include filters.Fc              3      K   | ]}|v V  	d S N ).0charr   s     r'   	<genexpr>z,_is_valid_include_pattern.<locals>.<genexpr>>   s'      
<
<t47?
<
<
<
<
<
<r(   ) 
NT)anyr)   recompilefnmatch	translateerror)r   r&   	candidates   `  r'   _is_valid_include_patternr<   9   s     u

<
<
<
<';
<
<
<<< u'00Hu! 	5 	5IJw(334444	58   uu 4s   +A# #A65A6basenamec                `     t          |          }|sdS t           fd|D                       S )z8Return True if the basename matches the include pattern.Fc              3  B   K   | ]}t          j         |          V  d S r-   )r8   )r/   r;   r=   s     r'   r1   z)_match_include_pattern.<locals>.<genexpr>T   s/      NN	wx33NNNNNNr(   )r)   r5   )r=   r   r&   s   `  r'   _match_include_patternr@   N   s@    '00H uNNNNXNNNNNNr(   c                  R    e Zd ZdZdddddZddZddZddZedd            Z	dS ) FilesystemFileSearchMiddlewarea  Provides Glob and Grep search over filesystem files.

    This middleware adds two tools that search through local filesystem:

    - Glob: Fast file pattern matching by file path
    - Grep: Fast content search using ripgrep or Python fallback

    Example:
        ```python
        from langchain.agents import create_agent
        from langchain.agents.middleware import (
            FilesystemFileSearchMiddleware,
        )

        agent = create_agent(
            model=model,
            tools=[],  # Add tools as needed
            middleware=[
                FilesystemFileSearchMiddleware(root_path="/workspace"),
            ],
        )
        ```
    T
   )use_ripgrepmax_file_size_mb	root_pathr   rD   r*   rE   intr   r   c                    t          |                                           _        | _        |dz  dz   _        t
          dd fd            }t
          	 	 	 dd fd            }| _        | _        ||g _        dS )a)  Initialize the search middleware.

        Args:
            root_path: Root directory to search.
            use_ripgrep: Whether to use `ripgrep` for search.

                Falls back to Python if `ripgrep` unavailable.
            max_file_size_mb: Maximum file size to search in MB.
        i   /r   r   pathr   c                f   	 	                     |          }n# t          $ r Y dS w xY w|                                r|                                sdS g }|                    |           D ]}|                                rdt          |                    	j                            z   }|	                                }t          j        |j        t          j                                                  }|                    ||f           |sdS d |D             }d                    |          S )a  Fast file pattern matching tool that works with any codebase size.

            Supports glob patterns like `**/*.js` or `src/**/*.ts`.

            Returns matching file paths sorted by modification time.

            Use this tool when you need to find files by name patterns.

            Args:
                pattern: The glob pattern to match files against.
                path: The directory to search in. If not specified, searches from root.

            Returns:
                Newline-separated list of matching file paths, sorted by modification
                time (most recently modified first). Returns `'No files found'` if no
                matches.
            zNo files foundrI   )tzc                    g | ]\  }}|S r.   r.   )r/   p_s      r'   
<listcomp>zPFilesystemFileSearchMiddleware.__init__.<locals>.glob_search.<locals>.<listcomp>   s    1111!111r(   r3   )_validate_and_resolve_pathr   existsis_dirglobis_filer   relative_torF   statr   fromtimestampst_mtimer   utc	isoformatr   join)
r   rJ   	base_fullmatchingmatchvirtual_pathrW   modified_at
file_pathsselfs
            r'   glob_searchz<FilesystemFileSearchMiddleware.__init__.<locals>.glob_search   sD   &( ;;DAA		 ( ( ('''( ##%% (Y-=-=-?-? ('' /1H"00 A A==?? A#&U->->t~-N-N)O)O#OL ::<<D"*"88<"X"X"X"b"b"d"dKOO\;$?@@@ (''11111J99Z(((s    
''Nfiles_with_matchesinclude
str | Noneoutput_mode1Literal['files_with_matches', 'content', 'count']c                   	 t          j        |            n!# t           j        $ r}d| cY d}~S d}~ww xY w|rt          |          sdS d}j        rYt          t          t          j        t          j	                  5  
                    | ||          }ddd           n# 1 swxY w Y   |                    | ||          }|sdS                     ||          S )a  Fast content search tool that works with any codebase size.

            Searches file contents using regular expressions. Supports full regex
            syntax and filters files by pattern with the include parameter.

            Args:
                pattern: The regular expression pattern to search for in file contents.
                path: The directory to search in. If not specified, searches from root.
                include: File pattern to filter (e.g., `'*.js'`, `'*.{ts,tsx}'`).
                output_mode: Output format:

                    - `'files_with_matches'`: Only file paths containing matches
                    - `'content'`: Matching lines with `file:line:content` format
                    - `'count'`: Count of matches per file

            Returns:
                Search results formatted according to `output_mode`.
                    Returns `'No matches found'` if no results.
            zInvalid regex pattern: NzInvalid include patternzNo matches found)r6   r7   r:   r<   rD   r   FileNotFoundError
subprocessCalledProcessErrorTimeoutExpired_ripgrep_search_python_search_format_grep_results)r   rJ   rf   rh   eresultsrc   s         r'   grep_searchz<FilesystemFileSearchMiddleware.__init__.<locals>.grep_search   sn   65
7####8 5 5 54444444445  18AA 100 G K%1-  K K
 #227D'JJGK K K K K K K K K K K K K K K --gtWEE *)) ,,WkBBBs&    6166?B##B'*B')rI   )r   r   rJ   r   r   r   )rI   Nre   )
r   r   rJ   r   rf   rg   rh   ri   r   r   )	r   resolverF   rD   max_file_size_bytesr	   rd   rt   tools)rc   rF   rD   rE   rd   rt   s   `     r'   __init__z'FilesystemFileSearchMiddleware.__init__p   s      i0022&#3d#:T#A  
(	) (	) (	) (	) (	) (	) 
(	)T 
 "&Ma	4	C 4	C 4	C 4	C 4	C 4	C 
4	Cl '&!;/


r(   rJ   r   c                L   |                     d          sd|z   }d|v sd|v rd}t          |          |                    d          }| j        |z                                  }	 |                    | j                   n## t          $ r d| }t          |          dw xY w|S )z7Validate and resolve a virtual path to filesystem path.rI   z..~zPath traversal not allowedzPath outside root directory: N)
startswithr   lstriprF   ru   rV   )rc   rJ   msgrelative	full_paths        r'   rQ   z9FilesystemFileSearchMiddleware._validate_and_resolve_path   s     s## 	:D 4<<3$;;.CS//! ;;s##^h.7799		,!!$.1111 	, 	, 	,8$88CS//t+	, s   &B  B!r   	base_pathrf   rg    dict[str, list[tuple[int, str]]]c                   	 |                      |          }n# t          $ r i cY S w xY w|                                si S ddg}|r|                    d|g           |                    d|t	          |          g           	 t          j        |dddd          }n3# t
          j        t          f$ r | 	                    |||          cY S w xY wi }|j
                                        D ]}	 t          j        |          }	|	d	         d
k    r|	d         d         d         }
dt	          t          |
                              | j                            z   }|	d         d         }|	d         d         d                             d          }||vrg ||<   ||                             ||f           # t          j        t(          f$ r Y w xY w|S )z Search using ripgrep subprocess.rgz--jsonz--globz--T   F)capture_outputtexttimeoutchecktyper_   datarJ   r   rI   line_numberlinesr3   )rQ   r   rR   extendr   rl   runrn   rk   rp   stdout
splitlinesjsonloadsr   rV   rF   rstripr   JSONDecodeErrorKeyError)rc   r   r   rf   r]   cmdresultrs   liner   rJ   r`   line_num	line_texts                 r'   ro   z.FilesystemFileSearchMiddleware._ripgrep_search  s.   	77	BBII 	 	 	III	 !! 	I X 	,JJ'*+++

D'3y>>2333
	D^#  FF )+<= 	D 	D 	D&&w	7CCCCC	D
 57M,,.. 	 	Dz$''<7**</7D#&T$ZZ-C-CDN-S-S)T)T#TL#F|M:H $VW 5f = D DT J JI#72202-L)00(I1FGGG((3    s1    ''B -CC.CF55GGc                   	 |                      |          }n# t          $ r i cY S w xY w|                                si S t          j        |          }i }|                    d          D ]}|                                s|rt          |j        |          s0|	                                j
        | j        k    rS	 |                                }n# t          t          f$ r Y |w xY wt          |                                d          D ]j\  }	}
|                    |
          rPdt%          |                    | j                            z   }||vrg ||<   ||                             |	|
f           k|S )z%Search using Python regex (fallback).*r   rI   )rQ   r   rR   r6   r7   rglobrU   r@   namerW   st_sizerv   	read_textUnicodeDecodeErrorPermissionError	enumerater   searchr   rV   rF   r   )rc   r   r   rf   r]   regexrs   	file_pathcontentr   r   r`   s               r'   rp   z-FilesystemFileSearchMiddleware._python_search8  s   	77	BBII 	 	 	III	 !! 	I
7##46 #-- 	C 	CI$$&&   5ingNN  ~~'$*BBB#--//&8    #,G,>,>,@,@!"D"D C C$<<%% C#&Y-B-B4>-R-R)S)S#SL#72202-L)00(D1ABBBC s    ''?CC('C(rs   rh   c           	        |dk    r4d                     t          |                                                     S |dk    rfg }t          |                                           D ]-}| |         D ]"\  }}|                    | d| d|            #.d                     |          S |dk    rjg }t          |                                           D ]1}t	          | |                   }|                    | d|            2d                     |          S d                     t          |                                                     S )z)Format grep results based on output mode.re   r3   r   :count)r\   sortedkeysr   len)rs   rh   r   r   r   r   r   s          r'   rq   z3FilesystemFileSearchMiddleware._format_grep_resultsc  sZ    ...99VGLLNN33444)##E#GLLNN33 C C	&-i&8 C CNHdLLI!A!A!A!A4!A!ABBBBC99U###'!!E#GLLNN33 5 5	GI.//	33E33444499U### yy//000r(   N)rF   r   rD   r*   rE   rG   r   r   )rJ   r   r   r   )r   r   r   r   rf   rg   r   r   )rs   r   rh   r   r   r   )
__name__
__module____qualname____doc__rx   rQ   ro   rp   staticmethodrq   r.   r(   r'   rB   rB   W   s         8 ! "y0 y0 y0 y0 y0 y0v   03 3 3 3j) ) ) )V 1 1 1 \1 1 1r(   rB   )r   r   r   r   )r   r   r   r*   )r=   r   r   r   r   r*   )r   
__future__r   r8   r   r6   rl   
contextlibr   r   r   pathlibr   typingr   langchain_core.toolsr	   !langchain.agents.middleware.typesr
   r   r   r   r)   r<   r@   rB   __all__r.   r(   r'   <module>r      sd    # " " " " "   				           ' ' ' ' ' ' ' '             % % % % % % ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^   D   *O O O Og1 g1 g1 g1 g1_Z	5JHV_5_%` g1 g1 g1V	 %r(   