2025-04-19 19:45:42 +01:00
/**
* @license
* Copyright 2025 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
2025-09-10 09:54:50 -07:00
import fs from 'node:fs/promises' ;
2025-08-25 22:11:27 +02:00
import path from 'node:path' ;
2025-08-26 00:04:53 +02:00
import type { ToolInvocation , ToolResult } from './tools.js' ;
import { BaseDeclarativeTool , BaseToolInvocation , Kind } from './tools.js' ;
2025-04-19 19:45:42 +01:00
import { makeRelative , shortenPath } from '../utils/paths.js' ;
2025-08-26 00:04:53 +02:00
import type { Config } from '../config/config.js' ;
2025-09-26 13:37:00 -04:00
import { DEFAULT_FILE_FILTERING_OPTIONS } from '../config/constants.js' ;
2025-08-21 14:40:18 -07:00
import { ToolErrorType } from './tool-error.js' ;
2025-04-19 19:45:42 +01:00
/**
* Parameters for the LS tool
*/
export interface LSToolParams {
/**
* The absolute path to the directory to list
*/
path : string ;
/**
2025-06-03 21:40:46 -07:00
* Array of glob patterns to ignore (optional)
2025-04-19 19:45:42 +01:00
*/
ignore? : string [ ] ;
2025-06-03 21:40:46 -07:00
/**
2025-07-20 00:55:33 -07:00
* Whether to respect .gitignore and .geminiignore patterns (optional, defaults to true)
2025-06-03 21:40:46 -07:00
*/
2025-07-20 00:55:33 -07:00
file_filtering_options ? : {
respect_git_ignore? : boolean ;
respect_gemini_ignore? : boolean ;
} ;
2025-04-19 19:45:42 +01:00
}
/**
* File entry returned by LS tool
*/
export interface FileEntry {
/**
* Name of the file or directory
*/
name : string ;
/**
* Absolute path to the file or directory
*/
path : string ;
/**
* Whether this entry is a directory
*/
isDirectory : boolean ;
/**
* Size of the file in bytes (0 for directories)
*/
size : number ;
/**
* Last modified timestamp
*/
modifiedTime : Date ;
}
2025-08-13 11:57:37 -07:00
class LSToolInvocation extends BaseToolInvocation < LSToolParams , ToolResult > {
constructor (
private readonly config : Config ,
params : LSToolParams ,
) {
super ( params ) ;
2025-04-19 19:45:42 +01:00
}
/**
* Checks if a filename matches any of the ignore patterns
* @param filename Filename to check
* @param patterns Array of glob patterns to check against
* @returns True if the filename should be ignored
*/
private shouldIgnore ( filename : string , patterns? : string [ ] ) : boolean {
if ( ! patterns || patterns . length === 0 ) {
return false ;
}
for ( const pattern of patterns ) {
// Convert glob pattern to RegExp
const regexPattern = pattern
. replace ( /[.+^${}()|[\]\\]/g , '\\$&' )
. replace ( /\*/g , '.*' )
. replace ( /\?/g , '.' ) ;
const regex = new RegExp ( ` ^ ${ regexPattern } $ ` ) ;
if ( regex . test ( filename ) ) {
return true ;
}
}
return false ;
}
/**
* Gets a description of the file reading operation
* @returns A string describing the file being read
*/
2025-08-13 11:57:37 -07:00
getDescription ( ) : string {
const relativePath = makeRelative (
this . params . path ,
this . config . getTargetDir ( ) ,
) ;
2025-04-19 19:45:42 +01:00
return shortenPath ( relativePath ) ;
}
// Helper for consistent error formatting
2025-08-21 14:40:18 -07:00
private errorResult (
llmContent : string ,
returnDisplay : string ,
type : ToolErrorType ,
) : ToolResult {
2025-04-19 19:45:42 +01:00
return {
llmContent ,
// Keep returnDisplay simpler in core logic
returnDisplay : ` Error: ${ returnDisplay } ` ,
2025-08-21 14:40:18 -07:00
error : {
message : llmContent ,
type ,
} ,
2025-04-19 19:45:42 +01:00
} ;
}
/**
* Executes the LS operation with the given parameters
* @returns Result of the LS operation
*/
2025-08-13 11:57:37 -07:00
async execute ( _signal : AbortSignal ) : Promise < ToolResult > {
2025-04-19 19:45:42 +01:00
try {
2025-09-10 09:54:50 -07:00
const stats = await fs . stat ( this . params . path ) ;
2025-04-19 19:45:42 +01:00
if ( ! stats ) {
// fs.statSync throws on non-existence, so this check might be redundant
// but keeping for clarity. Error message adjusted.
return this . errorResult (
2025-08-13 11:57:37 -07:00
` Error: Directory not found or inaccessible: ${ this . params . path } ` ,
2025-04-19 19:45:42 +01:00
` Directory not found or inaccessible. ` ,
2025-08-21 14:40:18 -07:00
ToolErrorType . FILE_NOT_FOUND ,
2025-04-19 19:45:42 +01:00
) ;
}
if ( ! stats . isDirectory ( ) ) {
return this . errorResult (
2025-08-13 11:57:37 -07:00
` Error: Path is not a directory: ${ this . params . path } ` ,
2025-04-19 19:45:42 +01:00
` Path is not a directory. ` ,
2025-08-21 14:40:18 -07:00
ToolErrorType . PATH_IS_NOT_A_DIRECTORY ,
2025-04-19 19:45:42 +01:00
) ;
}
2025-09-10 09:54:50 -07:00
const files = await fs . readdir ( this . params . path ) ;
2025-04-19 19:45:42 +01:00
if ( files . length === 0 ) {
// Changed error message to be more neutral for LLM
return {
2025-08-13 11:57:37 -07:00
llmContent : ` Directory ${ this . params . path } is empty. ` ,
2025-04-19 19:45:42 +01:00
returnDisplay : ` Directory is empty. ` ,
} ;
}
2025-09-10 09:54:50 -07:00
const relativePaths = files . map ( ( file ) = >
path . relative (
2025-07-14 22:55:49 -07:00
this . config . getTargetDir ( ) ,
2025-09-10 09:54:50 -07:00
path . join ( this . params . path , file ) ,
) ,
) ;
2025-06-03 21:40:46 -07:00
2025-09-10 09:54:50 -07:00
const fileDiscovery = this . config . getFileService ( ) ;
const { filteredPaths , gitIgnoredCount , geminiIgnoredCount } =
fileDiscovery . filterFilesWithReport ( relativePaths , {
respectGitIgnore :
this.params.file_filtering_options?.respect_git_ignore ? ?
this . config . getFileFilteringOptions ( ) . respectGitIgnore ? ?
DEFAULT_FILE_FILTERING_OPTIONS . respectGitIgnore ,
respectGeminiIgnore :
this.params.file_filtering_options?.respect_gemini_ignore ? ?
this . config . getFileFilteringOptions ( ) . respectGeminiIgnore ? ?
DEFAULT_FILE_FILTERING_OPTIONS . respectGeminiIgnore ,
} ) ;
const entries = [ ] ;
for ( const relativePath of filteredPaths ) {
const fullPath = path . resolve ( this . config . getTargetDir ( ) , relativePath ) ;
if ( this . shouldIgnore ( path . basename ( fullPath ) , this . params . ignore ) ) {
2025-07-20 00:55:33 -07:00
continue ;
}
2025-06-03 21:40:46 -07:00
2025-04-19 19:45:42 +01:00
try {
2025-09-10 09:54:50 -07:00
const stats = await fs . stat ( fullPath ) ;
2025-04-19 19:45:42 +01:00
const isDir = stats . isDirectory ( ) ;
entries . push ( {
2025-09-10 09:54:50 -07:00
name : path.basename ( fullPath ) ,
2025-04-19 19:45:42 +01:00
path : fullPath ,
isDirectory : isDir ,
size : isDir ? 0 : stats.size ,
modifiedTime : stats.mtime ,
} ) ;
} catch ( error ) {
// Log error internally but don't fail the whole listing
console . error ( ` Error accessing ${ fullPath } : ${ error } ` ) ;
}
}
// Sort entries (directories first, then alphabetically)
entries . sort ( ( a , b ) = > {
if ( a . isDirectory && ! b . isDirectory ) return - 1 ;
if ( ! a . isDirectory && b . isDirectory ) return 1 ;
return a . name . localeCompare ( b . name ) ;
} ) ;
// Create formatted content for LLM
const directoryContent = entries
2025-04-24 15:42:18 -07:00
. map ( ( entry ) = > ` ${ entry . isDirectory ? '[DIR] ' : '' } ${ entry . name } ` )
2025-04-19 19:45:42 +01:00
. join ( '\n' ) ;
2025-08-13 11:57:37 -07:00
let resultMessage = ` Directory listing for ${ this . params . path } : \ n ${ directoryContent } ` ;
2025-07-20 00:55:33 -07:00
const ignoredMessages = [ ] ;
2025-06-03 21:40:46 -07:00
if ( gitIgnoredCount > 0 ) {
2025-07-20 00:55:33 -07:00
ignoredMessages . push ( ` ${ gitIgnoredCount } git-ignored ` ) ;
}
if ( geminiIgnoredCount > 0 ) {
ignoredMessages . push ( ` ${ geminiIgnoredCount } gemini-ignored ` ) ;
}
if ( ignoredMessages . length > 0 ) {
resultMessage += ` \ n \ n( ${ ignoredMessages . join ( ', ' ) } ) ` ;
2025-06-03 21:40:46 -07:00
}
let displayMessage = ` Listed ${ entries . length } item(s). ` ;
2025-07-20 00:55:33 -07:00
if ( ignoredMessages . length > 0 ) {
displayMessage += ` ( ${ ignoredMessages . join ( ', ' ) } ) ` ;
2025-06-03 21:40:46 -07:00
}
2025-04-19 19:45:42 +01:00
return {
2025-06-03 21:40:46 -07:00
llmContent : resultMessage ,
returnDisplay : displayMessage ,
2025-04-19 19:45:42 +01:00
} ;
} catch ( error ) {
const errorMsg = ` Error listing directory: ${ error instanceof Error ? error.message : String ( error ) } ` ;
2025-08-21 14:40:18 -07:00
return this . errorResult (
errorMsg ,
'Failed to list directory.' ,
ToolErrorType . LS_EXECUTION_ERROR ,
) ;
2025-04-19 19:45:42 +01:00
}
}
}
2025-08-13 11:57:37 -07:00
/**
* Implementation of the LS tool logic
*/
export class LSTool extends BaseDeclarativeTool < LSToolParams , ToolResult > {
static readonly Name = 'list_directory' ;
constructor ( private config : Config ) {
super (
LSTool . Name ,
'ReadFolder' ,
'Lists the names of files and subdirectories directly within a specified directory path. Can optionally ignore entries matching provided glob patterns.' ,
Kind . Search ,
{
properties : {
path : {
description :
'The absolute path to the directory to list (must be absolute, not relative)' ,
type : 'string' ,
} ,
ignore : {
description : 'List of glob patterns to ignore' ,
items : {
type : 'string' ,
} ,
type : 'array' ,
} ,
file_filtering_options : {
description :
'Optional: Whether to respect ignore patterns from .gitignore or .geminiignore' ,
type : 'object' ,
properties : {
respect_git_ignore : {
description :
'Optional: Whether to respect .gitignore patterns when listing files. Only available in git repositories. Defaults to true.' ,
type : 'boolean' ,
} ,
respect_gemini_ignore : {
description :
'Optional: Whether to respect .geminiignore patterns when listing files. Defaults to true.' ,
type : 'boolean' ,
} ,
} ,
} ,
} ,
required : [ 'path' ] ,
type : 'object' ,
} ,
) ;
}
/**
* Validates the parameters for the tool
* @param params Parameters to validate
* @returns An error message string if invalid, null otherwise
*/
2025-08-19 13:55:06 -07:00
protected override validateToolParamValues (
params : LSToolParams ,
) : string | null {
2025-08-13 11:57:37 -07:00
if ( ! path . isAbsolute ( params . path ) ) {
return ` Path must be absolute: ${ params . path } ` ;
}
const workspaceContext = this . config . getWorkspaceContext ( ) ;
if ( ! workspaceContext . isPathWithinWorkspace ( params . path ) ) {
const directories = workspaceContext . getDirectories ( ) ;
return ` Path must be within one of the workspace directories: ${ directories . join (
', ' ,
) } ` ;
}
return null ;
}
protected createInvocation (
params : LSToolParams ,
) : ToolInvocation < LSToolParams , ToolResult > {
return new LSToolInvocation ( this . config , params ) ;
}
}