
    ie                     H   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mZ ddl	m
Z
 ddlmZmZmZmZmZmZmZmZmZmZ ddlmZmZ ddlmZ ddlmZ dd	lmZ  G d
 d      Zde ddfdZ!dddddde"de#de"dee ef   dz  dee ef   f
dZ$	 ddddddddee  ed      f   dee" ed      f   dee# ed      f   dee" ed       f   dee# ed!      f   dee ef   dz  dee ef   fd"Z%dddd#dee  ed$      f   d%ee" ed&      f   d'ee" ed(      f   dee ef   dz  dee ef   f
d)Z&dddd*dee  ed+      f   dee" ed,      f   d-ee" ed.      f   dee ef   dz  dee ef   f
d/Z'dd0d1e dee ef   dz  dee   fd2Z(d3d4dd5de d6e d7e d8ed9   dee ef   dz  dee ef   fd:Z)dd;d3dd<de d=e#de#d7e dee ef   dz  dee ef   fd>Z*d?d@ddAdddBdee  edC      f   dDee# edE      f   dFee# edG      f   dHee" edI      f   d7ee  edJ      f   dKee" edL      f   dee ef   dz  dee ef   fdMZ+ edN       G dO dP             Z,ddQdAdRdddSdee  edT      f   dDee# edU      f   dVeee#    edW      f   dXeee     edY      f   d7ee  edZ      f   d[ee  ed\      f   d]eee"    ed^      f   dee ef   dz  dee ef   fd_Z-ddd`daee  edb      f   dcee  edd      f   d4ee" ede      f   dee ef   dz  dee ef   f
dfZ.ddd`daee  edg      f   dcee  edh      f   d4ee" edi      f   dee ef   dz  dee ef   f
djZ/ddd`daee  edg      f   dcee  edh      f   d4ee" edk      f   dee ef   dz  dee ef   f
dlZ0ddddddmdmdddn	doee  edp      f   dqeeee        edr      f   dseeee        edt      f   duee" edv      f   dwee" edx      f   dyee# edz      f   d{ee# ed|      f   d}ee# ed~      f   dee" ed      f   dee ef   dz  dee ef   fdZ1de
d7e de2e e f   fdZ3dee    fdZ4 ejj                  d      Z6de de fdZ7de de2ee    e"f   fdZ8de de#de dee ef   fdZ9dee    dDe#de de"de f
dZ:deee ef      dee,   fdZ;dDe#dVee#   dXee    deee ef      fdZ<dee,   ddfdZ=dee    dee,   ddfdZ>de de de fdZ?de
d4e"ddfdZ@deee       dee    fdZAde
dee    dee    de"dee
   f
dZBde
de"fdZCde dee    de"fdZDde
dee    fdZEdee    deej                  e       de de dwe"due"deee ef      fdZGdee    de#de#de"dee    f
dZHy)z:File-related function tools for model-invoked file access.    N)	dataclass)Path)
	AnnotatedAnyDictIterableListLiteralMappingMutableSequenceOptionalSequence)MessageBlockMessageBlockType)AttachmentStore)iter_workspace_entries)	ParamMetac                       e Zd ZdZdeeef   dz  fdZedede	fd       Z
ededefd	       Zeded
edefd       Zdeez  defdZdeez  defdZdeez  dz  dee   fdZdeez  dz  dee   fdZy)FileToolContextz=Helper to read runtime context injected via `_context` kwarg.ctxNc                     |t        d      || _        | j                  |j                  d            | _        | j                  |j                  d            | _        | j                  |j                  d      | j                        | _        y )Nz#_context is required for file toolsattachment_storepython_workspace_rootgraph_directory)	
ValueError_ctx_require_storegetr   _require_workspaceworkspace_root_require_session_rootsession_root)selfr   s     L/Users/bowang/.openclaw/workspace/ChatDev/functions/function_calling/file.py__init__zFileToolContext.__init__!   sz    ;BCC	 $ 3 3CGG<N4O P"55cgg>U6VW 66sww?P7QSWSfSfg    storereturnc                 <    t        | t              st        d      | S )Nz&attachment_store missing from _context)
isinstancer   r   )r'   s    r$   r   zFileToolContext._require_store)   s    %1EFFr&   rootc                 x    | t        d      t        |       j                         }|j                  dd       |S )Nz+python_workspace_root missing from _contextTparentsexist_ok)r   r   resolvemkdir)r+   paths     r$   r   z"FileToolContext._require_workspace/   s:    <JKKDz!!#

4$
/r&   r    c                 ~    | xs |j                   }t        |      j                         }|j                  dd       |S )NTr-   )parentr   r0   r1   )r+   r    baser2   s       r$   r!   z%FileToolContext._require_session_root7   s9    ,~,,Dz!!#

4$
/r&   relative_pathc                     t        |      }|j                         r|j                         n| j                  |z  j                         }| j                  |j                  vr|| j                  k7  rt        d      |S )NzPath is outside workspace)r   is_absoluter0   r    r.   r   )r#   r6   reltargets       r$   resolve_under_workspacez'FileToolContext.resolve_under_workspace>   sg    =!"%//"3$:M:MPS:S9\9\9^fnn44CVCV9V899r&   c                    t        |      }g }|j                         r |j                  |j                                nK|j                  | j                  |z  j                                |j                  |j                                |D ]-  }| j                  |j
                  v s|| j                  k(  s+|c S  t        d      )Nz!Path is outside session directory)r   r8   appendr0   r"   r.   r   )r#   r6   raw
candidatesr:   s        r$   resolve_under_sessionz%FileToolContext.resolve_under_sessionE   s    =!
??ckkm,t0036??ABckkm, F  FNN2f@Q@Q6Q ! <==r&   absolute_pathc                     |sy t        |      j                         }| j                  |j                  v s|| j                  k(  r)|j	                  | j                        j                         S t        |      S N)r   r0   r"   r.   relative_toas_posixstr)r#   rA   r:   s      r$   to_session_relativez#FileToolContext.to_session_relativeR   sd    m$,,..&D<M<M2M%%d&7&78AACC6{r&   c                     |sy t        |      j                         }| j                  |j                  v s|| j                  k(  r/|j	                  | j                        }|j                         xs dS y )N.)r   r0   r    r.   rD   rE   )r#   rA   r:   r9   s       r$   to_workspace_relativez%FileToolContext.to_workspace_relativeZ   sd    m$,,.&..0Fd>Q>Q4Q$$T%8%89C<<>(S(r&   )__name__
__module____qualname____doc__r   rF   r   r%   staticmethodr   r   r   r   r!   r;   r@   r   rG   rJ    r&   r$   r   r      s    GhDcNT1 h c o  
     C  $  S4Z D >3: >$ >td1B xPS} 3:3D RU r&   r   r2   r(   c                 <    | j                  d      rt        d      y )Nattachmentsz:Modifications to the attachments directory are not allowed)
startswithr   r2   s    r$   _check_attachments_not_modifiedrU   d   s    }%UVV &r&   T   F)	recursivelimitinclude_hidden_contextrW   rX   rY   rZ   c                    d}t        |      }g }t        d|      }t        |j                  | ||      D ]  }t	        |      |k\  r n|j                  |j
                  z  j                         }	t        |j
                        }
|j                  |j
                  t        |j
                        j                  d|
|	|j                  |j                  |j                  d        d|d| iS )zY
    List accessible files from the attachment store and the current code_workspace.
          )rW   	max_depthrY   	workspace)idnamesourcer2   rA   typesizedepthfilesN)r   maxr   r    lenr2   r0   r   r=   ra   rc   rd   re   )rW   rX   rY   rZ   r^   r   entriestotal_limitentryabs_pathworkspace_paths              r$   describe_available_filesrn   h   s     I
(
#C$&Ga-K. (%	 w<;&&&3<<>ejj)jjUZZ(--%&!)



		
0 W\k*++r&      i  )rW   r^   rY   rX   rZ   z!Workspace-relative directory path)descriptionzTraverse subdirectoriesr^   z!Maximum depth when recursive=Truez!Include entries starting with '.'zMaximum entries to returnc          	      J   t        |      }|j                  |       }|j                         st        d|        |j	                         st        d|        |dk  rt        d      |r|dk  rt        d      g }|dfg}	|j                  |      xs d}
|	rEt        |      |k  r6|	j                         \  }}	 t        |j                         d 	      }|D ]  }|j                  |      }|st        |      r"d
}d
}	 |j                         }|j                   }|j#                         r|j$                  }|j(                  |j+                         t-        |      |j	                         rdnd|||d}|j/                  |       t        |      |k\  r n5|s|j	                         s|dz   |k  s|	j/                  ||dz   f        |	rt        |      |k  r6|
|d
| t        |      |k\  |dS # t        t        f$ r Y pw xY w# t        t        t&        f$ r Y w xY w)z0List contents of a workspace-relative directory.zDirectory not found: zPath is not a directory: r   zlimit must be positiver]   z%max_depth must be >= 1 when recursiverI   c                 6    | j                   j                         S rC   )ra   lower)ps    r$   <lambda>z list_directory.<locals>.<lambda>   s    qvv||~r&   keyN	directoryfile)ra   r6   rA   rc   rd   modified_tsre   )rx   ri   	truncatedrW   )r   r;   existsFileNotFoundErroris_dirNotADirectoryErrorr   rJ   rh   popsortediterdirPermissionErrorrD   _path_is_hiddenstatst_mtimeis_filest_sizeOSErrorra   rE   rF   r=   )r2   rW   r^   rY   rX   rZ   r   r:   ri   stackbase_relativecurrentre   childrenchildr9   	stat_sizemodifiedr   rk   s                       r$   list_directoryr      s     (
#C((.F==?"7v >??==? #<TF!CDDz122Y]@AA$&G&,a[ME--f5<M
CL5(	goo/5MNH E##F+C!oc&:IHzz|====? $I 

!$!$U',||~6!'E NN5!7|u$U\\^	I0EeUQY/05  CL5(F #6E?\U*	 = "?3 		 &@ s$   =G5 8H5HHH"!H")r.   r/   rZ   zWorkspace-relative folder pathr.   z!Create missing parent directoriesr/   z%Do not raise if folder already existsc                D   | st        d      t        |        t        |      }|j                  |       }|j	                         r|j                         st        d      |j	                         }|j                  ||       |j                  |      t        |      | dS )z,Create a directory tree under the workspace.path must be providedz$Target exists and is not a directoryr-   )r2   rA   created)	r   rU   r   r;   r|   r~   r1   rJ   rF   )r2   r.   r/   rZ   r   r:   previously_existss          r$   create_folderr      s     011#D)
(
#C((.F}}v}}?@@
LL8L4 ))&1V(( r&   )rW   
missing_okrZ   z&Workspace-relative file or folder pathz0Allow deleting non-empty directories recursivelyr   z!Suppress error if path is missingc                   | st        d      t        |        t        |      }|j                  |       }|j	                         s/|r|j                  |      t        |      dddS t        d|        |j                         r%|st        d      t        j                  |       d}n|j                          d}|j                  |      t        |      d	|d
S )z%Delete a workspace file or directory.r   Fmissing)r2   rA   deletedreasonzPath not found: z(Set recursive=True to delete directoriesrx   ry   T)r2   rA   r   rc   )r   rU   r   r;   r|   rJ   rF   r}   r~   IsADirectoryErrorshutilrmtreeunlink)r2   rW   r   rZ   r   r:   deleted_types          r$   delete_pathr     s     011#D)
(
#C((.F==?11&9!$V #	   "24& 9::}}#$NOOf" ))&1V	 r&   )rZ   
path_or_idc                   t        |      }|j                  j                  |       }|r|j                         gS |j	                  |       }|j                         r|j                         st        d|        t        j                  |j                        d   xs d}|j                  j                  |t        j                  |      |j                  |dddd| dd	      }|j                         gS )
zT
    Load an attachment by ID or register a workspace file as a new attachment.
    zWorkspace file not found: r   zapplication/octet-streamFTr_   	reference)rb   rm   storage)kinddisplay_name	mime_type	copy_filepersistdeduplicateextra)r   r   r   as_message_blockr;   r|   r   r   	mimetypes
guess_typera   register_filer   from_mime_type)r   rZ   r   recordr:   r   s         r$   	load_filer   =  s     (
#C !!%%j1F'')** ((4F==?&.."25j\BCC $$V[[1!4R8RI!!//,,Y7[[!("
 0 F ##%&&r&   utf-8	overwrite)encodingmoderZ   contentr   r   )r   r=   c                f   |dvrt        d      t        |      }|j                  |       }|j                         r|j	                         rt        d      |j
                  j                  dd       |j                  |      }|dk(  rdnd}	 |j                  |      5 }	|	j                  |       d	d	d	       |j                         r|j                         j                  nd	}|j                  |      t        |      |dS # 1 sw Y   SxY w# t        $ r}
t        d
| d|
       |
d	}
~
ww xY w)a  
    Persist data to a workspace file while optionally registering it as an attachment.

    Args:
        path: Relative path where the file will be written.
        content: Plain-text payload encoded with `encoding`.
        encoding: Text encoding used when `content` is provided.
        mode: Whether to replace the file (`overwrite`) or append to it (`append`).

    Returns:
        A dictionary describing the persisted file, including workspace path, absolute path,
        and byte size.

    Raises:
        ValueError: If arguments are missing/invalid or the path escapes the workspace.
        OSError: If the file cannot be written.
    >   r=   r   z+mode must be either 'overwrite' or 'append'z!Target path points to a directoryTr-   r   wbabNzFailed to write file 'z': )r2   rA   rd   )r   r   r;   r|   r~   r4   r1   encodeopenwriter   r   r   rJ   rF   )r2   r   r   r   rZ   r   r:   data
write_modehandleexcrd   s               r$   	save_filer   f  s   4 **FGG
(
#C((.F}}6==?<==
MMt4>>(#D,$JJ[[$LL %
 %+MMO6;;=  D))&1V  %$ J.vhc#?@cIJs0   D  D2D D	D 	D0D++D0i  )offsetrX   r   rZ   r   c                   t        |      }d}	 |j                  |       }|r"|j                         r|j	                         r|}|?|j                  |       }|j                         r|j	                         st        d|        |j                  |d      }||||z    }	|	||z   t        |      k  t        |      |dS # t        $ r d}Y w xY w)zGRead a snippet of a workspace text file without loading entire content.Nz1File not found in session attachments/workspace: replace)r   errors)snippetr{   lengthr   )r   r;   r   r|   r   r@   	read_textrh   )
r2   r   rX   r   rZ   r   r:   	candidater   r   s
             r$   read_text_file_snippetr     s     (
#CF//5	 Y%%'I,=,=,?~**40}}fnn&6PQUPVWXXXi@D6FUN+Ge^c$i/d)	   	s   B? ?CCr]   (   auto)
start_line
line_countinline_line_numbersr   include_line_offsetsrZ   z!Workspace-relative text file pathr   z!1-based line to begin the snippetr   z3Number of lines to include starting from start_liner   zIIf true, prefix each snippet line with its line number inside the snippetzExplicit encoding or 'auto'r   z6Include 1-based line metadata for the returned snippetc                N   |dk  rt        d      |dk  rt        d      t        |      }|j                  |       }|j                         r|j	                         st        d|        t        ||      \  }	}
t        |	      }|j                         }|	j                  d      }|sdg}t        |      }|dz
  }||k\  rt        d      t        |||z
        }||z   }||| }dj                  |      }|}d	g}|D ]"  }|j                  |d
   t        |      z          $ ||   }|j                  |      |
||||z   dz
  ||||||k  |j                  |j                   dd}|r"t#        ||||j%                  d            }||d<   |r|j'                  t)        |	||             |S )z6Read a line range plus metadata from a workspace file.r]   start_line must be >= 1zline_count must be >= 1File not found: T)keepends z:start_line is beyond the total number of lines in the filer   
line_range)r2   r   newliner   end_liner   lines_returnedtotal_linesr   r{   	file_sizerz   r   

r   )r   r   r;   r|   r   r}   _read_text_content_detect_newliner   
splitlinesrh   minjoinr=   rJ   r   r   !_render_snippet_with_line_numbersendswithupdate_describe_segment_line_offsets)r2   r   r   r   r   r   rZ   r   r:   textused_encodingnewline_styler   lines_with_breaksr   	start_idxr   end_idxsegment_linesr   raw_snippetline_startsline
start_charresponses                            r$   read_file_segmentr     s   $ A~233A~233
(
#C((.F==?&.."2"24& 9::,VX>D-#D)M;;=D6D'(KQIKUVV[9%<=N.(G%i8Mggm$GKSK!;r?SY67 "Y'J ))&1!  /!3 ("{*\\}} H  3  !56	
 &6tZUVOr&   )frozenc                   6    e Zd ZU dZeed<   eed<   ee   ed<   y)TextEditz0Normalized representation of a single line edit.r   r   replacement_linesN)rK   rL   rM   rN   int__annotations__r	   rF   rP   r&   r$   r   r     s    :OMCy r&   r   r   preserve)r   replacementr   r   ensure_trailing_newlinerZ   zWorkspace-relative file to editz/1-based line where the replacement should beginr   z>Last line (>= start_line-1) to replace; defaults to start_liner   z0Text that should replace the selected line rangezText encoding or 'auto'r   z0Newline style: 'preserve', 'lf', 'crlf', or 'cr'r  zFForce presence/absence of trailing newline; default preserves originalc          	         t        |      }|j                  |       }	|	j                         r|	j                         st	        d|        t        |        t        t        |||            }
t        |	|      \  }}t        |      \  }}t        |t        |            }t        ||
       ||}n|}|j                  |      }|r||z  }|	j                  j                  dd       |	j!                  ||       |	j#                         }|j%                  |	      ||t'        |      t'        |
      ||j(                  |j*                  dS )z@Apply ordered line edits with newline and encoding preservation.r   Tr-   r   )r2   r   r   r   applied_editstrailing_newliner   rz   )r   r;   r|   r   r}   rU   _normalize_edits_build_single_editr   _split_lines_resolve_newline_choicer   _apply_edits_in_placer   r4   r1   
write_textr   rJ   rh   r   r   )r2   r   r   r   r   r   r  rZ   r   r:   
normalizedoriginal_textr   lineshad_trailing_newliner   final_trailingrenderedr   s                      r$   apply_text_editsr    s:   2 (
#C((.F==?&.."2"24& 9::#D)!"4Z;"WXJ#5fh#G M=".}"=E+G_]5STM%,&-0!!%(HM!
MMt4
h7;;=D))&1! %jZ*\\}}	 	r&   )r   rZ   srcz Existing workspace-relative pathdstzNew workspace-relative pathz'Allow replacing an existing destinationc                   t        |      }|j                  |       }|j                  |      }t        |        t        |       |j                         st	        d|        ||k(  r|j                  |      dddS t        ||       |j                  j                  dd       |j                  |       |j                  |      |j                  |      ddS )z1Rename files or directories inside the workspace.Source does not exist: renameTr2   	operationskippedr-   )r2   previous_pathr  )
r   r;   rU   r|   r}   rJ   _clear_destinationr4   r1   r  r  r  r   rZ   r   rb   destinations          r$   rename_pathr  Y  s     (
#C((-F--c2K#C(#C(==?"9# ?@@--k:!
 	
 {I.TD9
MM+))+6226: r&   zSource workspace-relative pathz#Destination workspace-relative pathz(Allow replacing destination if it existsc                   t        |      }|j                  |       }|j                  |      }t        |       |j                         st	        d|        |j                         r|st        d|       t        |d       |j                  j                  dd       |j                         rt        j                  ||       nt        j                  ||       |j                  |      |j                  |      ddS )z&Copy a file tree within the workspace.r  Destination already exists: T)r   r-   copyr2   rb   r  )r   r;   rU   r|   r}   FileExistsErrorr  r4   r1   r~   r   copytreecopy2rJ   r  s          r$   	copy_pathr'  ~  s     (
#C((-F--c2K#C(==?"9# ?@@!$@"FGG;$7TD9}},V[)))+6++F3 r&   z Allow replacing destination pathc                   t        |      }|j                  |       }|j                  |      }t        |        t        |       |j                         st	        d|        ||k(  r|j                  |      dddS t        ||       |j                  j                  dd       t        j                  ||       |j                  |      |j                  |      ddS )zEMove files or directories, mirroring `mv` semantics across platforms.r  moveTr  r-   r#  )r   r;   rU   r|   r}   rJ   r  r4   r1   r   r)  r  s          r$   	move_pathr*    s     (
#C((-F--c2K#C(#C(==?"9# ?@@--k:
 	

 {I.TD9
KK$))+6++F3 r&      )	globsexclude_globs	use_regexcase_sensitivemax_resultsbefore_contextafter_contextrY   rZ   patternzPlain text or regex patternr,  z&Restrict search to these glob patternsr-  zGlob patterns to excluder.  zTreat pattern as regexr/  zMatch case when Truer0  zStop after this many matchesr1  zLines to include before matchr2  zLines to include after matchzSearch hidden files/foldersc       	            |dk  rt        d      t        |	      }
t        |      xs dg}t        |      }g }d}d}|r| n| j                         }|r;t        j
                  }|s|t        j                  z  }t	        j                  | |      }t        |
j                  |||      D ]  }|dz  }t        |      }|st        |||| ||      D ]o  }t        ||d   |d      }t        ||d   |d	      }|j                  |
j                  |      |d   |d
   |d   ||d       t        |      |k\  sf|dd|dc c S   |d	d|dS )z5Search workspace files and return structured matches.r   zmax_results must be positivez**/*Nr]   line_numberT)beforeFcolumn	line_text)ry   r   r7  r8  r6  afterpython)matcheslimitedenginesearched_files)r   r   _normalize_globsrs   re	MULTILINE
IGNORECASEcompile_iter_candidate_filesr    _read_file_lines_for_search_iter_line_matches_slice_contextr=   rJ   rh   )r3  r,  r-  r.  r/  r0  r1  r2  rY   rZ   r   include_patternsexclude_patternsr;  r>  compiled_regexliteralflagsr   r  matchr6  r9  s                          r$   search_in_filesrN    s   * a788
(
#C'.:6('6$&GN04N'gW]]_GR]]"EGU3*		 	!+I6'
E $E5+?X\]F"5%*>V[\ENN55i@!-0#Ho!&{!3$"	 7|{*&#&&4	 +
N (	 r&   c                     |dk7  r| j                  |      |fS | j                         }t               D ]  }	 |j                  |      |fc S  |j                  dd      dfS # t        $ r Y :w xY w)Nr   r  r   r   )r   )r   
read_bytes_candidate_encodingsdecodeUnicodeDecodeError)r2   r   r>   r   s       r$   r   r     s    6~~x~0(::
//
C)+		::i()33 ,
 ::gi:0'99 " 		s   A##	A/.A/c                      t        j                  d      xs d} dd| ddddg}t               }g }|D ]?  }|xs dj                         }|r||v r|j	                  |       |j                  |       A |S )	NFr   z	utf-8-sigr   zutf-16z	utf-16-lez	utf-16-bezlatin-1)localegetpreferredencodingsetrs   addr=   )	preferredorderedseenresultitemr  s         r$   rQ  rQ  '  s    ++E28bIG UDFjb'')
Z4/d  Mr&   z
\r\n|\r|\nr   c                      d| v ryd| v rd| vryy)Nr   r   r   rP   )r   s    r$   r   r   @  s     ~t|D(r&   c                 T    | sg dfS | j                  d      }| j                         |fS )NFr   )r   r   )r   has_trailings     r$   r  r  H  s0    5y==!56L??l**r&   	full_textstart_indexr   c                    | d| }d}d}t         j                  |      D ]  }|dz  }|j                         } ||z
  }|d|dg}|}	d}
t         j                  |      D ]:  }|j                         }
|	dz  }	|j                  |	|j                         dd       < |r |
rt	        |      |
z
  }n|t	        |      z   }n|}|||	||dS )zZReturn 1-based line metadata (columns are 0-based) for a snippet extracted from full_text.Nr]   r   )r   r   r7  )r   start_columnr   
end_columnline_offsets)_LINE_BREAK_REfinditerendr=   rh   )ra  rb  r   before_segmentr   last_break_endrM  rd  rf  r5  last_break_insidere  s               r$   r   r   O  s     |,NJN((8a
 9 /L qLA*L K((1!IIKq[EIIKSTUV 2
 W(99J%G4J!
 !$ $ r&   r  r   preserve_trailing_newlinec                     g }t        |       D ]/  \  }}|j                  d      }|j                  ||z    d|        1 |j                  |      }|r|r||z  }|S )Nr   :)	enumeraterstripr=   r   )	r  r   r   rm  numberedidxr   bodyr  s	            r$   r   r   u  sm     Hu%	T{{6":+,AdV45 & !!(+H XM!Or&   editsc           	         | st        d      g }| D ]  }t        |t              st        d      	 t        |d         }|j                  d|      }	 t        |      }|dk  rt        d      ||dz
  k  rt        d	      |j                  d
d      }t        |t              st        d      |j                  t        |||j                                       |j                  d        t        |       |S # t        t
        t         f$ r}t        d      |d }~ww xY w# t
        t         f$ r}t        d      |d }~ww xY w)Nz)at least one edit instruction is requiredz(each edit entry must be a mapping objectr   z$start_line is required for each editr   zend_line must be an integerr]   r   z"end_line must be >= start_line - 1r   r   zreplacement must be a string)r   r   r   c                 2    | j                   | j                  fS rC   )r   r   )edits    r$   ru   z"_normalize_edits.<locals>.<lambda>  s    doot}}%Er&   rv   )r   r*   r   r   KeyError	TypeErrorr   rF   r=   r   r   sort_validate_edit_ranges)ru  r  r]  r   r   end_line_rawr   r   s           r$   r  r    sV   DEE!#J$(GHH	NT,/0J xx
J7	E<(H >677j1n$ABBhh}b1+s+;<<%!"-"8"8":	
' 6 OOEOF*%1 )Z0 	NCD#M	N
 :& 	E:;D	Es/   C:D":DDD"E1D==Ec                 (    ||n| }| |||ndd}|gS )Nr   )r   r   r   rP   )r   r   r   effective_endpayloads        r$   r  r    s1    
 !) 4H*M !&1&={2G
 9r&   c                     d}| D ]P  }t        |j                  |j                  dz
        }|j                  |k  r|dkD  rt        d      t        ||      }R y )Nr   r]   z?edit ranges overlap; merge them before calling apply_text_edits)rg   r   r   r   )ru  previous_range_endrx  r  s       r$   r|  r|    sZ    DMM4??Q+>???005G!5K^__ !3]C	 r&   c                    t        |      D ]  }t        |       }|j                  |dz   kD  rt        d      t	        |j                  dz
  |      }||kD  rt        d      t        |j                  |j                  z
  dz   d      }|dkD  r;t	        |j                  t        |             }t        ||j                  z
  dz   d      }||z   }|j                  | ||  y )Nr]   z(start_line is beyond the end of the filer   )reversedrh   r   r   r   rg   r   r   )r  ru  rx  current_line_countr   removal_countr   r   s           r$   r
  r
    s     Z??/!33GHH!+-?@	))GHHDMMDOO;a?C14==#e*5H4?? :Q >BMm+#'#9#9i   r&   
preferencedetectedc                 v    | xs dj                         }|dk(  ry|dk(  ry|dk(  ry|xs t        j                  S )Nr   lfr   crlfr   crr   )rs   oslinesep)r  r  r  s      r$   r	  r	    sE    "))+JTVT!rzz!r&   r  c                     | j                         sy |st        d|        | j                         rt        j                  |        y | j                          y )Nr!  )r|   r$  r~   r   r   r   )r  r   s     r$   r  r    sK     <[MJKKk"r&   patternsc                 Z    | sg S g }| D ]  }|s|j                  t        |             ! |S rC   )r=   rF   )r  r  r>   s      r$   r?  r?    s9    	J#c(#  r&   r+   rH  rI  c              #   (  K   t               }|D ]  }| j                  |      D ]i  }|j                         s|j                  |       }|j	                         }||v r:|st        |      rHt        ||      rU|j                  |       | k  y wrC   )rW  globr   rD   rE   r   _is_excludedrX  )	r+   rH  rI  rY   yieldedr3  r   r9   rel_keys	            r$   rD  rD    s      G#7+I$$&''-CllnG'!!oc&:G%56KK O , $s   BBc                 :    t        d | j                  D              S )Nc              3   >   K   | ]  }|j                  d         yw)rI   N)rS   ).0parts     r$   	<genexpr>z"_path_is_hidden.<locals>.<genexpr>	  s     ;
ts#
s   )anypartsrT   s    r$   r   r     s    ;

;;;r&   relative_posixc                 B    |D ]  }t        j                   | |      s y y)NTF)fnmatch)r  rI  r3  s      r$   r  r    s"    #??>73 $ r&   c                 B    t        | d      \  }}|j                         S )Nr   r  )r   r   )r2   r>   _s      r$   rE  rE    s    v6FC>>r&   rJ  literal_loweroriginal_patternc           
   #     K   t        |       D ]  \  }}|dz   }|}	|r2|0|j                  |	      D ]  }
||
j                         dz   |	d  A|sD|r|	n|	j                         }|r|n|}|j	                  |      }|dk7  su||dz   |	d |j	                  ||t        t        |      d      z         }|dk7  r9 y w)Nr]   )r5  r7  r8  r   )rp  rh  startrs   findrg   rh   )r  rJ  r  r  r/  r.  rs  raw_liner5  r8  rM  haystackneedler  s                 r$   rF  rF    s      #5)XAg	3'00;#.#kkma/!*  < $$2y	8IH)7%]FMM&)E2+#.#ai!* 
 !fec#f+q6I.IJ 2+! *s   B B?8B?<B?center_linespanr6  c                    |dk  rg S |rt        ||z
  d      }|dz
  }n|dz   }t        ||z   t        |             }||k  rg S |dz
  }|}t        | ||       S )Nr   r]   )rg   r   rh   list)r  r  r  r6  r   r   r   r   s           r$   rG  rG  9  sx     qy	t+Q/
? 1_
{T)3u:6*	QIGi())r&   )rI   )IrN   r  rU  r   r  r@  r   dataclassesr   pathlibr   typingr   r   r   r   r	   r
   r   r   r   r   entity.messagesr   r   utils.attachmentsr   utils.workspace_scannerr   utils.function_catalogr   r   rF   rU   boolr   rn   r   r   r   r   r   r   r   r   r  r  r'  r*  rN  tupler   rQ  rC  rg  r   r  r   r   r  r  r|  r
  r	  r  r?  rD  r   r  rE  PatternrF  rG  rP   r&   r$   <module>r     s   @    	 	  !    ; - : ,C CLW# W$ W  &*>,>, >, 	>, 38nt#>, 
#s(^>,D VYB TY\]bgPS&*B
C/RSS
TB y5NOOPB i4WXXY	B
 dI:]$^^_B S)0KLLMB 38nt#B 
#s(^BR 
&*
C/OPP
Q tY3VWWX
 i4[\\] 38nt# 
#s(^J 	&*-
C/WXX
Y- PQ	S- $	6Y ZZ[- 38nt#- 
#s(^-h '+	&'&' 38nt#	&'
 
,&'Z +6&*3
33 	3
 '
(3 38nt#3 
#s(^3r &* 
    	 
   38nt#  
#s(^ L \]mo 	SY 	&*O
C/RSS
TO #y5XYYZO #y5jkkl	O
 #ij	lO Y3PQQRO $VW	YO 38nt#O 
#s(^Od $! ! ! 	 	OU  	&*+<
C/PQQ
R< #y5fggh< ^_	a	< PQ	S< Y3LMMN< PQ	S<" 'fg	i#<* 38nt#+<, 
#s(^-<L 	&*"	3	.PQQ	R"	3	.KLL	M" GH	J	" 38nt#" 
#s(^"X 	&*!	3	.NOO	P!	3	.STT	U! HI	K	! 38nt#! 
#s(^!V 	&*!	3	.NOO	P!	3	.STT	U! @A	C	! 38nt#! 
#s(^!T 	 	PTSXWZ[\YZZ_&*#QsI2OPPQQ #FG	IQ #89	;Q y5MNNOQ dI:P$QQRQ 3	6T UUVQ c99X#YYZQ S)8V"WWXQ  dI:W$XXY!Q" 38nt##Q$ 
#s(^%Qh
:T 
:S 
:U38_ 
:d3i , M*# # +s +uT#Y_5 +#c # #c #VZ[^`c[cVd #LC=   $	
 	 !HWS#X%67 !DN !Hsm # 
'#s(
	D(!3 D D:!5 :hx>P :UY : " "s "s "D T d x6 49 
sm sm 	
 d^.<$ <4 <  $ d tCy 
KC=KRZZ_-K K 	K
 K K d38nKB*C=** *
 * 
#Y*r&   