|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
import * as fs from 'node:fs/promises'; |
|
|
import * as path from 'node:path'; |
|
|
import type { PartListUnion, PartUnion } from '@google/genai'; |
|
|
import type { AnyToolInvocation, Config } from '@google/gemini-cli-core'; |
|
|
import { |
|
|
getErrorMessage, |
|
|
isNodeError, |
|
|
unescapePath, |
|
|
} from '@google/gemini-cli-core'; |
|
|
import type { HistoryItem, IndividualToolCallDisplay } from '../types.js'; |
|
|
import { ToolCallStatus } from '../types.js'; |
|
|
import type { UseHistoryManagerReturn } from './useHistoryManager.js'; |
|
|
|
|
|
interface HandleAtCommandParams { |
|
|
query: string; |
|
|
config: Config; |
|
|
addItem: UseHistoryManagerReturn['addItem']; |
|
|
onDebugMessage: (message: string) => void; |
|
|
messageId: number; |
|
|
signal: AbortSignal; |
|
|
} |
|
|
|
|
|
interface HandleAtCommandResult { |
|
|
processedQuery: PartListUnion | null; |
|
|
shouldProceed: boolean; |
|
|
} |
|
|
|
|
|
interface AtCommandPart { |
|
|
type: 'text' | 'atPath'; |
|
|
content: string; |
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
function parseAllAtCommands(query: string): AtCommandPart[] { |
|
|
const parts: AtCommandPart[] = []; |
|
|
let currentIndex = 0; |
|
|
|
|
|
while (currentIndex < query.length) { |
|
|
let atIndex = -1; |
|
|
let nextSearchIndex = currentIndex; |
|
|
|
|
|
while (nextSearchIndex < query.length) { |
|
|
if ( |
|
|
query[nextSearchIndex] === '@' && |
|
|
(nextSearchIndex === 0 || query[nextSearchIndex - 1] !== '\\') |
|
|
) { |
|
|
atIndex = nextSearchIndex; |
|
|
break; |
|
|
} |
|
|
nextSearchIndex++; |
|
|
} |
|
|
|
|
|
if (atIndex === -1) { |
|
|
|
|
|
if (currentIndex < query.length) { |
|
|
parts.push({ type: 'text', content: query.substring(currentIndex) }); |
|
|
} |
|
|
break; |
|
|
} |
|
|
|
|
|
|
|
|
if (atIndex > currentIndex) { |
|
|
parts.push({ |
|
|
type: 'text', |
|
|
content: query.substring(currentIndex, atIndex), |
|
|
}); |
|
|
} |
|
|
|
|
|
|
|
|
let pathEndIndex = atIndex + 1; |
|
|
let inEscape = false; |
|
|
while (pathEndIndex < query.length) { |
|
|
const char = query[pathEndIndex]; |
|
|
if (inEscape) { |
|
|
inEscape = false; |
|
|
} else if (char === '\\') { |
|
|
inEscape = true; |
|
|
} else if (/[,\s;!?()[\]{}]/.test(char)) { |
|
|
|
|
|
break; |
|
|
} else if (char === '.') { |
|
|
|
|
|
|
|
|
const nextChar = |
|
|
pathEndIndex + 1 < query.length ? query[pathEndIndex + 1] : ''; |
|
|
if (nextChar === '' || /\s/.test(nextChar)) { |
|
|
break; |
|
|
} |
|
|
} |
|
|
pathEndIndex++; |
|
|
} |
|
|
const rawAtPath = query.substring(atIndex, pathEndIndex); |
|
|
|
|
|
const atPath = unescapePath(rawAtPath); |
|
|
parts.push({ type: 'atPath', content: atPath }); |
|
|
currentIndex = pathEndIndex; |
|
|
} |
|
|
|
|
|
return parts.filter( |
|
|
(part) => !(part.type === 'text' && part.content.trim() === ''), |
|
|
); |
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
export async function handleAtCommand({ |
|
|
query, |
|
|
config, |
|
|
addItem, |
|
|
onDebugMessage, |
|
|
messageId: userMessageTimestamp, |
|
|
signal, |
|
|
}: HandleAtCommandParams): Promise<HandleAtCommandResult> { |
|
|
const commandParts = parseAllAtCommands(query); |
|
|
const atPathCommandParts = commandParts.filter( |
|
|
(part) => part.type === 'atPath', |
|
|
); |
|
|
|
|
|
if (atPathCommandParts.length === 0) { |
|
|
return { processedQuery: [{ text: query }], shouldProceed: true }; |
|
|
} |
|
|
|
|
|
|
|
|
const fileDiscovery = config.getFileService(); |
|
|
|
|
|
const respectFileIgnore = config.getFileFilteringOptions(); |
|
|
|
|
|
const pathSpecsToRead: string[] = []; |
|
|
const atPathToResolvedSpecMap = new Map<string, string>(); |
|
|
const contentLabelsForDisplay: string[] = []; |
|
|
const ignoredByReason: Record<string, string[]> = { |
|
|
git: [], |
|
|
gemini: [], |
|
|
both: [], |
|
|
}; |
|
|
|
|
|
const toolRegistry = config.getToolRegistry(); |
|
|
const readManyFilesTool = toolRegistry.getTool('read_many_files'); |
|
|
const globTool = toolRegistry.getTool('glob'); |
|
|
|
|
|
if (!readManyFilesTool) { |
|
|
addItem( |
|
|
{ type: 'error', text: 'Error: read_many_files tool not found.' }, |
|
|
userMessageTimestamp, |
|
|
); |
|
|
return { processedQuery: null, shouldProceed: false }; |
|
|
} |
|
|
|
|
|
for (const atPathPart of atPathCommandParts) { |
|
|
const originalAtPath = atPathPart.content; |
|
|
|
|
|
if (originalAtPath === '@') { |
|
|
onDebugMessage( |
|
|
'Lone @ detected, will be treated as text in the modified query.', |
|
|
); |
|
|
continue; |
|
|
} |
|
|
|
|
|
const pathName = originalAtPath.substring(1); |
|
|
if (!pathName) { |
|
|
|
|
|
|
|
|
addItem( |
|
|
{ |
|
|
type: 'error', |
|
|
text: `Error: Invalid @ command '${originalAtPath}'. No path specified.`, |
|
|
}, |
|
|
userMessageTimestamp, |
|
|
); |
|
|
|
|
|
|
|
|
return { processedQuery: null, shouldProceed: false }; |
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
const workspaceContext = config.getWorkspaceContext(); |
|
|
if (!workspaceContext.isPathWithinWorkspace(pathName)) { |
|
|
onDebugMessage( |
|
|
`Path ${pathName} is not in the workspace and will be skipped.`, |
|
|
); |
|
|
continue; |
|
|
} |
|
|
|
|
|
const gitIgnored = |
|
|
respectFileIgnore.respectGitIgnore && |
|
|
fileDiscovery.shouldIgnoreFile(pathName, { |
|
|
respectGitIgnore: true, |
|
|
respectGeminiIgnore: false, |
|
|
}); |
|
|
const geminiIgnored = |
|
|
respectFileIgnore.respectGeminiIgnore && |
|
|
fileDiscovery.shouldIgnoreFile(pathName, { |
|
|
respectGitIgnore: false, |
|
|
respectGeminiIgnore: true, |
|
|
}); |
|
|
|
|
|
if (gitIgnored || geminiIgnored) { |
|
|
const reason = |
|
|
gitIgnored && geminiIgnored ? 'both' : gitIgnored ? 'git' : 'gemini'; |
|
|
ignoredByReason[reason].push(pathName); |
|
|
const reasonText = |
|
|
reason === 'both' |
|
|
? 'ignored by both git and gemini' |
|
|
: reason === 'git' |
|
|
? 'git-ignored' |
|
|
: 'gemini-ignored'; |
|
|
onDebugMessage(`Path ${pathName} is ${reasonText} and will be skipped.`); |
|
|
continue; |
|
|
} |
|
|
|
|
|
for (const dir of config.getWorkspaceContext().getDirectories()) { |
|
|
let currentPathSpec = pathName; |
|
|
let resolvedSuccessfully = false; |
|
|
try { |
|
|
const absolutePath = path.resolve(dir, pathName); |
|
|
const stats = await fs.stat(absolutePath); |
|
|
if (stats.isDirectory()) { |
|
|
currentPathSpec = |
|
|
pathName + (pathName.endsWith(path.sep) ? `**` : `/**`); |
|
|
onDebugMessage( |
|
|
`Path ${pathName} resolved to directory, using glob: ${currentPathSpec}`, |
|
|
); |
|
|
} else { |
|
|
onDebugMessage(`Path ${pathName} resolved to file: ${absolutePath}`); |
|
|
} |
|
|
resolvedSuccessfully = true; |
|
|
} catch (error) { |
|
|
if (isNodeError(error) && error.code === 'ENOENT') { |
|
|
if (config.getEnableRecursiveFileSearch() && globTool) { |
|
|
onDebugMessage( |
|
|
`Path ${pathName} not found directly, attempting glob search.`, |
|
|
); |
|
|
try { |
|
|
const globResult = await globTool.buildAndExecute( |
|
|
{ |
|
|
pattern: `**/*${pathName}*`, |
|
|
path: dir, |
|
|
}, |
|
|
signal, |
|
|
); |
|
|
if ( |
|
|
globResult.llmContent && |
|
|
typeof globResult.llmContent === 'string' && |
|
|
!globResult.llmContent.startsWith('No files found') && |
|
|
!globResult.llmContent.startsWith('Error:') |
|
|
) { |
|
|
const lines = globResult.llmContent.split('\n'); |
|
|
if (lines.length > 1 && lines[1]) { |
|
|
const firstMatchAbsolute = lines[1].trim(); |
|
|
currentPathSpec = path.relative(dir, firstMatchAbsolute); |
|
|
onDebugMessage( |
|
|
`Glob search for ${pathName} found ${firstMatchAbsolute}, using relative path: ${currentPathSpec}`, |
|
|
); |
|
|
resolvedSuccessfully = true; |
|
|
} else { |
|
|
onDebugMessage( |
|
|
`Glob search for '**/*${pathName}*' did not return a usable path. Path ${pathName} will be skipped.`, |
|
|
); |
|
|
} |
|
|
} else { |
|
|
onDebugMessage( |
|
|
`Glob search for '**/*${pathName}*' found no files or an error. Path ${pathName} will be skipped.`, |
|
|
); |
|
|
} |
|
|
} catch (globError) { |
|
|
console.error( |
|
|
`Error during glob search for ${pathName}: ${getErrorMessage(globError)}`, |
|
|
); |
|
|
onDebugMessage( |
|
|
`Error during glob search for ${pathName}. Path ${pathName} will be skipped.`, |
|
|
); |
|
|
} |
|
|
} else { |
|
|
onDebugMessage( |
|
|
`Glob tool not found. Path ${pathName} will be skipped.`, |
|
|
); |
|
|
} |
|
|
} else { |
|
|
console.error( |
|
|
`Error stating path ${pathName}: ${getErrorMessage(error)}`, |
|
|
); |
|
|
onDebugMessage( |
|
|
`Error stating path ${pathName}. Path ${pathName} will be skipped.`, |
|
|
); |
|
|
} |
|
|
} |
|
|
if (resolvedSuccessfully) { |
|
|
pathSpecsToRead.push(currentPathSpec); |
|
|
atPathToResolvedSpecMap.set(originalAtPath, currentPathSpec); |
|
|
contentLabelsForDisplay.push(pathName); |
|
|
break; |
|
|
} |
|
|
} |
|
|
} |
|
|
|
|
|
|
|
|
let initialQueryText = ''; |
|
|
for (let i = 0; i < commandParts.length; i++) { |
|
|
const part = commandParts[i]; |
|
|
if (part.type === 'text') { |
|
|
initialQueryText += part.content; |
|
|
} else { |
|
|
|
|
|
const resolvedSpec = atPathToResolvedSpecMap.get(part.content); |
|
|
if ( |
|
|
i > 0 && |
|
|
initialQueryText.length > 0 && |
|
|
!initialQueryText.endsWith(' ') |
|
|
) { |
|
|
|
|
|
const prevPart = commandParts[i - 1]; |
|
|
if ( |
|
|
prevPart.type === 'text' || |
|
|
(prevPart.type === 'atPath' && |
|
|
atPathToResolvedSpecMap.has(prevPart.content)) |
|
|
) { |
|
|
initialQueryText += ' '; |
|
|
} |
|
|
} |
|
|
if (resolvedSpec) { |
|
|
initialQueryText += `@${resolvedSpec}`; |
|
|
} else { |
|
|
|
|
|
|
|
|
if ( |
|
|
i > 0 && |
|
|
initialQueryText.length > 0 && |
|
|
!initialQueryText.endsWith(' ') && |
|
|
!part.content.startsWith(' ') |
|
|
) { |
|
|
initialQueryText += ' '; |
|
|
} |
|
|
initialQueryText += part.content; |
|
|
} |
|
|
} |
|
|
} |
|
|
initialQueryText = initialQueryText.trim(); |
|
|
|
|
|
|
|
|
const totalIgnored = |
|
|
ignoredByReason['git'].length + |
|
|
ignoredByReason['gemini'].length + |
|
|
ignoredByReason['both'].length; |
|
|
|
|
|
if (totalIgnored > 0) { |
|
|
const messages = []; |
|
|
if (ignoredByReason['git'].length) { |
|
|
messages.push(`Git-ignored: ${ignoredByReason['git'].join(', ')}`); |
|
|
} |
|
|
if (ignoredByReason['gemini'].length) { |
|
|
messages.push(`Gemini-ignored: ${ignoredByReason['gemini'].join(', ')}`); |
|
|
} |
|
|
if (ignoredByReason['both'].length) { |
|
|
messages.push(`Ignored by both: ${ignoredByReason['both'].join(', ')}`); |
|
|
} |
|
|
|
|
|
const message = `Ignored ${totalIgnored} files:\n${messages.join('\n')}`; |
|
|
console.log(message); |
|
|
onDebugMessage(message); |
|
|
} |
|
|
|
|
|
|
|
|
if (pathSpecsToRead.length === 0) { |
|
|
onDebugMessage('No valid file paths found in @ commands to read.'); |
|
|
if (initialQueryText === '@' && query.trim() === '@') { |
|
|
|
|
|
return { processedQuery: [{ text: query }], shouldProceed: true }; |
|
|
} else if (!initialQueryText && query) { |
|
|
|
|
|
return { processedQuery: [{ text: query }], shouldProceed: true }; |
|
|
} |
|
|
|
|
|
return { |
|
|
processedQuery: [{ text: initialQueryText || query }], |
|
|
shouldProceed: true, |
|
|
}; |
|
|
} |
|
|
|
|
|
const processedQueryParts: PartUnion[] = [{ text: initialQueryText }]; |
|
|
|
|
|
const toolArgs = { |
|
|
paths: pathSpecsToRead, |
|
|
file_filtering_options: { |
|
|
respect_git_ignore: respectFileIgnore.respectGitIgnore, |
|
|
respect_gemini_ignore: respectFileIgnore.respectGeminiIgnore, |
|
|
}, |
|
|
|
|
|
}; |
|
|
let toolCallDisplay: IndividualToolCallDisplay; |
|
|
|
|
|
let invocation: AnyToolInvocation | undefined = undefined; |
|
|
try { |
|
|
invocation = readManyFilesTool.build(toolArgs); |
|
|
const result = await invocation.execute(signal); |
|
|
toolCallDisplay = { |
|
|
callId: `client-read-${userMessageTimestamp}`, |
|
|
name: readManyFilesTool.displayName, |
|
|
description: invocation.getDescription(), |
|
|
status: ToolCallStatus.Success, |
|
|
resultDisplay: |
|
|
result.returnDisplay || |
|
|
`Successfully read: ${contentLabelsForDisplay.join(', ')}`, |
|
|
confirmationDetails: undefined, |
|
|
}; |
|
|
|
|
|
if (Array.isArray(result.llmContent)) { |
|
|
const fileContentRegex = /^--- (.*?) ---\n\n([\s\S]*?)\n\n$/; |
|
|
processedQueryParts.push({ |
|
|
text: '\n--- Content from referenced files ---', |
|
|
}); |
|
|
for (const part of result.llmContent) { |
|
|
if (typeof part === 'string') { |
|
|
const match = fileContentRegex.exec(part); |
|
|
if (match) { |
|
|
const filePathSpecInContent = match[1]; |
|
|
const fileActualContent = match[2].trim(); |
|
|
processedQueryParts.push({ |
|
|
text: `\nContent from @${filePathSpecInContent}:\n`, |
|
|
}); |
|
|
processedQueryParts.push({ text: fileActualContent }); |
|
|
} else { |
|
|
processedQueryParts.push({ text: part }); |
|
|
} |
|
|
} else { |
|
|
|
|
|
processedQueryParts.push(part); |
|
|
} |
|
|
} |
|
|
} else { |
|
|
onDebugMessage( |
|
|
'read_many_files tool returned no content or empty content.', |
|
|
); |
|
|
} |
|
|
|
|
|
addItem( |
|
|
{ type: 'tool_group', tools: [toolCallDisplay] } as Omit< |
|
|
HistoryItem, |
|
|
'id' |
|
|
>, |
|
|
userMessageTimestamp, |
|
|
); |
|
|
return { processedQuery: processedQueryParts, shouldProceed: true }; |
|
|
} catch (error: unknown) { |
|
|
toolCallDisplay = { |
|
|
callId: `client-read-${userMessageTimestamp}`, |
|
|
name: readManyFilesTool.displayName, |
|
|
description: |
|
|
invocation?.getDescription() ?? |
|
|
'Error attempting to execute tool to read files', |
|
|
status: ToolCallStatus.Error, |
|
|
resultDisplay: `Error reading files (${contentLabelsForDisplay.join(', ')}): ${getErrorMessage(error)}`, |
|
|
confirmationDetails: undefined, |
|
|
}; |
|
|
addItem( |
|
|
{ type: 'tool_group', tools: [toolCallDisplay] } as Omit< |
|
|
HistoryItem, |
|
|
'id' |
|
|
>, |
|
|
userMessageTimestamp, |
|
|
); |
|
|
return { processedQuery: null, shouldProceed: false }; |
|
|
} |
|
|
} |
|
|
|