From 3fce6cea27d3e6129d6c06e528b62e1b11bf7094 Mon Sep 17 00:00:00 2001 From: Evan Senter Date: Sat, 19 Apr 2025 19:45:42 +0100 Subject: [PATCH] Starting to modularize into separate cli / server packages. (#55) * Starting to move a lot of code into packages/server * More of the massive refactor, builds and runs, some issues though. * Fixing outstanding issue with double messages. * Fixing a minor UI issue. * Fixing the build post-merge. * Running formatting. * Addressing comments. --- eslint.config.js | 7 +- packages/cli/src/config/config.ts | 104 +-- packages/cli/src/core/gemini-client.test.ts | 165 ----- packages/cli/src/core/gemini-client.ts | 282 --------- packages/cli/src/core/gemini-stream.ts | 183 +----- packages/cli/src/core/history-updater.ts | 4 +- packages/cli/src/core/turn.ts | 233 ------- packages/cli/src/gemini.ts | 20 +- packages/cli/src/tools/edit.tool.ts | 402 +++--------- packages/cli/src/tools/glob.tool.ts | 257 ++------ packages/cli/src/tools/grep.tool.ts | 592 ++---------------- packages/cli/src/tools/ls.tool.ts | 280 ++------- packages/cli/src/tools/read-file.tool.ts | 281 +-------- packages/cli/src/tools/terminal.tool.ts | 381 +++-------- packages/cli/src/tools/tool-registry.ts | 28 +- packages/cli/src/tools/web-fetch.tool.ts | 164 +---- packages/cli/src/tools/write-file.tool.ts | 177 ++---- packages/cli/src/ui/App.tsx | 31 +- packages/cli/src/ui/components/Header.tsx | 2 +- .../cli/src/ui/components/InputPrompt.tsx | 56 +- .../components/messages/ToolGroupMessage.tsx | 2 + .../ui/components/messages/ToolMessage.tsx | 144 +++-- packages/cli/src/ui/hooks/useAppEffects.ts | 4 +- packages/cli/src/ui/hooks/useGeminiStream.ts | 417 +++++++++--- packages/cli/src/ui/types.ts | 9 +- .../src/utils/BackgroundTerminalAnalyzer.ts | 220 ++++--- packages/server/package.json | 9 + packages/server/src/config/config.ts | 65 ++ packages/server/src/core/gemini-client.ts | 171 +++++ packages/{cli => server}/src/core/prompts.ts | 19 +- packages/server/src/core/turn.ts | 199 ++++++ packages/server/src/index.test.ts | 8 +- packages/server/src/index.ts | 31 +- packages/server/src/tools/edit.ts | 353 +++++++++++ packages/server/src/tools/glob.ts | 216 +++++++ packages/server/src/tools/grep.ts | 565 +++++++++++++++++ packages/server/src/tools/ls.ts | 276 ++++++++ packages/server/src/tools/read-file.ts | 278 ++++++++ packages/server/src/tools/terminal.ts | 256 ++++++++ packages/server/src/tools/tools.ts | 150 +++++ packages/server/src/tools/web-fetch.ts | 141 +++++ packages/server/src/tools/write-file.ts | 167 +++++ packages/{cli => server}/src/utils/errors.ts | 0 .../src/utils/getFolderStructure.ts | 0 packages/{cli => server}/src/utils/paths.ts | 0 .../src/utils/schemaValidator.ts | 0 46 files changed, 3946 insertions(+), 3403 deletions(-) delete mode 100644 packages/cli/src/core/gemini-client.test.ts delete mode 100644 packages/cli/src/core/gemini-client.ts delete mode 100644 packages/cli/src/core/turn.ts create mode 100644 packages/server/src/config/config.ts create mode 100644 packages/server/src/core/gemini-client.ts rename packages/{cli => server}/src/core/prompts.ts (91%) create mode 100644 packages/server/src/core/turn.ts create mode 100644 packages/server/src/tools/edit.ts create mode 100644 packages/server/src/tools/glob.ts create mode 100644 packages/server/src/tools/grep.ts create mode 100644 packages/server/src/tools/ls.ts create mode 100644 packages/server/src/tools/read-file.ts create mode 100644 packages/server/src/tools/terminal.ts create mode 100644 packages/server/src/tools/tools.ts create mode 100644 packages/server/src/tools/web-fetch.ts create mode 100644 packages/server/src/tools/write-file.ts rename packages/{cli => server}/src/utils/errors.ts (100%) rename packages/{cli => server}/src/utils/getFolderStructure.ts (100%) rename packages/{cli => server}/src/utils/paths.ts (100%) rename packages/{cli => server}/src/utils/schemaValidator.ts (100%) diff --git a/eslint.config.js b/eslint.config.js index c5ecac46..ae924cc7 100644 --- a/eslint.config.js +++ b/eslint.config.js @@ -16,7 +16,12 @@ import globals from 'globals'; export default tseslint.config( { // Global ignores - ignores: ['node_modules/**', 'eslint.config.js', 'packages/cli/dist/**'], + ignores: [ + 'node_modules/**', + 'eslint.config.js', + 'packages/cli/dist/**', + 'packages/server/dist/**', + ], }, eslint.configs.recommended, ...tseslint.configs.recommended, diff --git a/packages/cli/src/config/config.ts b/packages/cli/src/config/config.ts index d9960613..48cc96a0 100644 --- a/packages/cli/src/config/config.ts +++ b/packages/cli/src/config/config.ts @@ -6,61 +6,20 @@ import yargs from 'yargs/yargs'; import { hideBin } from 'yargs/helpers'; -import * as dotenv from 'dotenv'; -import * as fs from 'node:fs'; -import * as path from 'node:path'; import process from 'node:process'; +// Import server config logic +import { + Config, + loadEnvironment, + createServerConfig, +} from '@gemini-code/server'; const DEFAULT_GEMINI_MODEL = 'gemini-2.5-flash-preview-04-17'; -export class Config { - private apiKey: string; - private model: string; - private targetDir: string; - - constructor(apiKey: string, model: string, targetDir: string) { - this.apiKey = apiKey; - this.model = model; - this.targetDir = targetDir; - } - - getApiKey(): string { - return this.apiKey; - } - - getModel(): string { - return this.model; - } - - getTargetDir(): string { - return this.targetDir; - } -} - -export function loadConfig(): Config { - loadEnvironment(); - if (!process.env.GEMINI_API_KEY) { - console.log( - 'GEMINI_API_KEY is not set. See https://ai.google.dev/gemini-api/docs/api-key to obtain one. ' + - 'Please set it in your .env file or as an environment variable.', - ); - process.exit(1); - } - const argv = parseArguments(); - return new Config( - process.env.GEMINI_API_KEY, - argv.model || DEFAULT_GEMINI_MODEL, - argv.target_dir || process.cwd(), - ); -} - -export const globalConfig = loadConfig(); // TODO(jbd): Remove global state. - +// Keep CLI-specific argument parsing interface CliArgs { target_dir: string | undefined; model: string | undefined; - // Add other expected args here if needed - // e.g., verbose?: boolean; } function parseArguments(): CliArgs { @@ -79,35 +38,34 @@ function parseArguments(): CliArgs { }) .help() .alias('h', 'help') - .strict().argv; // Keep strict mode to error on unknown options - - // Cast to the interface to ensure the structure aligns with expectations - // Use `unknown` first for safer casting if types might not perfectly match + .strict().argv; return argv as unknown as CliArgs; } -function findEnvFile(startDir: string): string | null { - // Start search from the provided directory (e.g., current working directory) - let currentDir = path.resolve(startDir); // Ensure absolute path - while (true) { - const envPath = path.join(currentDir, '.env'); - if (fs.existsSync(envPath)) { - return envPath; - } +// Renamed function for clarity +export function loadCliConfig(): Config { + // Load .env file using logic from server package + loadEnvironment(); - const parentDir = path.dirname(currentDir); - if (parentDir === currentDir || !parentDir) { - return null; - } - currentDir = parentDir; + // Check API key (CLI responsibility) + if (!process.env.GEMINI_API_KEY) { + console.log( + 'GEMINI_API_KEY is not set. See https://ai.google.dev/gemini-api/docs/api-key to obtain one. ' + + 'Please set it in your .env file or as an environment variable.', + ); + process.exit(1); } + + // Parse CLI arguments + const argv = parseArguments(); + + // Create config using factory from server package + return createServerConfig( + process.env.GEMINI_API_KEY, + argv.model || DEFAULT_GEMINI_MODEL, + argv.target_dir || process.cwd(), + ); } -function loadEnvironment(): void { - // Start searching from the current working directory by default - const envFilePath = findEnvFile(process.cwd()); - if (!envFilePath) { - return; - } - dotenv.config({ path: envFilePath }); -} +// The globalConfig export is problematic, CLI entry point (gemini.ts) should call loadCliConfig +// export const globalConfig = loadCliConfig(); // Remove or replace global export diff --git a/packages/cli/src/core/gemini-client.test.ts b/packages/cli/src/core/gemini-client.test.ts deleted file mode 100644 index 4651529e..00000000 --- a/packages/cli/src/core/gemini-client.test.ts +++ /dev/null @@ -1,165 +0,0 @@ -import { describe, it, expect, vi, beforeEach, Mock } from 'vitest'; -import { GoogleGenAI, Type, Content } from '@google/genai'; -import { GeminiClient } from './gemini-client.js'; -import { Config } from '../config/config.js'; - -// Mock the entire @google/genai module -vi.mock('@google/genai'); - -// Mock the Config class and its methods -vi.mock('../config/config.js', () => { - // The mock constructor should accept the arguments but not explicitly return an object. - // vi.fn() will create a mock instance that inherits from the prototype. - const MockConfig = vi.fn(); - // Methods are mocked on the prototype, so instances will inherit them. - MockConfig.prototype.getApiKey = vi.fn(() => 'mock-api-key'); - MockConfig.prototype.getModel = vi.fn(() => 'mock-model'); - MockConfig.prototype.getTargetDir = vi.fn(() => 'mock-target-dir'); - return { Config: MockConfig }; -}); - -// Define a type for the mocked GoogleGenAI instance structure -type MockGoogleGenAIType = { - models: { - generateContent: Mock; - }; - chats: { - create: Mock; - }; -}; - -describe('GeminiClient', () => { - // Use the specific types defined above - let mockGenerateContent: MockGoogleGenAIType['models']['generateContent']; - let mockGoogleGenAIInstance: MockGoogleGenAIType; - let config: Config; - let client: GeminiClient; - - beforeEach(() => { - vi.clearAllMocks(); - - // Mock the generateContent method specifically - mockGenerateContent = vi.fn(); - - // Mock the chainable structure ai.models.generateContent - mockGoogleGenAIInstance = { - models: { - generateContent: mockGenerateContent, - }, - chats: { - create: vi.fn(), // Mock create as well - }, - }; - - // Configure the mocked GoogleGenAI constructor to return our mock instance - (GoogleGenAI as Mock).mockImplementation(() => mockGoogleGenAIInstance); - - config = new Config('mock-api-key-arg', 'mock-model-arg', 'mock-dir-arg'); - client = new GeminiClient(config); - }); - - describe('generateJson', () => { - it('should call ai.models.generateContent with correct parameters', async () => { - const mockContents: Content[] = [ - { role: 'user', parts: [{ text: 'test prompt' }] }, - ]; - const mockSchema = { - type: Type.OBJECT, - properties: { key: { type: Type.STRING } }, - }; - const mockApiResponse = { text: JSON.stringify({ key: 'value' }) }; - - mockGenerateContent.mockResolvedValue(mockApiResponse); - await client.generateJson(mockContents, mockSchema); - - expect(mockGenerateContent).toHaveBeenCalledTimes(1); - - // Use expect.objectContaining for the config assertion - const expectedConfigMatcher = expect.objectContaining({ - temperature: 0, - topP: 1, - systemInstruction: expect.any(String), - responseSchema: mockSchema, - responseMimeType: 'application/json', - }); - expect(mockGenerateContent).toHaveBeenCalledWith({ - model: 'mock-model', - config: expectedConfigMatcher, - contents: mockContents, - }); - }); - - it('should return the parsed JSON response', async () => { - const mockContents: Content[] = [ - { role: 'user', parts: [{ text: 'test prompt' }] }, - ]; - const mockSchema = { - type: Type.OBJECT, - properties: { key: { type: Type.STRING } }, - }; - const expectedJson = { key: 'value' }; - const mockApiResponse = { text: JSON.stringify(expectedJson) }; - - mockGenerateContent.mockResolvedValue(mockApiResponse); - - const result = await client.generateJson(mockContents, mockSchema); - - expect(result).toEqual(expectedJson); - }); - - it('should throw an error if API returns empty response', async () => { - const mockContents: Content[] = [ - { role: 'user', parts: [{ text: 'test prompt' }] }, - ]; - const mockSchema = { - type: Type.OBJECT, - properties: { key: { type: Type.STRING } }, - }; - const mockApiResponse = { text: '' }; // Empty response - - mockGenerateContent.mockResolvedValue(mockApiResponse); - - await expect( - client.generateJson(mockContents, mockSchema), - ).rejects.toThrow( - 'Failed to generate JSON content: API returned an empty response.', - ); - }); - - it('should throw an error if API response is not valid JSON', async () => { - const mockContents: Content[] = [ - { role: 'user', parts: [{ text: 'test prompt' }] }, - ]; - const mockSchema = { - type: Type.OBJECT, - properties: { key: { type: Type.STRING } }, - }; - const mockApiResponse = { text: 'invalid json' }; // Invalid JSON - - mockGenerateContent.mockResolvedValue(mockApiResponse); - - await expect( - client.generateJson(mockContents, mockSchema), - ).rejects.toThrow('Failed to parse API response as JSON:'); - }); - - it('should throw an error if generateContent rejects', async () => { - const mockContents: Content[] = [ - { role: 'user', parts: [{ text: 'test prompt' }] }, - ]; - const mockSchema = { - type: Type.OBJECT, - properties: { key: { type: Type.STRING } }, - }; - const apiError = new Error('API call failed'); - - mockGenerateContent.mockRejectedValue(apiError); - - await expect( - client.generateJson(mockContents, mockSchema), - ).rejects.toThrow(`Failed to generate JSON content: ${apiError.message}`); - }); - }); - - // TODO: Add tests for startChat and sendMessageStream later -}); diff --git a/packages/cli/src/core/gemini-client.ts b/packages/cli/src/core/gemini-client.ts deleted file mode 100644 index 19dba40f..00000000 --- a/packages/cli/src/core/gemini-client.ts +++ /dev/null @@ -1,282 +0,0 @@ -/** - * @license - * Copyright 2025 Google LLC - * SPDX-License-Identifier: Apache-2.0 - */ - -import { - GenerateContentConfig, - GoogleGenAI, - Part, - Chat, - Type, - SchemaUnion, - PartListUnion, - Content, -} from '@google/genai'; -import { CoreSystemPrompt } from './prompts.js'; -import process from 'node:process'; -import { toolRegistry } from '../tools/tool-registry.js'; -import { getFolderStructure } from '../utils/getFolderStructure.js'; -import { GeminiEventType, GeminiStream } from './gemini-stream.js'; -import { Config } from '../config/config.js'; -import { Turn } from './turn.js'; - -export class GeminiClient { - private config: Config; - private ai: GoogleGenAI; - private generateContentConfig: GenerateContentConfig = { - temperature: 0, - topP: 1, - }; - private readonly MAX_TURNS = 100; - - constructor(config: Config) { - this.config = config; - this.ai = new GoogleGenAI({ apiKey: config.getApiKey() }); - } - - private async getEnvironment(): Promise { - const cwd = process.cwd(); - const today = new Date().toLocaleDateString(undefined, { - weekday: 'long', - year: 'numeric', - month: 'long', - day: 'numeric', - }); - const platform = process.platform; - - const folderStructure = await getFolderStructure(cwd); - - const context = ` - Okay, just setting up the context for our chat. - Today is ${today}. - My operating system is: ${platform} - I'm currently working in the directory: ${cwd} - ${folderStructure} - `.trim(); - - return { text: context }; - } - - async startChat(): Promise { - const envPart = await this.getEnvironment(); - const model = this.config.getModel(); - const tools = toolRegistry.getToolSchemas(); - - try { - const chat = this.ai.chats.create({ - model, - config: { - systemInstruction: CoreSystemPrompt, - ...this.generateContentConfig, - tools, - }, - history: [ - // --- Add the context as a single part in the initial user message --- - { - role: 'user', - parts: [envPart], // Pass the single Part object in an array - }, - // --- Add an empty model response to balance the history --- - { - role: 'model', - parts: [{ text: 'Got it. Thanks for the context!' }], // A slightly more conversational model response - }, - // --- End history modification --- - ], - }); - return chat; - } catch (error) { - console.error('Error initializing Gemini chat session:', error); - const message = error instanceof Error ? error.message : 'Unknown error.'; - throw new Error(`Failed to initialize chat: ${message}`); - } - } - - async *sendMessageStream( - chat: Chat, - request: PartListUnion, - signal?: AbortSignal, - ): GeminiStream { - let turns = 0; - - try { - while (turns < this.MAX_TURNS) { - turns++; - // A turn either yields a text response or returns - // function responses to be used in the next turn. - // This callsite is responsible to handle the buffered - // function responses and use it on the next turn. - const turn = new Turn(chat); - const resultStream = turn.run(request, signal); - - for await (const event of resultStream) { - yield event; - } - const fnResponses = turn.getFunctionResponses(); - if (fnResponses.length > 0) { - request = fnResponses; - continue; // use the responses in the next turn - } - - const history = chat.getHistory(); - const checkPrompt = `Analyze *only* the content and structure of your immediately preceding response (your last turn in the conversation history). Based *strictly* on that response, determine who should logically speak next: the 'user' or the 'model' (you). - - **Decision Rules (apply in order):** - - 1. **Model Continues:** If your last response explicitly states an immediate next action *you* intend to take (e.g., "Next, I will...", "Now I'll process...", "Moving on to analyze...", indicates an intended tool call that didn't execute), OR if the response seems clearly incomplete (cut off mid-thought without a natural conclusion), then the **'model'** should speak next. - 2. **Question to User:** If your last response ends with a direct question specifically addressed *to the user*, then the **'user'** should speak next. - 3. **Waiting for User:** If your last response completed a thought, statement, or task *and* does not meet the criteria for Rule 1 (Model Continues) or Rule 2 (Question to User), it implies a pause expecting user input or reaction. In this case, the **'user'** should speak next. - - **Output Format:** - - Respond *only* in JSON format according to the following schema. Do not include any text outside the JSON structure. - - \`\`\`json - { - "type": "object", - "properties": { - "reasoning": { - "type": "string", - "description": "Brief explanation justifying the 'next_speaker' choice based *strictly* on the applicable rule and the content/structure of the preceding turn." - }, - "next_speaker": { - "type": "string", - "enum": ["user", "model"], - "description": "Who should speak next based *only* on the preceding turn and the decision rules." - } - }, - "required": ["next_speaker", "reasoning"] - \`\`\` - }`; - - // Schema Idea - const responseSchema: SchemaUnion = { - type: Type.OBJECT, - properties: { - reasoning: { - type: Type.STRING, - description: - "Brief explanation justifying the 'next_speaker' choice based *strictly* on the applicable rule and the content/structure of the preceding turn.", - }, - next_speaker: { - type: Type.STRING, - enum: ['user', 'model'], // Enforce the choices - description: - 'Who should speak next based *only* on the preceding turn and the decision rules', - }, - }, - required: ['reasoning', 'next_speaker'], - }; - - try { - // Use the new generateJson method, passing the history and the check prompt - const parsedResponse = await this.generateJson( - [ - ...history, - { - role: 'user', - parts: [{ text: checkPrompt }], - }, - ], - responseSchema, - ); - - // Safely extract the next speaker value - const nextSpeaker: string | undefined = - typeof parsedResponse?.next_speaker === 'string' - ? parsedResponse.next_speaker - : undefined; - - if (nextSpeaker === 'model') { - request = { text: 'alright' }; // Or potentially a more meaningful continuation prompt - } else { - // 'user' should speak next, or value is missing/invalid. End the turn. - break; - } - } catch (error) { - console.error( - `[Turn ${turns}] Failed to get or parse next speaker check:`, - error, - ); - // If the check fails, assume user should speak next to avoid infinite loops - break; - } - } - - if (turns >= this.MAX_TURNS) { - console.warn( - 'sendMessageStream: Reached maximum tool call turns limit.', - ); - yield { - type: GeminiEventType.Content, - value: - '\n\n[System Notice: Maximum interaction turns reached. The conversation may be incomplete.]', - }; - } - } catch (error: unknown) { - // TODO(jbd): There is so much of packing/unpacking of error types. - // Figure out a way to remove the redundant work. - if (error instanceof Error && error.name === 'AbortError') { - console.log('Gemini stream request aborted by user.'); - throw error; - } else { - console.error(`Error during Gemini stream or tool interaction:`, error); - const message = error instanceof Error ? error.message : String(error); - yield { - type: GeminiEventType.Content, - value: `\n\n[Error: An unexpected error occurred during the chat: ${message}]`, - }; - throw error; - } - } - } - - /** - * Generates structured JSON content based on conversational history and a schema. - * @param contents The conversational history (Content array) to provide context. - * @param schema The SchemaUnion defining the desired JSON structure. - * @returns A promise that resolves to the parsed JSON object matching the schema. - * @throws Throws an error if the API call fails or the response is not valid JSON. - */ - async generateJson( - contents: Content[], - schema: SchemaUnion, - ): Promise> { - const model = this.config.getModel(); - try { - const result = await this.ai.models.generateContent({ - model, - config: { - ...this.generateContentConfig, - systemInstruction: CoreSystemPrompt, - responseSchema: schema, - responseMimeType: 'application/json', - }, - contents, // Pass the full Content array - }); - - const responseText = result.text; - if (!responseText) { - throw new Error('API returned an empty response.'); - } - - try { - const parsedJson = JSON.parse(responseText); - // TODO: Add schema validation if needed - return parsedJson; - } catch (parseError) { - console.error('Failed to parse JSON response:', responseText); - throw new Error( - `Failed to parse API response as JSON: ${parseError instanceof Error ? parseError.message : String(parseError)}`, - ); - } - } catch (error) { - console.error('Error generating JSON content:', error); - const message = - error instanceof Error ? error.message : 'Unknown API error.'; - throw new Error(`Failed to generate JSON content: ${message}`); - } - } -} diff --git a/packages/cli/src/core/gemini-stream.ts b/packages/cli/src/core/gemini-stream.ts index 182291f7..d41c50d7 100644 --- a/packages/cli/src/core/gemini-stream.ts +++ b/packages/cli/src/core/gemini-stream.ts @@ -4,181 +4,16 @@ * SPDX-License-Identifier: Apache-2.0 */ -import { ToolCallEvent, HistoryItem } from '../ui/types.js'; -import { Part } from '@google/genai'; -import { - handleToolCallChunk, - addErrorMessageToHistory, -} from './history-updater.js'; - -export enum GeminiEventType { - Content, - ToolCallInfo, -} - -export interface GeminiContentEvent { - type: GeminiEventType.Content; - value: string; -} - -export interface GeminiToolCallInfoEvent { - type: GeminiEventType.ToolCallInfo; - value: ToolCallEvent; -} - -export type GeminiEvent = GeminiContentEvent | GeminiToolCallInfoEvent; - -export type GeminiStream = AsyncIterable; - +// Only defining the state enum needed by the UI export enum StreamingState { - Idle, - Responding, + Idle = 'idle', + Responding = 'responding', + WaitingForConfirmation = 'waiting_for_confirmation', } -interface StreamProcessorParams { - stream: GeminiStream; - signal: AbortSignal; - setHistory: React.Dispatch>; - submitQuery: (query: Part) => Promise; - getNextMessageId: () => number; - addHistoryItem: (itemData: Omit, id: number) => void; - currentToolGroupIdRef: React.MutableRefObject; +// Copied from server/src/core/turn.ts for CLI usage +export enum GeminiEventType { + Content = 'content', + ToolCallRequest = 'tool_call_request', + // Add other event types if the UI hook needs to handle them } - -/** - * Processes the Gemini stream, managing text buffering, adaptive rendering, - * and delegating history updates for tool calls and errors. - */ -export const processGeminiStream = async ({ - // Renamed function for clarity - stream, - signal, - setHistory, - submitQuery, - getNextMessageId, - addHistoryItem, - currentToolGroupIdRef, -}: StreamProcessorParams): Promise => { - // --- State specific to this stream processing invocation --- - let textBuffer = ''; - let renderTimeoutId: NodeJS.Timeout | null = null; - let isStreamComplete = false; - let currentGeminiMessageId: number | null = null; - - const render = (content: string) => { - if (currentGeminiMessageId === null) { - return; - } - setHistory((prev) => - prev.map((item) => - item.id === currentGeminiMessageId && item.type === 'gemini' - ? { ...item, text: (item.text ?? '') + content } - : item, - ), - ); - }; - // --- Adaptive Rendering Logic (nested) --- - const renderBufferedText = () => { - if (signal.aborted) { - if (renderTimeoutId) clearTimeout(renderTimeoutId); - renderTimeoutId = null; - return; - } - - const bufferLength = textBuffer.length; - let chunkSize = 0; - let delay = 50; - - if (bufferLength > 150) { - chunkSize = Math.min(bufferLength, 30); - delay = 5; - } else if (bufferLength > 30) { - chunkSize = Math.min(bufferLength, 10); - delay = 10; - } else if (bufferLength > 0) { - chunkSize = 2; - delay = 20; - } - - if (chunkSize > 0) { - const chunkToRender = textBuffer.substring(0, chunkSize); - textBuffer = textBuffer.substring(chunkSize); - render(chunkToRender); - - renderTimeoutId = setTimeout(renderBufferedText, delay); - } else { - renderTimeoutId = null; // Clear timeout ID if nothing to render - if (!isStreamComplete) { - // Buffer empty, but stream might still send data, check again later - renderTimeoutId = setTimeout(renderBufferedText, 50); - } - } - }; - - const scheduleRender = () => { - if (renderTimeoutId === null) { - renderTimeoutId = setTimeout(renderBufferedText, 0); - } - }; - - // --- Stream Processing Loop --- - try { - for await (const chunk of stream) { - if (signal.aborted) break; - - if (chunk.type === GeminiEventType.Content) { - currentToolGroupIdRef.current = null; // Reset tool group on text - - if (currentGeminiMessageId === null) { - currentGeminiMessageId = getNextMessageId(); - addHistoryItem({ type: 'gemini', text: '' }, currentGeminiMessageId); - textBuffer = ''; - } - textBuffer += chunk.value; - scheduleRender(); - } else if (chunk.type === GeminiEventType.ToolCallInfo) { - if (renderTimeoutId) { - // Stop rendering loop - clearTimeout(renderTimeoutId); - renderTimeoutId = null; - } - // Flush any text buffer content. - render(textBuffer); - currentGeminiMessageId = null; // End text message context - textBuffer = ''; // Clear buffer - - // Delegate history update for tool call - handleToolCallChunk( - chunk.value, - setHistory, - submitQuery, - getNextMessageId, - currentToolGroupIdRef, - ); - } - } - if (signal.aborted) { - throw new Error('Request cancelled by user'); - } - } catch (error: unknown) { - if (renderTimeoutId) { - // Ensure render loop stops on error - clearTimeout(renderTimeoutId); - renderTimeoutId = null; - } - // Delegate history update for error message - addErrorMessageToHistory( - error as Error | DOMException, - setHistory, - getNextMessageId, - ); - } finally { - isStreamComplete = true; // Signal stream end for render loop completion - if (renderTimeoutId) { - clearTimeout(renderTimeoutId); - renderTimeoutId = null; - } - - renderBufferedText(); // Force final render - } -}; diff --git a/packages/cli/src/core/history-updater.ts b/packages/cli/src/core/history-updater.ts index 5363bfce..f56e76ca 100644 --- a/packages/cli/src/core/history-updater.ts +++ b/packages/cli/src/core/history-updater.ts @@ -54,9 +54,9 @@ export const handleToolCallChunk = ( handleToolCallChunk( { ...chunk, - status: ToolCallStatus.Canceled, + status: ToolCallStatus.Error, confirmationDetails: undefined, - resultDisplay, + resultDisplay: resultDisplay ?? 'Canceled by user.', }, setHistory, submitQuery, diff --git a/packages/cli/src/core/turn.ts b/packages/cli/src/core/turn.ts deleted file mode 100644 index e8c4ef78..00000000 --- a/packages/cli/src/core/turn.ts +++ /dev/null @@ -1,233 +0,0 @@ -import { - Part, - Chat, - PartListUnion, - GenerateContentResponse, - FunctionCall, -} from '@google/genai'; -import { - type ToolCallConfirmationDetails, - ToolCallStatus, - ToolCallEvent, -} from '../ui/types.js'; -import { ToolResult } from '../tools/tools.js'; -import { toolRegistry } from '../tools/tool-registry.js'; -import { GeminiEventType, GeminiStream } from './gemini-stream.js'; - -export type ToolExecutionOutcome = { - callId: string; - name: string; - args: Record; - result?: ToolResult; - error?: Error; - confirmationDetails?: ToolCallConfirmationDetails; -}; - -// TODO(jbd): Move ToolExecutionOutcome to somewhere else? - -// A turn manages the agentic loop turn. -// Turn.run emits throught the turn events that could be used -// as immediate feedback to the user. -export class Turn { - private readonly chat: Chat; - private pendingToolCalls: Array<{ - callId: string; - name: string; - args: Record; - }>; - private fnResponses: Part[]; - private debugResponses: GenerateContentResponse[]; - - constructor(chat: Chat) { - this.chat = chat; - this.pendingToolCalls = []; - this.fnResponses = []; - this.debugResponses = []; - } - - async *run(req: PartListUnion, signal?: AbortSignal): GeminiStream { - const responseStream = await this.chat.sendMessageStream({ - message: req, - }); - for await (const resp of responseStream) { - this.debugResponses.push(resp); - if (signal?.aborted) { - throw this.abortError(); - } - if (resp.text) { - yield { - type: GeminiEventType.Content, - value: resp.text, - }; - continue; - } - if (!resp.functionCalls) { - continue; - } - for (const fnCall of resp.functionCalls) { - for await (const event of this.handlePendingFunctionCall(fnCall)) { - yield event; - } - } - - // Create promises to be able to wait for executions to complete. - const toolPromises = this.pendingToolCalls.map( - async (pendingToolCall) => { - const tool = toolRegistry.getTool(pendingToolCall.name); - if (!tool) { - return { - ...pendingToolCall, - error: new Error( - `Tool "${pendingToolCall.name}" not found or is not registered.`, - ), - }; - } - const shouldConfirm = await tool.shouldConfirmExecute( - pendingToolCall.args, - ); - if (shouldConfirm) { - return { - // TODO(jbd): Should confirm isn't confirmation details. - ...pendingToolCall, - confirmationDetails: shouldConfirm, - }; - } - const result = await tool.execute(pendingToolCall.args); - return { ...pendingToolCall, result }; - }, - ); - const outcomes = await Promise.all(toolPromises); - for await (const event of this.handleToolOutcomes(outcomes)) { - yield event; - } - this.pendingToolCalls = []; - - // TODO(jbd): Make it harder for the caller to ignore the - // buffered function responses. - this.fnResponses = this.buildFunctionResponses(outcomes); - } - } - - private async *handlePendingFunctionCall(fnCall: FunctionCall): GeminiStream { - const callId = - fnCall.id ?? - `${fnCall.name}-${Date.now()}-${Math.random().toString(16).slice(2)}`; - // TODO(jbd): replace with uuid. - const name = fnCall.name || 'undefined_tool_name'; - const args = (fnCall.args || {}) as Record; - - this.pendingToolCalls.push({ callId, name, args }); - const value: ToolCallEvent = { - type: 'tool_call', - status: ToolCallStatus.Pending, - callId, - name, - args, - resultDisplay: undefined, - confirmationDetails: undefined, - }; - yield { - type: GeminiEventType.ToolCallInfo, - value, - }; - } - - private async *handleToolOutcomes( - outcomes: ToolExecutionOutcome[], - ): GeminiStream { - for (const outcome of outcomes) { - const { callId, name, args, result, error, confirmationDetails } = - outcome; - if (error) { - // TODO(jbd): Error handling needs a cleanup. - const errorMessage = error?.message || String(error); - yield { - type: GeminiEventType.Content, - value: `[Error invoking tool ${name}: ${errorMessage}]`, - }; - return; - } - if ( - result && - typeof result === 'object' && - result !== null && - 'error' in result - ) { - const errorMessage = String(result.error); - yield { - type: GeminiEventType.Content, - value: `[Error executing tool ${name}: ${errorMessage}]`, - }; - return; - } - const status = confirmationDetails - ? ToolCallStatus.Confirming - : ToolCallStatus.Invoked; - const value: ToolCallEvent = { - type: 'tool_call', - status, - callId, - name, - args, - resultDisplay: result?.returnDisplay, - confirmationDetails, - }; - yield { - type: GeminiEventType.ToolCallInfo, - value, - }; - } - } - - private buildFunctionResponses(outcomes: ToolExecutionOutcome[]): Part[] { - return outcomes.map((outcome: ToolExecutionOutcome): Part => { - const { name, result, error } = outcome; - const output = { output: result?.llmContent }; - let fnResponse: Record; - - if (error) { - const errorMessage = error?.message || String(error); - fnResponse = { - error: `Invocation failed: ${errorMessage}`, - }; - console.error(`[Turn] Critical error invoking tool ${name}:`, error); - } else if ( - result && - typeof result === 'object' && - result !== null && - 'error' in result - ) { - fnResponse = output; - console.warn( - `[Turn] Tool ${name} returned an error structure:`, - result.error, - ); - } else { - fnResponse = output; - } - - return { - functionResponse: { - name, - id: outcome.callId, - response: fnResponse, - }, - }; - }); - } - - private abortError(): Error { - // TODO(jbd): Move it out of this class. - const error = new Error('Request cancelled by user during stream.'); - error.name = 'AbortError'; - throw error; - } - - getFunctionResponses(): Part[] { - return this.fnResponses; - } - - getDebugResponses(): GenerateContentResponse[] { - return this.debugResponses; - } -} diff --git a/packages/cli/src/gemini.ts b/packages/cli/src/gemini.ts index feab6c17..c69810a5 100644 --- a/packages/cli/src/gemini.ts +++ b/packages/cli/src/gemini.ts @@ -16,20 +16,19 @@ import { EditTool } from './tools/edit.tool.js'; import { TerminalTool } from './tools/terminal.tool.js'; import { WriteFileTool } from './tools/write-file.tool.js'; import { WebFetchTool } from './tools/web-fetch.tool.js'; -import { globalConfig } from './config/config.js'; - -// TODO(b/411707095): remove. left here as an example of how to pull in inter-package deps -import { helloServer } from '@gemini-code/server'; -helloServer(); +import { loadCliConfig } from './config/config.js'; async function main() { - // Configure tools - registerTools(globalConfig.getTargetDir()); + // Load configuration + const config = loadCliConfig(); - // Render UI + // Configure tools using the loaded config + registerTools(config.getTargetDir()); + + // Render UI, passing necessary config values render( React.createElement(App, { - directory: globalConfig.getTargetDir(), + config, }), ); } @@ -81,12 +80,13 @@ main().catch((error) => { }); function registerTools(targetDir: string) { + const config = loadCliConfig(); const lsTool = new LSTool(targetDir); const readFileTool = new ReadFileTool(targetDir); const grepTool = new GrepTool(targetDir); const globTool = new GlobTool(targetDir); const editTool = new EditTool(targetDir); - const terminalTool = new TerminalTool(targetDir); + const terminalTool = new TerminalTool(targetDir, config); const writeFileTool = new WriteFileTool(targetDir); const webFetchTool = new WebFetchTool(); diff --git a/packages/cli/src/tools/edit.tool.ts b/packages/cli/src/tools/edit.tool.ts index 5803f23a..75bb59a8 100644 --- a/packages/cli/src/tools/edit.tool.ts +++ b/packages/cli/src/tools/edit.tool.ts @@ -6,233 +6,63 @@ import fs from 'fs'; import path from 'path'; -import * as Diff from 'diff'; -import { SchemaValidator } from '../utils/schemaValidator.js'; -import { BaseTool, ToolResult } from './tools.js'; +import { + EditLogic, + EditToolParams, + ToolResult, + makeRelative, + shortenPath, + isNodeError, +} from '@gemini-code/server'; +import { BaseTool } from './tools.js'; import { ToolCallConfirmationDetails, ToolConfirmationOutcome, ToolEditConfirmationDetails, } from '../ui/types.js'; -import { makeRelative, shortenPath } from '../utils/paths.js'; -import { ReadFileTool } from './read-file.tool.js'; -import { WriteFileTool } from './write-file.tool.js'; -import { isNodeError } from '../utils/errors.js'; +import * as Diff from 'diff'; /** - * Parameters for the Edit tool - */ -export interface EditToolParams { - /** - * The absolute path to the file to modify - */ - file_path: string; - - /** - * The text to replace - */ - old_string: string; - - /** - * The text to replace it with - */ - new_string: string; - - /** - * The expected number of replacements to perform (optional, defaults to 1) - */ - expected_replacements?: number; -} - -interface CalculatedEdit { - currentContent: string | null; - newContent: string; - occurrences: number; - error?: { display: string; raw: string }; - isNewFile: boolean; -} - -/** - * Implementation of the Edit tool that modifies files. - * This tool maintains state for the "Always Edit" confirmation preference. + * CLI wrapper for the Edit tool. + * Handles confirmation prompts and potentially UI-specific state like 'Always Edit'. */ export class EditTool extends BaseTool { + static readonly Name: string = EditLogic.Name; + private coreLogic: EditLogic; private shouldAlwaysEdit = false; - private readonly rootDirectory: string; /** - * Creates a new instance of the EditTool + * Creates a new instance of the EditTool CLI wrapper * @param rootDirectory Root directory to ground this tool in. */ constructor(rootDirectory: string) { + const coreLogicInstance = new EditLogic(rootDirectory); super( - 'replace', + EditTool.Name, 'Edit', - `Replaces a SINGLE, UNIQUE occurrence of text within a file. Requires providing significant context around the change to ensure uniqueness. For moving/renaming files, use the Bash tool with \`mv\`. For replacing entire file contents or creating new files use the ${WriteFileTool.Name} tool. Always use the ${ReadFileTool.Name} tool to examine the file before using this tool.`, - { - properties: { - file_path: { - description: - 'The absolute path to the file to modify. Must start with /. When creating a new file, ensure the parent directory exists (use the `LS` tool to verify).', - type: 'string', - }, - old_string: { - description: - 'The exact text to replace. CRITICAL: Must uniquely identify the single instance to change. Include at least 3-5 lines of context BEFORE and AFTER the target text, matching whitespace and indentation precisely. If this string matches multiple locations or does not match exactly, the tool will fail. Use an empty string ("") when creating a new file.', - type: 'string', - }, - new_string: { - description: - 'The text to replace the `old_string` with. When creating a new file (using an empty `old_string`), this should contain the full desired content of the new file. Ensure the resulting code is correct and idiomatic.', - type: 'string', - }, - }, - required: ['file_path', 'old_string', 'new_string'], - type: 'object', - }, + `Replaces a SINGLE, UNIQUE occurrence of text within a file. Requires providing significant context around the change to ensure uniqueness. For moving/renaming files, use the Bash tool with \`mv\`. For replacing entire file contents or creating new files use the WriteFile tool. Always use the ReadFile tool to examine the file before using this tool.`, + (coreLogicInstance.schema.parameters as Record) ?? {}, ); - this.rootDirectory = path.resolve(rootDirectory); + this.coreLogic = coreLogicInstance; } /** - * Checks if a path is within the root directory. - * @param pathToCheck The absolute path to check. - * @returns True if the path is within the root directory, false otherwise. + * Delegates validation to the core logic */ - private isWithinRoot(pathToCheck: string): boolean { - const normalizedPath = path.normalize(pathToCheck); - const normalizedRoot = this.rootDirectory; - - const rootWithSep = normalizedRoot.endsWith(path.sep) - ? normalizedRoot - : normalizedRoot + path.sep; - - return ( - normalizedPath === normalizedRoot || - normalizedPath.startsWith(rootWithSep) - ); + validateToolParams(params: EditToolParams): string | null { + return this.coreLogic.validateParams(params); } /** - * Validates the parameters for the Edit tool - * @param params Parameters to validate - * @returns True if parameters are valid, false otherwise + * Delegates getting description to the core logic */ - validateParams(params: EditToolParams): boolean { - if ( - this.schema.parameters && - !SchemaValidator.validate( - this.schema.parameters as Record, - params, - ) - ) { - return false; - } - - // Ensure path is absolute - if (!path.isAbsolute(params.file_path)) { - console.error(`File path must be absolute: ${params.file_path}`); - return false; - } - - // Ensure path is within the root directory - if (!this.isWithinRoot(params.file_path)) { - console.error( - `File path must be within the root directory (${this.rootDirectory}): ${params.file_path}`, - ); - return false; - } - - // Validate expected_replacements if provided - if ( - params.expected_replacements !== undefined && - params.expected_replacements < 0 - ) { - console.error('Expected replacements must be a non-negative number'); - return false; - } - - return true; + getDescription(params: EditToolParams): string { + return this.coreLogic.getDescription(params); } /** - * Calculates the potential outcome of an edit operation. - * @param params Parameters for the edit operation - * @returns An object describing the potential edit outcome - * @throws File system errors if reading the file fails unexpectedly (e.g., permissions) - */ - private calculateEdit(params: EditToolParams): CalculatedEdit { - const expectedReplacements = - params.expected_replacements === undefined - ? 1 - : params.expected_replacements; - let currentContent: string | null = null; - let fileExists = false; - let isNewFile = false; - let newContent = ''; - let occurrences = 0; - let error: { display: string; raw: string } | undefined = undefined; - - try { - currentContent = fs.readFileSync(params.file_path, 'utf8'); - fileExists = true; - } catch (err: unknown) { - if (!isNodeError(err) || err.code !== 'ENOENT') { - throw err; - } - fileExists = false; - } - - if (params.old_string === '' && !fileExists) { - isNewFile = true; - newContent = params.new_string; - occurrences = 0; - } else if (!fileExists) { - error = { - display: `File not found.`, - raw: `File not found: ${params.file_path}`, - }; - } else if (currentContent !== null) { - occurrences = this.countOccurrences(currentContent, params.old_string); - - if (occurrences === 0) { - error = { - display: `No edits made`, - raw: `Failed to edit, 0 occurrences found`, - }; - } else if (occurrences !== expectedReplacements) { - error = { - display: `Failed to edit, expected ${expectedReplacements} occurrences but found ${occurrences}`, - raw: `Failed to edit, Expected ${expectedReplacements} occurrences but found ${occurrences} in file: ${params.file_path}`, - }; - } else { - newContent = this.replaceAll( - currentContent, - params.old_string, - params.new_string, - ); - } - } else { - error = { - display: `Failed to read content`, - raw: `Failed to read content of existing file: ${params.file_path}`, - }; - } - - return { - currentContent, - newContent, - occurrences, - error, - isNewFile, - }; - } - - /** - * Determines if confirmation is needed and prepares the confirmation details. - * This method performs the calculation needed to generate the diff and respects the `shouldAlwaysEdit` state. - * @param params Parameters for the potential edit operation - * @returns Confirmation details object or false if no confirmation is needed/possible. + * Handles the confirmation prompt for the Edit tool in the CLI. + * It needs to calculate the diff to show the user. */ async shouldConfirmExecute( params: EditToolParams, @@ -240,40 +70,62 @@ export class EditTool extends BaseTool { if (this.shouldAlwaysEdit) { return false; } - - if (!this.validateParams(params)) { + const validationError = this.validateToolParams(params); + if (validationError) { console.error( - '[EditTool] Attempted confirmation with invalid parameters.', + `[EditTool Wrapper] Attempted confirmation with invalid parameters: ${validationError}`, ); return false; } - - let calculatedEdit: CalculatedEdit; + let currentContent: string | null = null; + let fileExists = false; + let newContent = ''; try { - calculatedEdit = this.calculateEdit(params); - } catch (error) { - console.error( - `Error calculating edit for confirmation: ${error instanceof Error ? error.message : String(error)}`, + currentContent = fs.readFileSync(params.file_path, 'utf8'); + fileExists = true; + } catch (err: unknown) { + if (isNodeError(err) && err.code === 'ENOENT') { + fileExists = false; + } else { + console.error(`Error reading file for confirmation diff: ${err}`); + return false; + } + } + if (params.old_string === '' && !fileExists) { + newContent = params.new_string; + } else if (!fileExists) { + return false; + } else if (currentContent !== null) { + const occurrences = this.coreLogic['countOccurrences']( + currentContent, + params.old_string, ); + const expectedReplacements = + params.expected_replacements === undefined + ? 1 + : params.expected_replacements; + if (occurrences === 0 || occurrences !== expectedReplacements) { + return false; + } + newContent = this.coreLogic['replaceAll']( + currentContent, + params.old_string, + params.new_string, + ); + } else { return false; } - - if (calculatedEdit.error) { - return false; - } - const fileName = path.basename(params.file_path); const fileDiff = Diff.createPatch( fileName, - calculatedEdit.currentContent ?? '', - calculatedEdit.newContent, + currentContent ?? '', + newContent, 'Current', 'Proposed', - { context: 3, ignoreWhitespace: true }, + { context: 3 }, ); - const confirmationDetails: ToolEditConfirmationDetails = { - title: `Confirm Edit: ${shortenPath(makeRelative(params.file_path, this.rootDirectory))}`, + title: `Confirm Edit: ${shortenPath(makeRelative(params.file_path, this.coreLogic['rootDirectory']))}`, fileName, fileDiff, onConfirm: async (outcome: ToolConfirmationOutcome) => { @@ -285,122 +137,10 @@ export class EditTool extends BaseTool { return confirmationDetails; } - getDescription(params: EditToolParams): string { - const relativePath = makeRelative(params.file_path, this.rootDirectory); - const oldStringSnippet = - params.old_string.split('\n')[0].substring(0, 30) + - (params.old_string.length > 30 ? '...' : ''); - const newStringSnippet = - params.new_string.split('\n')[0].substring(0, 30) + - (params.new_string.length > 30 ? '...' : ''); - return `${shortenPath(relativePath)}: ${oldStringSnippet} => ${newStringSnippet}`; - } - /** - * Executes the edit operation with the given parameters. - * This method recalculates the edit operation before execution. - * @param params Parameters for the edit operation - * @returns Result of the edit operation + * Delegates execution to the core logic */ async execute(params: EditToolParams): Promise { - if (!this.validateParams(params)) { - return { - llmContent: 'Invalid parameters for file edit operation', - returnDisplay: '**Error:** Invalid parameters for file edit operation', - }; - } - - let editData: CalculatedEdit; - try { - editData = this.calculateEdit(params); - } catch (error) { - return { - llmContent: `Error preparing edit: ${error instanceof Error ? error.message : String(error)}`, - returnDisplay: 'Failed to prepare edit', - }; - } - - if (editData.error) { - return { - llmContent: editData.error.raw, - returnDisplay: editData.error.display, - }; - } - - try { - this.ensureParentDirectoriesExist(params.file_path); - fs.writeFileSync(params.file_path, editData.newContent, 'utf8'); - - if (editData.isNewFile) { - return { - llmContent: `Created new file: ${params.file_path} with provided content.`, - returnDisplay: `Created ${shortenPath(makeRelative(params.file_path, this.rootDirectory))}`, - }; - } else { - const fileName = path.basename(params.file_path); - const fileDiff = Diff.createPatch( - fileName, - editData.currentContent ?? '', - editData.newContent, - 'Current', - 'Proposed', - { context: 3, ignoreWhitespace: true }, - ); - - return { - llmContent: `Successfully modified file: ${params.file_path} (${editData.occurrences} replacements).`, - returnDisplay: { fileDiff }, - }; - } - } catch (error) { - return { - llmContent: `Error executing edit: ${error instanceof Error ? error.message : String(error)}`, - returnDisplay: `Failed to edit file`, - }; - } - } - - /** - * Counts occurrences of a substring in a string - * @param str String to search in - * @param substr Substring to count - * @returns Number of occurrences - */ - private countOccurrences(str: string, substr: string): number { - if (substr === '') { - return 0; - } - let count = 0; - let pos = str.indexOf(substr); - while (pos !== -1) { - count++; - pos = str.indexOf(substr, pos + substr.length); - } - return count; - } - - /** - * Replaces all occurrences of a substring in a string - * @param str String to modify - * @param find Substring to find - * @param replace Replacement string - * @returns Modified string - */ - private replaceAll(str: string, find: string, replace: string): string { - if (find === '') { - return str; - } - return str.split(find).join(replace); - } - - /** - * Creates parent directories if they don't exist - * @param filePath Path to ensure parent directories exist - */ - private ensureParentDirectoriesExist(filePath: string): void { - const dirName = path.dirname(filePath); - if (!fs.existsSync(dirName)) { - fs.mkdirSync(dirName, { recursive: true }); - } + return this.coreLogic.execute(params); } } diff --git a/packages/cli/src/tools/glob.tool.ts b/packages/cli/src/tools/glob.tool.ts index b846db46..8a56d51b 100644 --- a/packages/cli/src/tools/glob.tool.ts +++ b/packages/cli/src/tools/glob.tool.ts @@ -4,247 +4,72 @@ * SPDX-License-Identifier: Apache-2.0 */ -import fs from 'fs'; -import path from 'path'; -import fg from 'fast-glob'; -import { SchemaValidator } from '../utils/schemaValidator.js'; -import { BaseTool, ToolResult } from './tools.js'; -import { shortenPath, makeRelative } from '../utils/paths.js'; +// Import core logic and types from the server package +import { GlobLogic, GlobToolParams, ToolResult } from '@gemini-code/server'; + +// Import CLI-specific base class and types +import { BaseTool } from './tools.js'; +import { ToolCallConfirmationDetails } from '../ui/types.js'; /** - * Parameters for the GlobTool - */ -export interface GlobToolParams { - /** - * The glob pattern to match files against - */ - pattern: string; - - /** - * The directory to search in (optional, defaults to current directory) - */ - path?: string; -} - -/** - * Implementation of the GlobTool that finds files matching patterns, - * sorted by modification time (newest first). + * CLI wrapper for the Glob tool */ export class GlobTool extends BaseTool { - /** - * The root directory that this tool is grounded in. - * All file operations will be restricted to this directory. - */ - private rootDirectory: string; + static readonly Name: string = GlobLogic.Name; // Use name from logic + + // Core logic instance from the server package + private coreLogic: GlobLogic; /** - * Creates a new instance of the GlobTool - * @param rootDirectory Root directory to ground this tool in. All operations will be restricted to this directory. + * Creates a new instance of the GlobTool CLI wrapper + * @param rootDirectory Root directory to ground this tool in. */ constructor(rootDirectory: string) { + // Instantiate the core logic from the server package + const coreLogicInstance = new GlobLogic(rootDirectory); + + // Initialize the CLI BaseTool super( - 'glob', - 'FindFiles', - 'Efficiently finds files matching specific glob patterns (e.g., `src/**/*.ts`, `**/*.md`), returning absolute paths sorted by modification time (newest first). Ideal for quickly locating files based on their name or path structure, especially in large codebases.', - { - properties: { - pattern: { - description: - "The glob pattern to match against (e.g., '*.py', 'src/**/*.js', 'docs/*.md').", - type: 'string', - }, - path: { - description: - 'Optional: The absolute path to the directory to search within. If omitted, searches the root directory.', - type: 'string', - }, - }, - required: ['pattern'], - type: 'object', - }, + GlobTool.Name, + 'FindFiles', // Define display name here + 'Efficiently finds files matching specific glob patterns (e.g., `src/**/*.ts`, `**/*.md`), returning absolute paths sorted by modification time (newest first). Ideal for quickly locating files based on their name or path structure, especially in large codebases.', // Define description here + (coreLogicInstance.schema.parameters as Record) ?? {}, ); - // Set the root directory - this.rootDirectory = path.resolve(rootDirectory); + this.coreLogic = coreLogicInstance; } /** - * Checks if a path is within the root directory. - * This is a security measure to prevent the tool from accessing files outside of its designated root. - * @param pathToCheck The path to check (expects an absolute path) - * @returns True if the path is within the root directory, false otherwise - */ - private isWithinRoot(pathToCheck: string): boolean { - const absolutePathToCheck = path.resolve(pathToCheck); - const normalizedPath = path.normalize(absolutePathToCheck); - const normalizedRoot = path.normalize(this.rootDirectory); - - // Ensure the normalizedRoot ends with a path separator for proper prefix comparison - const rootWithSep = normalizedRoot.endsWith(path.sep) - ? normalizedRoot - : normalizedRoot + path.sep; - - // Check if it's the root itself or starts with the root path followed by a separator. - // This ensures that we don't accidentally allow access to parent directories. - return ( - normalizedPath === normalizedRoot || - normalizedPath.startsWith(rootWithSep) - ); - } - - /** - * Validates the parameters for the tool. - * Ensures that the provided parameters adhere to the expected schema and that the search path is valid and within the tool's root directory. - * @param params Parameters to validate - * @returns An error message string if invalid, null otherwise + * Delegates validation to the core logic */ validateToolParams(params: GlobToolParams): string | null { - if ( - this.schema.parameters && - !SchemaValidator.validate( - this.schema.parameters as Record, - params, - ) - ) { - return "Parameters failed schema validation. Ensure 'pattern' is a string and 'path' (if provided) is a string."; - } - - // Determine the absolute path to check - const searchDirAbsolute = params.path ?? this.rootDirectory; - - // Validate path is within root directory - if (!this.isWithinRoot(searchDirAbsolute)) { - return `Search path ("${searchDirAbsolute}") resolves outside the tool's root directory ("${this.rootDirectory}").`; - } - - // Validate path exists and is a directory using the absolute path. - // These checks prevent the tool from attempting to search in non-existent or non-directory paths, which would lead to errors. - try { - if (!fs.existsSync(searchDirAbsolute)) { - return `Search path does not exist: ${shortenPath(makeRelative(searchDirAbsolute, this.rootDirectory))} (absolute: ${searchDirAbsolute})`; - } - if (!fs.statSync(searchDirAbsolute).isDirectory()) { - return `Search path is not a directory: ${shortenPath(makeRelative(searchDirAbsolute, this.rootDirectory))} (absolute: ${searchDirAbsolute})`; - } - } catch (e: unknown) { - // Catch potential permission errors during sync checks - return `Error accessing search path: ${e}`; - } - - // Validate glob pattern (basic non-empty check) - if ( - !params.pattern || - typeof params.pattern !== 'string' || - params.pattern.trim() === '' - ) { - return "The 'pattern' parameter cannot be empty."; - } - // Could add more sophisticated glob pattern validation if needed - - return null; // Parameters are valid + return this.coreLogic.validateToolParams(params); } /** - * Gets a description of the glob operation. - * @param params Parameters for the glob operation. - * @returns A string describing the glob operation. + * Delegates getting description to the core logic */ getDescription(params: GlobToolParams): string { - let description = `'${params.pattern}'`; - - if (params.path) { - const searchDir = params.path || this.rootDirectory; - const relativePath = makeRelative(searchDir, this.rootDirectory); - description += ` within ${shortenPath(relativePath)}`; - } - - return description; + return this.coreLogic.getDescription(params); } /** - * Executes the glob search with the given parameters - * @param params Parameters for the glob search - * @returns Result of the glob search + * Define confirmation behavior (Glob likely doesn't need confirmation) + */ + shouldConfirmExecute( + // eslint-disable-next-line @typescript-eslint/no-unused-vars + params: GlobToolParams, + ): Promise { + return Promise.resolve(false); + } + + /** + * Delegates execution to the core logic */ async execute(params: GlobToolParams): Promise { - const validationError = this.validateToolParams(params); - if (validationError) { - return { - llmContent: `Error: Invalid parameters provided. Reason: ${validationError}`, - returnDisplay: `**Error:** Failed to execute tool.`, - }; - } - - try { - // 1. Resolve the absolute search directory. Validation ensures it exists and is a directory. - const searchDirAbsolute = params.path ?? this.rootDirectory; - - // 2. Perform Glob Search using fast-glob - // We use fast-glob because it's performant and supports glob patterns. - const entries = await fg(params.pattern, { - cwd: searchDirAbsolute, // Search within this absolute directory - absolute: true, // Return absolute paths - onlyFiles: true, // Match only files - stats: true, // Include file stats object for sorting - dot: true, // Include files starting with a dot - ignore: ['**/node_modules/**', '**/.git/**'], // Common sensible default, adjust as needed - followSymbolicLinks: false, // Avoid potential issues with symlinks unless specifically needed - suppressErrors: true, // Suppress EACCES errors for individual files (we handle dir access in validation) - }); - - // 3. Handle No Results - if (!entries || entries.length === 0) { - return { - llmContent: `No files found matching pattern "${params.pattern}" within ${searchDirAbsolute}.`, - returnDisplay: `No files found`, - }; - } - - // 4. Sort Results by Modification Time (Newest First) - // Sorting by modification time ensures that the most recently modified files are listed first. - // This can be useful for quickly identifying the files that have been recently changed. - // The stats object is guaranteed by the `stats: true` option in the fast-glob configuration. - entries.sort((a, b) => { - // Ensure stats exist before accessing mtime (though fg should provide them) - const mtimeA = a.stats?.mtime?.getTime() ?? 0; - const mtimeB = b.stats?.mtime?.getTime() ?? 0; - return mtimeB - mtimeA; // Descending order - }); - - // 5. Format Output - const sortedAbsolutePaths = entries.map((entry) => entry.path); - - // Convert absolute paths to relative paths (to rootDir) for clearer display - const sortedRelativePaths = sortedAbsolutePaths.map((absPath) => - makeRelative(absPath, this.rootDirectory), - ); - - // Construct the result message - const fileListDescription = sortedRelativePaths - .map((p) => ` - ${shortenPath(p)}`) - .join('\n'); - const fileCount = sortedRelativePaths.length; - const relativeSearchDir = makeRelative( - searchDirAbsolute, - this.rootDirectory, - ); - const displayPath = shortenPath( - relativeSearchDir === '.' ? 'root directory' : relativeSearchDir, - ); - - return { - llmContent: `Found ${fileCount} file(s) matching "${params.pattern}" within ${displayPath}, sorted by modification time (newest first):\n${fileListDescription}`, - returnDisplay: `Found ${fileCount} matching file(s)`, - }; - } catch (error) { - // Catch unexpected errors during glob execution (less likely with suppressErrors=true, but possible) - const errorMessage = - error instanceof Error ? error.message : String(error); - console.error(`GlobTool execute Error: ${errorMessage}`, error); - return { - llmContent: `Error during glob search operation: ${errorMessage}`, - returnDisplay: `**Error:** An unexpected error occurred.`, - }; - } + return this.coreLogic.execute(params); } + + // Removed private methods (isWithinRoot) + // as they are now part of GlobLogic in the server package. } diff --git a/packages/cli/src/tools/grep.tool.ts b/packages/cli/src/tools/grep.tool.ts index 79eb9770..50cff362 100644 --- a/packages/cli/src/tools/grep.tool.ts +++ b/packages/cli/src/tools/grep.tool.ts @@ -4,578 +4,76 @@ * SPDX-License-Identifier: Apache-2.0 */ -import fs from 'fs'; // Used for sync checks in validation -import fsPromises from 'fs/promises'; // Used for async operations in fallback -import path from 'path'; -import { EOL } from 'os'; // Used for parsing grep output lines -import { spawn } from 'child_process'; // Used for git grep and system grep -import fastGlob from 'fast-glob'; // Used for JS fallback file searching -import { BaseTool, ToolResult } from './tools.js'; -import { SchemaValidator } from '../utils/schemaValidator.js'; -import { makeRelative, shortenPath } from '../utils/paths.js'; -import { getErrorMessage, isNodeError } from '../utils/errors.js'; +// Import core logic and types from the server package +import { GrepLogic, GrepToolParams, ToolResult } from '@gemini-code/server'; -// --- Interfaces (kept separate for clarity) --- +// Import CLI-specific base class and types +import { BaseTool } from './tools.js'; +import { ToolCallConfirmationDetails } from '../ui/types.js'; + +// --- Interfaces (Params defined in server package) --- + +// --- GrepTool CLI Wrapper Class --- /** - * Parameters for the GrepTool - */ -export interface GrepToolParams { - /** - * The regular expression pattern to search for in file contents - */ - pattern: string; - - /** - * The directory to search in (optional, defaults to current directory relative to root) - */ - path?: string; - - /** - * File pattern to include in the search (e.g. "*.js", "*.{ts,tsx}") - */ - include?: string; -} - -/** - * Result object for a single grep match - */ -interface GrepMatch { - filePath: string; - lineNumber: number; - line: string; -} - -// --- GrepTool Class --- - -/** - * Implementation of the GrepTool that searches file contents using git grep, system grep, or JS fallback. + * CLI wrapper for the Grep tool */ export class GrepTool extends BaseTool { - private rootDirectory: string; + static readonly Name: string = GrepLogic.Name; // Use name from logic + + // Core logic instance from the server package + private coreLogic: GrepLogic; /** - * Creates a new instance of the GrepTool - * @param rootDirectory Root directory to ground this tool in. All operations will be restricted to this directory. + * Creates a new instance of the GrepTool CLI wrapper + * @param rootDirectory Root directory to ground this tool in. */ constructor(rootDirectory: string) { + // Instantiate the core logic from the server package + const coreLogicInstance = new GrepLogic(rootDirectory); + + // Initialize the CLI BaseTool super( - 'search_file_content', - 'SearchText', - 'Searches for a regular expression pattern within the content of files in a specified directory (or current working directory). Can filter files by a glob pattern. Returns the lines containing matches, along with their file paths and line numbers.', - { - properties: { - pattern: { - description: - "The regular expression (regex) pattern to search for within file contents (e.g., 'function\\s+myFunction', 'import\\s+\\{.*\\}\\s+from\\s+.*').", - type: 'string', - }, - path: { - description: - 'Optional: The absolute path to the directory to search within. If omitted, searches the current working directory.', - type: 'string', - }, - include: { - description: - "Optional: A glob pattern to filter which files are searched (e.g., '*.js', '*.{ts,tsx}', 'src/**'). If omitted, searches all files (respecting potential global ignores).", - type: 'string', - }, - }, - required: ['pattern'], - type: 'object', - }, + GrepTool.Name, + 'SearchText', // Define display name here + 'Searches for a regular expression pattern within the content of files in a specified directory (or current working directory). Can filter files by a glob pattern. Returns the lines containing matches, along with their file paths and line numbers.', // Define description here + (coreLogicInstance.schema.parameters as Record) ?? {}, ); - // Ensure rootDirectory is absolute and normalized - this.rootDirectory = path.resolve(rootDirectory); - } - // --- Validation Methods --- - - /** - * Checks if a path is within the root directory and resolves it. - * @param relativePath Path relative to the root directory (or undefined for root). - * @returns The absolute path if valid and exists. - * @throws {Error} If path is outside root, doesn't exist, or isn't a directory. - */ - private resolveAndValidatePath(relativePath?: string): string { - const targetPath = path.resolve(this.rootDirectory, relativePath || '.'); - - // Security Check: Ensure the resolved path is still within the root directory. - if ( - !targetPath.startsWith(this.rootDirectory) && - targetPath !== this.rootDirectory - ) { - throw new Error( - `Path validation failed: Attempted path "${relativePath || '.'}" resolves outside the allowed root directory "${this.rootDirectory}".`, - ); - } - - // Check existence and type after resolving - try { - const stats = fs.statSync(targetPath); - if (!stats.isDirectory()) { - throw new Error(`Path is not a directory: ${targetPath}`); - } - } catch (error: unknown) { - if (isNodeError(error) && error.code !== 'ENOENT') { - throw new Error(`Path does not exist: ${targetPath}`); - } - throw new Error( - `Failed to access path stats for ${targetPath}: ${error}`, - ); - } - - return targetPath; + this.coreLogic = coreLogicInstance; } /** - * Validates the parameters for the tool - * @param params Parameters to validate - * @returns An error message string if invalid, null otherwise + * Delegates validation to the core logic */ validateToolParams(params: GrepToolParams): string | null { - if ( - this.schema.parameters && - !SchemaValidator.validate( - this.schema.parameters as Record, - params, - ) - ) { - return 'Parameters failed schema validation.'; - } - - try { - new RegExp(params.pattern); - } catch (error) { - return `Invalid regular expression pattern provided: ${params.pattern}. Error: ${error instanceof Error ? error.message : String(error)}`; - } - - try { - this.resolveAndValidatePath(params.path); - } catch (error) { - return error instanceof Error ? error.message : String(error); - } - - return null; // Parameters are valid - } - - // --- Core Execution --- - - /** - * Executes the grep search with the given parameters - * @param params Parameters for the grep search - * @returns Result of the grep search - */ - async execute(params: GrepToolParams): Promise { - const validationError = this.validateToolParams(params); - if (validationError) { - console.error(`GrepTool Parameter Validation Failed: ${validationError}`); - return { - llmContent: `Error: Invalid parameters provided. Reason: ${validationError}`, - returnDisplay: `**Error:** Failed to execute tool.`, - }; - } - - let searchDirAbs: string; - try { - searchDirAbs = this.resolveAndValidatePath(params.path); - const searchDirDisplay = params.path || '.'; - - const matches: GrepMatch[] = await this.performGrepSearch({ - pattern: params.pattern, - path: searchDirAbs, - include: params.include, - }); - - if (matches.length === 0) { - const noMatchMsg = `No matches found for pattern "${params.pattern}" in path "${searchDirDisplay}"${params.include ? ` (filter: "${params.include}")` : ''}.`; - const noMatchUser = `No matches found`; - return { llmContent: noMatchMsg, returnDisplay: noMatchUser }; - } - - const matchesByFile = matches.reduce( - (acc, match) => { - const relativeFilePath = - path.relative( - searchDirAbs, - path.resolve(searchDirAbs, match.filePath), - ) || path.basename(match.filePath); - if (!acc[relativeFilePath]) { - acc[relativeFilePath] = []; - } - acc[relativeFilePath].push(match); - acc[relativeFilePath].sort((a, b) => a.lineNumber - b.lineNumber); - return acc; - }, - {} as Record, - ); - - let llmContent = `Found ${matches.length} match(es) for pattern "${params.pattern}" in path "${searchDirDisplay}"${params.include ? ` (filter: "${params.include}")` : ''}:\n---\n`; - - for (const filePath in matchesByFile) { - llmContent += `File: ${filePath}\n`; - matchesByFile[filePath].forEach((match) => { - const trimmedLine = match.line.trim(); - llmContent += `L${match.lineNumber}: ${trimmedLine}\n`; - }); - llmContent += '---\n'; - } - - return { - llmContent: llmContent.trim(), - returnDisplay: `Found ${matches.length} matche(s)`, - }; - } catch (error) { - console.error(`Error during GrepTool execution: ${error}`); - const errorMessage = - error instanceof Error ? error.message : String(error); - return { - llmContent: `Error during grep search operation: ${errorMessage}`, - returnDisplay: errorMessage, - }; - } - } - - // --- Inlined Grep Logic and Helpers --- - - /** - * Checks if a command is available in the system's PATH. - * @param {string} command The command name (e.g., 'git', 'grep'). - * @returns {Promise} True if the command is available, false otherwise. - */ - private isCommandAvailable(command: string): Promise { - return new Promise((resolve) => { - const checkCommand = process.platform === 'win32' ? 'where' : 'command'; - const checkArgs = - process.platform === 'win32' ? [command] : ['-v', command]; - try { - const child = spawn(checkCommand, checkArgs, { - stdio: 'ignore', - shell: process.platform === 'win32', - }); - child.on('close', (code) => resolve(code === 0)); - child.on('error', () => resolve(false)); - } catch { - resolve(false); - } - }); + return this.coreLogic.validateToolParams(params); } /** - * Checks if a directory or its parent directories contain a .git folder. - * @param {string} dirPath Absolute path to the directory to check. - * @returns {Promise} True if it's a Git repository, false otherwise. - */ - private async isGitRepository(dirPath: string): Promise { - let currentPath = path.resolve(dirPath); - const root = path.parse(currentPath).root; - - try { - while (true) { - const gitPath = path.join(currentPath, '.git'); - try { - const stats = await fsPromises.stat(gitPath); - if (stats.isDirectory() || stats.isFile()) { - return true; - } - return false; - } catch (error: unknown) { - if (!isNodeError(error) || error.code !== 'ENOENT') { - console.error( - `Error checking for .git in ${currentPath}: ${error}`, - ); - return false; - } - } - - if (currentPath === root) { - break; - } - currentPath = path.dirname(currentPath); - } - } catch (error: unknown) { - console.error( - `Error traversing directory structure upwards from ${dirPath}: ${error instanceof Error ? error.message : error}`, - ); - } - return false; - } - - /** - * Parses the standard output of grep-like commands (git grep, system grep). - * Expects format: filePath:lineNumber:lineContent - * Handles colons within file paths and line content correctly. - * @param {string} output The raw stdout string. - * @param {string} basePath The absolute directory the search was run from, for relative paths. - * @returns {GrepMatch[]} Array of match objects. - */ - private parseGrepOutput(output: string, basePath: string): GrepMatch[] { - const results: GrepMatch[] = []; - if (!output) return results; - - const lines = output.split(EOL); // Use OS-specific end-of-line - - for (const line of lines) { - if (!line.trim()) continue; - - // Find the index of the first colon. - const firstColonIndex = line.indexOf(':'); - if (firstColonIndex === -1) { - // Malformed line: Does not contain any colon. Skip. - continue; - } - - // Find the index of the second colon, searching *after* the first one. - const secondColonIndex = line.indexOf(':', firstColonIndex + 1); - if (secondColonIndex === -1) { - // Malformed line: Contains only one colon (e.g., filename:content). Skip. - // Grep output with -n should always have file:line:content. - continue; - } - - // Extract parts based on the found colon indices - const filePathRaw = line.substring(0, firstColonIndex); - const lineNumberStr = line.substring( - firstColonIndex + 1, - secondColonIndex, - ); - // The rest of the line, starting after the second colon, is the content. - const lineContent = line.substring(secondColonIndex + 1); - - const lineNumber = parseInt(lineNumberStr, 10); - - if (!isNaN(lineNumber)) { - // Resolve the raw path relative to the base path where grep ran - const absoluteFilePath = path.resolve(basePath, filePathRaw); - // Make the final path relative to the basePath for consistency - const relativeFilePath = path.relative(basePath, absoluteFilePath); - - results.push({ - // Use relative path, or just the filename if it's in the base path itself - filePath: relativeFilePath || path.basename(absoluteFilePath), - lineNumber, - line: lineContent, // Use the full extracted line content - }); - } - // Silently ignore lines where the line number isn't parsable - } - return results; - } - - /** - * Gets a description of the grep operation - * @param params Parameters for the grep operation - * @returns A string describing the grep + * Delegates getting description to the core logic */ getDescription(params: GrepToolParams): string { - let description = `'${params.pattern}'`; - - if (params.include) { - description += ` in ${params.include}`; - } - - if (params.path) { - const searchDir = params.path || this.rootDirectory; - const relativePath = makeRelative(searchDir, this.rootDirectory); - description += ` within ${shortenPath(relativePath || './')}`; - } - - return description; + return this.coreLogic.getDescription(params); } /** - * Performs the actual search using the prioritized strategies. - * @param options Search options including pattern, absolute path, and include glob. - * @returns A promise resolving to an array of match objects. + * Define confirmation behavior (Grep likely doesn't need confirmation) */ - private async performGrepSearch(options: { - pattern: string; - path: string; // Expects absolute path - include?: string; - }): Promise { - const { pattern, path: absolutePath, include } = options; - let strategyUsed = 'none'; // Keep track for potential error reporting - - try { - // --- Strategy 1: git grep --- - const isGit = await this.isGitRepository(absolutePath); - const gitAvailable = isGit && (await this.isCommandAvailable('git')); - - if (gitAvailable) { - strategyUsed = 'git grep'; - const gitArgs = [ - 'grep', - '--untracked', - '-n', - '-E', - '--ignore-case', - pattern, - ]; - if (include) { - gitArgs.push('--', include); - } - - try { - const output = await new Promise((resolve, reject) => { - const child = spawn('git', gitArgs, { - cwd: absolutePath, - windowsHide: true, - }); - const stdoutChunks: Buffer[] = []; - const stderrChunks: Buffer[] = []; - - child.stdout.on('data', (chunk) => { - stdoutChunks.push(chunk); - }); - child.stderr.on('data', (chunk) => { - stderrChunks.push(chunk); - }); - - child.on('error', (err) => - reject(new Error(`Failed to start git grep: ${err.message}`)), - ); - - child.on('close', (code) => { - const stdoutData = Buffer.concat(stdoutChunks).toString('utf8'); - const stderrData = Buffer.concat(stderrChunks).toString('utf8'); - if (code === 0) resolve(stdoutData); - else if (code === 1) - resolve(''); // No matches is not an error - else - reject( - new Error(`git grep exited with code ${code}: ${stderrData}`), - ); - }); - }); - return this.parseGrepOutput(output, absolutePath); - } catch (gitError: unknown) { - console.error( - `GrepTool: git grep strategy failed: ${getErrorMessage(gitError)}. Falling back...`, - ); - } - } - - // --- Strategy 2: System grep --- - const grepAvailable = await this.isCommandAvailable('grep'); - if (grepAvailable) { - strategyUsed = 'system grep'; - const grepArgs = ['-r', '-n', '-H', '-E']; - const commonExcludes = ['.git', 'node_modules', 'bower_components']; - commonExcludes.forEach((dir) => grepArgs.push(`--exclude-dir=${dir}`)); - if (include) { - grepArgs.push(`--include=${include}`); - } - grepArgs.push(pattern); - grepArgs.push('.'); - - try { - const output = await new Promise((resolve, reject) => { - const child = spawn('grep', grepArgs, { - cwd: absolutePath, - windowsHide: true, - }); - const stdoutChunks: Buffer[] = []; - const stderrChunks: Buffer[] = []; - - child.stdout.on('data', (chunk) => { - stdoutChunks.push(chunk); - }); - child.stderr.on('data', (chunk) => { - const stderrStr = chunk.toString(); - if ( - !stderrStr.includes('Permission denied') && - !/grep:.*: Is a directory/i.test(stderrStr) - ) { - stderrChunks.push(chunk); - } - }); - - child.on('error', (err) => - reject(new Error(`Failed to start system grep: ${err.message}`)), - ); - - child.on('close', (code) => { - const stdoutData = Buffer.concat(stdoutChunks).toString('utf8'); - const stderrData = Buffer.concat(stderrChunks) - .toString('utf8') - .trim(); - if (code === 0) resolve(stdoutData); - else if (code === 1) - resolve(''); // No matches - else { - if (stderrData) - reject( - new Error( - `System grep exited with code ${code}: ${stderrData}`, - ), - ); - else resolve(''); - } - }); - }); - return this.parseGrepOutput(output, absolutePath); - } catch (grepError: unknown) { - console.error( - `GrepTool: System grep strategy failed: ${getErrorMessage(grepError)}. Falling back...`, - ); - } - } - - // --- Strategy 3: Pure JavaScript Fallback --- - strategyUsed = 'javascript fallback'; - const globPattern = include ? include : '**/*'; - const ignorePatterns = [ - '.git', - 'node_modules', - 'bower_components', - '.svn', - '.hg', - ]; - - const filesStream = fastGlob.stream(globPattern, { - cwd: absolutePath, - dot: true, - ignore: ignorePatterns, - absolute: true, - onlyFiles: true, - suppressErrors: true, - stats: false, - }); - - const regex = new RegExp(pattern, 'i'); - const allMatches: GrepMatch[] = []; - - for await (const filePath of filesStream) { - const fileAbsolutePath = filePath as string; - try { - const content = await fsPromises.readFile(fileAbsolutePath, 'utf8'); - const lines = content.split(/\r?\n/); - lines.forEach((line, index) => { - if (regex.test(line)) { - allMatches.push({ - filePath: - path.relative(absolutePath, fileAbsolutePath) || - path.basename(fileAbsolutePath), - lineNumber: index + 1, - line, - }); - } - }); - } catch (readError: unknown) { - if (!isNodeError(readError) || readError.code !== 'ENOENT') { - console.error( - `GrepTool: Could not read or process file ${fileAbsolutePath}: ${getErrorMessage(readError)}`, - ); - } - } - } - - return allMatches; - } catch (error: unknown) { - console.error( - `GrepTool: Error during performGrepSearch (Strategy: ${strategyUsed}): ${getErrorMessage(error)}`, - ); - throw error; // Re-throw to be caught by the execute method's handler - } + shouldConfirmExecute( + // eslint-disable-next-line @typescript-eslint/no-unused-vars + params: GrepToolParams, + ): Promise { + return Promise.resolve(false); } + + /** + * Delegates execution to the core logic + */ + async execute(params: GrepToolParams): Promise { + return this.coreLogic.execute(params); + } + + // Removed private methods (resolveAndValidatePath, performGrepSearch, etc.) + // as they are now part of GrepLogic in the server package. } diff --git a/packages/cli/src/tools/ls.tool.ts b/packages/cli/src/tools/ls.tool.ts index 8592e593..6259f2fc 100644 --- a/packages/cli/src/tools/ls.tool.ts +++ b/packages/cli/src/tools/ls.tool.ts @@ -4,267 +4,75 @@ * SPDX-License-Identifier: Apache-2.0 */ -import fs from 'fs'; -import path from 'path'; -import { BaseTool, ToolResult } from './tools.js'; -import { SchemaValidator } from '../utils/schemaValidator.js'; -import { makeRelative, shortenPath } from '../utils/paths.js'; +// Import core logic and types from the server package +import { LSLogic, LSToolParams, ToolResult } from '@gemini-code/server'; + +// Import CLI-specific base class and types +import { BaseTool } from './tools.js'; +import { ToolCallConfirmationDetails } from '../ui/types.js'; /** - * Parameters for the LS tool - */ -export interface LSToolParams { - /** - * The absolute path to the directory to list - */ - path: string; - - /** - * List of glob patterns to ignore - */ - ignore?: string[]; -} - -/** - * 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; -} - -/** - * Implementation of the LS tool that lists directory contents + * CLI wrapper for the LS tool */ export class LSTool extends BaseTool { - /** - * The root directory that this tool is grounded in. - * All path operations will be restricted to this directory. - */ - private rootDirectory: string; + static readonly Name: string = LSLogic.Name; // Use name from logic + + // Core logic instance from the server package + private coreLogic: LSLogic; /** - * Creates a new instance of the LSTool - * @param rootDirectory Root directory to ground this tool in. All operations will be restricted to this directory. + * Creates a new instance of the LSTool CLI wrapper + * @param rootDirectory Root directory to ground this tool in. */ constructor(rootDirectory: string) { + // Instantiate the core logic from the server package + const coreLogicInstance = new LSLogic(rootDirectory); + + // Initialize the CLI BaseTool super( - 'list_directory', - 'ReadFolder', - 'Lists the names of files and subdirectories directly within a specified directory path. Can optionally ignore entries matching provided glob patterns.', - { - 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', - }, - }, - required: ['path'], - type: 'object', - }, + LSTool.Name, + 'ReadFolder', // Define display name here + 'Lists the names of files and subdirectories directly within a specified directory path. Can optionally ignore entries matching provided glob patterns.', // Define description here + (coreLogicInstance.schema.parameters as Record) ?? {}, ); - // Set the root directory - this.rootDirectory = path.resolve(rootDirectory); + this.coreLogic = coreLogicInstance; } /** - * Checks if a path is within the root directory - * @param dirpath The path to check - * @returns True if the path is within the root directory, false otherwise - */ - private isWithinRoot(dirpath: string): boolean { - const normalizedPath = path.normalize(dirpath); - const normalizedRoot = path.normalize(this.rootDirectory); - // Ensure the normalizedRoot ends with a path separator for proper path comparison - const rootWithSep = normalizedRoot.endsWith(path.sep) - ? normalizedRoot - : normalizedRoot + path.sep; - return ( - normalizedPath === normalizedRoot || - normalizedPath.startsWith(rootWithSep) - ); - } - - /** - * Validates the parameters for the tool - * @param params Parameters to validate - * @returns An error message string if invalid, null otherwise + * Delegates validation to the core logic */ validateToolParams(params: LSToolParams): string | null { - if ( - this.schema.parameters && - !SchemaValidator.validate( - this.schema.parameters as Record, - params, - ) - ) { - return 'Parameters failed schema validation.'; - } - if (!path.isAbsolute(params.path)) { - return `Path must be absolute: ${params.path}`; - } - if (!this.isWithinRoot(params.path)) { - return `Path must be within the root directory (${this.rootDirectory}): ${params.path}`; - } - return null; + return this.coreLogic.validateToolParams(params); } /** - * 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 - * @param params Parameters for the file reading - * @returns A string describing the file being read + * Delegates getting description to the core logic */ getDescription(params: LSToolParams): string { - const relativePath = makeRelative(params.path, this.rootDirectory); - return shortenPath(relativePath); - } - - private errorResult(llmContent: string, returnDisplay: string): ToolResult { - return { - llmContent, - returnDisplay: `**Error:** ${returnDisplay}`, - }; + return this.coreLogic.getDescription(params); } /** - * Executes the LS operation with the given parameters - * @param params Parameters for the LS operation - * @returns Result of the LS operation + * Define confirmation behavior (LS likely doesn't need confirmation) + */ + shouldConfirmExecute( + // eslint-disable-next-line @typescript-eslint/no-unused-vars + params: LSToolParams, + ): Promise { + return Promise.resolve(false); + } + + /** + * Delegates execution to the core logic */ async execute(params: LSToolParams): Promise { - const validationError = this.validateToolParams(params); - if (validationError) { - return this.errorResult( - `Error: Invalid parameters provided. Reason: ${validationError}`, - `Failed to execute tool.`, - ); - } - - try { - const stats = fs.statSync(params.path); - if (!stats) { - return this.errorResult( - `Directory does not exist: ${params.path}`, - `Directory does not exist.`, - ); - } - if (!stats.isDirectory()) { - return this.errorResult( - `Path is not a directory: ${params.path}`, - `Path is not a directory.`, - ); - } - - const files = fs.readdirSync(params.path); - const entries: FileEntry[] = []; - if (files.length === 0) { - return this.errorResult( - `Directory is empty: ${params.path}`, - `Directory is empty.`, - ); - } - - for (const file of files) { - if (this.shouldIgnore(file, params.ignore)) { - continue; - } - - const fullPath = path.join(params.path, file); - try { - const stats = fs.statSync(fullPath); - const isDir = stats.isDirectory(); - entries.push({ - name: file, - path: fullPath, - isDirectory: isDir, - size: isDir ? 0 : stats.size, - modifiedTime: stats.mtime, - }); - } catch (error) { - 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 display - const directoryContent = entries - .map((entry) => { - const typeIndicator = entry.isDirectory ? 'd' : '-'; - const sizeInfo = entry.isDirectory ? '' : ` (${entry.size} bytes)`; - return `${typeIndicator} ${entry.name}${sizeInfo}`; - }) - .join('\n'); - - return { - llmContent: `Directory listing for ${params.path}:\n${directoryContent}`, - returnDisplay: `Found ${entries.length} item(s).`, - }; - } catch (error) { - return this.errorResult( - `Error listing directory: ${error instanceof Error ? error.message : String(error)}`, - 'Failed to list directory.', - ); - } + // The CLI wrapper could potentially modify the returnDisplay + // from the core logic if needed, but for LS, the core logic's + // display might be sufficient. + return this.coreLogic.execute(params); } + + // Removed private methods (isWithinRoot, shouldIgnore, errorResult) + // as they are now part of LSLogic in the server package. } diff --git a/packages/cli/src/tools/read-file.tool.ts b/packages/cli/src/tools/read-file.tool.ts index 0ebe2dbc..bbf9eafb 100644 --- a/packages/cli/src/tools/read-file.tool.ts +++ b/packages/cli/src/tools/read-file.tool.ts @@ -4,288 +4,65 @@ * SPDX-License-Identifier: Apache-2.0 */ -import fs from 'fs'; -import path from 'path'; -import { SchemaValidator } from '../utils/schemaValidator.js'; -import { makeRelative, shortenPath } from '../utils/paths.js'; -import { BaseTool, ToolResult } from './tools.js'; +import { + ReadFileLogic, + ReadFileToolParams, + ToolResult, +} from '@gemini-code/server'; +import { BaseTool } from './tools.js'; +import { ToolCallConfirmationDetails } from '../ui/types.js'; /** - * Parameters for the ReadFile tool - */ -export interface ReadFileToolParams { - /** - * The absolute path to the file to read - */ - file_path: string; - - /** - * The line number to start reading from (optional) - */ - offset?: number; - - /** - * The number of lines to read (optional) - */ - limit?: number; -} - -/** - * Implementation of the ReadFile tool that reads files from the filesystem + * CLI wrapper for the ReadFile tool */ export class ReadFileTool extends BaseTool { - static readonly Name: string = 'read_file'; - - // Maximum number of lines to read by default - private static readonly DEFAULT_MAX_LINES = 2000; - - // Maximum length of a line before truncating - private static readonly MAX_LINE_LENGTH = 2000; + static readonly Name: string = ReadFileLogic.Name; + private coreLogic: ReadFileLogic; /** - * The root directory that this tool is grounded in. - * All file operations will be restricted to this directory. - */ - private rootDirectory: string; - - /** - * Creates a new instance of the ReadFileTool - * @param rootDirectory Root directory to ground this tool in. All operations will be restricted to this directory. + * Creates a new instance of the ReadFileTool CLI wrapper + * @param rootDirectory Root directory to ground this tool in. */ constructor(rootDirectory: string) { + const coreLogicInstance = new ReadFileLogic(rootDirectory); super( ReadFileTool.Name, 'ReadFile', 'Reads and returns the content of a specified file from the local filesystem. Handles large files by allowing reading specific line ranges.', - { - properties: { - file_path: { - description: - "The absolute path to the file to read (e.g., '/home/user/project/file.txt'). Relative paths are not supported.", - type: 'string', - }, - offset: { - description: - "Optional: The 0-based line number to start reading from. Requires 'limit' to be set. Use for paginating through large files.", - type: 'number', - }, - limit: { - description: - "Optional: Maximum number of lines to read. Use with 'offset' to paginate through large files. If omitted, reads the entire file (if feasible).", - type: 'number', - }, - }, - required: ['file_path'], - type: 'object', - }, + (coreLogicInstance.schema.parameters as Record) ?? {}, ); - - // Set the root directory - this.rootDirectory = path.resolve(rootDirectory); + this.coreLogic = coreLogicInstance; } /** - * Checks if a path is within the root directory - * @param pathToCheck The path to check - * @returns True if the path is within the root directory, false otherwise + * Delegates validation to the core logic */ - private isWithinRoot(pathToCheck: string): boolean { - const normalizedPath = path.normalize(pathToCheck); - const normalizedRoot = path.normalize(this.rootDirectory); - - // Ensure the normalizedRoot ends with a path separator for proper path comparison - const rootWithSep = normalizedRoot.endsWith(path.sep) - ? normalizedRoot - : normalizedRoot + path.sep; - - return ( - normalizedPath === normalizedRoot || - normalizedPath.startsWith(rootWithSep) - ); - } - - /** - * Validates the parameters for the ReadFile tool - * @param params Parameters to validate - * @returns True if parameters are valid, false otherwise - */ - validateToolParams(params: ReadFileToolParams): string | null { - if ( - this.schema.parameters && - !SchemaValidator.validate( - this.schema.parameters as Record, - params, - ) - ) { - return 'Parameters failed schema validation.'; - } - const filePath = params.file_path; - if (!path.isAbsolute(filePath)) { - return `File path must be absolute: ${filePath}`; - } - if (!this.isWithinRoot(filePath)) { - return `File path must be within the root directory (${this.rootDirectory}): ${filePath}`; - } - if (params.offset !== undefined && params.offset < 0) { - return 'Offset must be a non-negative number'; - } - if (params.limit !== undefined && params.limit <= 0) { - return 'Limit must be a positive number'; - } + validateToolParams(_params: ReadFileToolParams): string | null { + // Currently allowing any path. Add validation if needed. return null; } /** - * Determines if a file is likely binary based on content sampling - * @param filePath Path to the file - * @returns True if the file appears to be binary + * Delegates getting description to the core logic */ - private isBinaryFile(filePath: string): boolean { - try { - // Read the first 4KB of the file - const fd = fs.openSync(filePath, 'r'); - const buffer = Buffer.alloc(4096); - const bytesRead = fs.readSync(fd, buffer, 0, 4096, 0); - fs.closeSync(fd); - - // Check for null bytes or high concentration of non-printable characters - let nonPrintableCount = 0; - for (let i = 0; i < bytesRead; i++) { - // Null byte is a strong indicator of binary data - if (buffer[i] === 0) { - return true; - } - - // Count non-printable characters - if (buffer[i] < 9 || (buffer[i] > 13 && buffer[i] < 32)) { - nonPrintableCount++; - } - } - - // If more than 30% are non-printable, likely binary - return nonPrintableCount / bytesRead > 0.3; - } catch { - return false; - } + getDescription(_params: ReadFileToolParams): string { + return this.coreLogic.getDescription(_params); } /** - * Detects the type of file based on extension and content - * @param filePath Path to the file - * @returns File type description + * Define confirmation behavior here in the CLI wrapper if needed + * For ReadFile, we likely don't need confirmation. */ - private detectFileType(filePath: string): string { - const ext = path.extname(filePath).toLowerCase(); - - // Common image formats - if ( - ['.jpg', '.jpeg', '.png', '.gif', '.bmp', '.webp', '.svg'].includes(ext) - ) { - return 'image'; - } - - // Other known binary formats - if (['.pdf', '.zip', '.tar', '.gz', '.exe', '.dll', '.so'].includes(ext)) { - return 'binary'; - } - - // Check content for binary indicators - if (this.isBinaryFile(filePath)) { - return 'binary'; - } - - return 'text'; + shouldConfirmExecute( + _params: ReadFileToolParams, + ): Promise { + return Promise.resolve(false); } /** - * Gets a description of the file reading operation - * @param params Parameters for the file reading - * @returns A string describing the file being read - */ - getDescription(params: ReadFileToolParams): string { - const relativePath = makeRelative(params.file_path, this.rootDirectory); - return shortenPath(relativePath); - } - - /** - * Reads a file and returns its contents with line numbers - * @param params Parameters for the file reading - * @returns Result with file contents + * Delegates execution to the core logic */ async execute(params: ReadFileToolParams): Promise { - const validationError = this.validateToolParams(params); - if (validationError) { - return { - llmContent: `Error: Invalid parameters provided. Reason: ${validationError}`, - returnDisplay: '**Error:** Failed to execute tool.', - }; - } - - const filePath = params.file_path; - try { - if (!fs.existsSync(filePath)) { - return { - llmContent: `File not found: ${filePath}`, - returnDisplay: `File not found.`, - }; - } - - const stats = fs.statSync(filePath); - if (stats.isDirectory()) { - return { - llmContent: `Path is a directory, not a file: ${filePath}`, - returnDisplay: `File is directory.`, - }; - } - - const fileType = this.detectFileType(filePath); - if (fileType !== 'text') { - return { - llmContent: `Binary file: ${filePath} (${fileType})`, - returnDisplay: ``, - }; - } - - const content = fs.readFileSync(filePath, 'utf8'); - const lines = content.split('\n'); - - const startLine = params.offset || 0; - const endLine = params.limit - ? startLine + params.limit - : Math.min(startLine + ReadFileTool.DEFAULT_MAX_LINES, lines.length); - const selectedLines = lines.slice(startLine, endLine); - - let truncated = false; - const formattedLines = selectedLines.map((line) => { - let processedLine = line; - if (line.length > ReadFileTool.MAX_LINE_LENGTH) { - processedLine = - line.substring(0, ReadFileTool.MAX_LINE_LENGTH) + '... [truncated]'; - truncated = true; - } - - return processedLine; - }); - - const contentTruncated = endLine < lines.length || truncated; - - let llmContent = ''; - if (contentTruncated) { - llmContent += `[File truncated: showing lines ${startLine + 1}-${endLine} of ${lines.length} total lines. Use offset parameter to view more.]\n`; - } - llmContent += formattedLines.join('\n'); - - return { - llmContent, - returnDisplay: '', - }; - } catch (error) { - const errorMsg = `Error reading file: ${error instanceof Error ? error.message : String(error)}`; - - return { - llmContent: `Error reading file ${filePath}: ${errorMsg}`, - returnDisplay: `Failed to read file: ${errorMsg}`, - }; - } + return this.coreLogic.execute(params); } } diff --git a/packages/cli/src/tools/terminal.tool.ts b/packages/cli/src/tools/terminal.tool.ts index 5b75463b..3813b7e8 100644 --- a/packages/cli/src/tools/terminal.tool.ts +++ b/packages/cli/src/tools/terminal.tool.ts @@ -8,22 +8,25 @@ import { spawn, SpawnOptions, ChildProcessWithoutNullStreams, -} from 'child_process'; // Added 'exec' +} from 'child_process'; import path from 'path'; import os from 'os'; import crypto from 'crypto'; import { promises as fs } from 'fs'; +import { + SchemaValidator, + getErrorMessage, + isNodeError, + Config, +} from '@gemini-code/server'; import { BaseTool, ToolResult } from './tools.js'; -import { SchemaValidator } from '../utils/schemaValidator.js'; import { ToolCallConfirmationDetails, ToolConfirmationOutcome, ToolExecuteConfirmationDetails, -} from '../ui/types.js'; // Adjust path as needed +} from '../ui/types.js'; import { BackgroundTerminalAnalyzer } from '../utils/BackgroundTerminalAnalyzer.js'; -import { getErrorMessage, isNodeError } from '../utils/errors.js'; -// --- Interfaces --- export interface TerminalToolParams { command: string; description?: string; @@ -31,15 +34,13 @@ export interface TerminalToolParams { runInBackground?: boolean; } -// --- Constants --- -const MAX_OUTPUT_LENGTH = 10000; // Default max output length -const DEFAULT_TIMEOUT_MS = 30 * 60 * 1000; // 30 minutes (for foreground commands) -const MAX_TIMEOUT_OVERRIDE_MS = 10 * 60 * 1000; // 10 minutes (max override for foreground) -const BACKGROUND_LAUNCH_TIMEOUT_MS = 15 * 1000; // 15 seconds timeout for *launching* background tasks -const BACKGROUND_POLL_TIMEOUT_MS = 30000; // 30 seconds total polling time for background process status +const MAX_OUTPUT_LENGTH = 10000; +const DEFAULT_TIMEOUT_MS = 30 * 60 * 1000; +const MAX_TIMEOUT_OVERRIDE_MS = 10 * 60 * 1000; +const BACKGROUND_LAUNCH_TIMEOUT_MS = 15 * 1000; +const BACKGROUND_POLL_TIMEOUT_MS = 30000; const BANNED_COMMAND_ROOTS = [ - // Session/flow control (excluding cd) 'alias', 'bg', 'command', @@ -64,7 +65,7 @@ const BANNED_COMMAND_ROOTS = [ 'popd', 'printf', 'pushd', - /* 'pwd' is safe */ 'read', + 'read', 'readonly', 'set', 'shift', @@ -81,7 +82,6 @@ const BANNED_COMMAND_ROOTS = [ 'unalias', 'unset', 'wait', - // Network commands 'curl', 'wget', 'nc', @@ -92,9 +92,7 @@ const BANNED_COMMAND_ROOTS = [ 'sftp', 'http', 'https', - 'ftp', 'rsync', - // Browsers/GUI launchers 'lynx', 'w3m', 'links', @@ -110,20 +108,15 @@ const BANNED_COMMAND_ROOTS = [ 'open', ]; -// --- Helper Type for Command Queue --- interface QueuedCommand { params: TerminalToolParams; resolve: (result: ToolResult) => void; reject: (error: Error) => void; - confirmationDetails: ToolExecuteConfirmationDetails | false; // Kept for potential future use + confirmationDetails: ToolExecuteConfirmationDetails | false; } -/** - * Implementation of the terminal tool that executes shell commands within a persistent session. - */ export class TerminalTool extends BaseTool { static Name: string = 'execute_bash_command'; - private readonly rootDirectory: string; private readonly outputLimit: number; private bashProcess: ChildProcessWithoutNullStreams | null = null; @@ -131,16 +124,19 @@ export class TerminalTool extends BaseTool { private isExecuting: boolean = false; private commandQueue: QueuedCommand[] = []; private currentCommandCleanup: (() => void) | null = null; - private shouldAlwaysExecuteCommands: Map = new Map(); // Track confirmation per root command + private shouldAlwaysExecuteCommands: Map = new Map(); private shellReady: Promise; - private resolveShellReady: (() => void) | undefined; // Definite assignment assertion - private rejectShellReady: ((reason?: unknown) => void) | undefined; // Definite assignment assertion + private resolveShellReady: (() => void) | undefined; + private rejectShellReady: ((reason?: unknown) => void) | undefined; private readonly backgroundTerminalAnalyzer: BackgroundTerminalAnalyzer; + private readonly config: Config; - constructor(rootDirectory: string, outputLimit: number = MAX_OUTPUT_LENGTH) { + constructor( + rootDirectory: string, + config: Config, + outputLimit: number = MAX_OUTPUT_LENGTH, + ) { const toolDisplayName = 'Terminal'; - // --- LLM-Facing Description --- - // Updated description for background tasks to mention polling and LLM analysis const toolDescription = `Executes one or more bash commands sequentially in a secure and persistent interactive shell session. Can run commands in the foreground (waiting for completion) or background (returning after launch, with subsequent status polling). Core Functionality: @@ -182,7 +178,6 @@ Usage Guidance & Restrictions: * The initial exit code (usually 0) signifies successful *launching*; the final status indicates completion or timeout after polling. Use this tool for running build steps (\`npm install\`, \`make\`), linters (\`eslint .\`), test runners (\`pytest\`, \`jest\`), code formatters (\`prettier --write .\`), package managers (\`pip install\`), version control operations (\`git status\`, \`git diff\`), starting background servers/services (\`node server.js --runInBackground true\`), or other safe, standard command-line operations within the project workspace.`; - // --- Parameter Schema --- const toolParameterSchema = { type: 'object', properties: { @@ -205,14 +200,13 @@ Use this tool for running build steps (\`npm install\`, \`make\`), linters (\`es }, required: ['command'], }; - super( TerminalTool.Name, toolDisplayName, toolDescription, toolParameterSchema, ); - + this.config = config; this.rootDirectory = path.resolve(rootDirectory); this.currentCwd = this.rootDirectory; this.outputLimit = outputLimit; @@ -220,12 +214,10 @@ Use this tool for running build steps (\`npm install\`, \`make\`), linters (\`es this.resolveShellReady = resolve; this.rejectShellReady = reject; }); - this.backgroundTerminalAnalyzer = new BackgroundTerminalAnalyzer(); - + this.backgroundTerminalAnalyzer = new BackgroundTerminalAnalyzer(config); this.initializeShell(); } - // --- Shell Initialization and Management (largely unchanged) --- private initializeShell() { if (this.bashProcess) { try { @@ -234,14 +226,12 @@ Use this tool for running build steps (\`npm install\`, \`make\`), linters (\`es /* Ignore */ } } - const spawnOptions: SpawnOptions = { cwd: this.rootDirectory, shell: true, env: { ...process.env }, stdio: ['pipe', 'pipe', 'pipe'], }; - try { const bashPath = os.platform() === 'win32' ? 'bash.exe' : 'bash'; this.bashProcess = spawn( @@ -249,28 +239,24 @@ Use this tool for running build steps (\`npm install\`, \`make\`), linters (\`es ['-s'], spawnOptions, ) as ChildProcessWithoutNullStreams; - this.currentCwd = this.rootDirectory; // Reset CWD on restart - + this.currentCwd = this.rootDirectory; this.bashProcess.on('error', (err) => { console.error('Persistent Bash Error:', err); - this.rejectShellReady?.(err); // Use optional chaining as reject might be cleared + this.rejectShellReady?.(err); this.bashProcess = null; this.isExecuting = false; this.clearQueue( new Error(`Persistent bash process failed to start: ${err.message}`), ); }); - this.bashProcess.on('close', (code, signal) => { this.bashProcess = null; this.isExecuting = false; - // Only reject if it hasn't been resolved/rejected already this.rejectShellReady?.( new Error( `Persistent bash process exited (code: ${code}, signal: ${signal})`, ), ); - // Reset shell readiness promise for reinitialization attempts this.shellReady = new Promise((resolve, reject) => { this.resolveShellReady = resolve; this.rejectShellReady = reject; @@ -280,27 +266,22 @@ Use this tool for running build steps (\`npm install\`, \`make\`), linters (\`es `Persistent bash process exited unexpectedly (code: ${code}, signal: ${signal}). State is lost. Queued commands cancelled.`, ), ); - // Attempt to reinitialize after a short delay setTimeout(() => this.initializeShell(), 1000); }); - - // Readiness check - ensure shell is responsive - // Slightly longer timeout to allow shell init setTimeout(() => { if (this.bashProcess && !this.bashProcess.killed) { - this.resolveShellReady?.(); // Use optional chaining + this.resolveShellReady?.(); } else if (!this.bashProcess) { - // Error likely already handled by 'error' or 'close' event + // Error likely handled } else { - // Process was killed during init? this.rejectShellReady?.( new Error('Shell killed during initialization'), ); } - }, 1000); // Increase readiness check timeout slightly + }, 1000); } catch (error: unknown) { console.error('Failed to spawn persistent bash:', error); - this.rejectShellReady?.(error); // Use optional chaining + this.rejectShellReady?.(error); this.bashProcess = null; this.clearQueue( new Error(`Failed to spawn persistent bash: ${getErrorMessage(error)}`), @@ -308,7 +289,6 @@ Use this tool for running build steps (\`npm install\`, \`make\`), linters (\`es } } - // --- Parameter Validation (unchanged) --- validateToolParams(params: TerminalToolParams): string | null { if ( !SchemaValidator.validate( @@ -318,16 +298,13 @@ Use this tool for running build steps (\`npm install\`, \`make\`), linters (\`es ) { return `Parameters failed schema validation.`; } - const commandOriginal = params.command.trim(); if (!commandOriginal) { return 'Command cannot be empty.'; } const commandParts = commandOriginal.split(/[\s;&&|]+/); - for (const part of commandParts) { if (!part) continue; - // Improved check: strip leading special chars before checking basename const cleanPart = part .replace(/^[^a-zA-Z0-9]+/, '') @@ -337,18 +314,15 @@ Use this tool for running build steps (\`npm install\`, \`make\`), linters (\`es return `Command contains a banned keyword: '${cleanPart}'. Banned list includes network tools, session control, etc.`; } } - if ( params.timeout !== undefined && (typeof params.timeout !== 'number' || params.timeout <= 0) ) { return 'Timeout must be a positive number of milliseconds.'; } - - return null; // Parameters are valid + return null; } - // --- Description and Confirmation (unchanged) --- getDescription(params: TerminalToolParams): string { return params.description || params.command; } @@ -362,13 +336,10 @@ Use this tool for running build steps (\`npm install\`, \`make\`), linters (\`es .split(/[\s;&&|]+/)[0] ?.split(/[/\\]/) .pop() || 'unknown'; - if (this.shouldAlwaysExecuteCommands.get(rootCommand)) { return false; } - const description = this.getDescription(params); - const confirmationDetails: ToolExecuteConfirmationDetails = { title: 'Confirm Shell Command', command: params.command, @@ -383,7 +354,6 @@ Use this tool for running build steps (\`npm install\`, \`make\`), linters (\`es return confirmationDetails; } - // --- Command Execution and Queueing (unchanged structure) --- async execute(params: TerminalToolParams): Promise { const validationError = this.validateToolParams(params); if (validationError) { @@ -392,23 +362,18 @@ Use this tool for running build steps (\`npm install\`, \`make\`), linters (\`es returnDisplay: `Error: ${validationError}`, }; } - - // Assume confirmation is handled before calling execute - return new Promise((resolve) => { const queuedItem: QueuedCommand = { params, - resolve, // Resolve outer promise + resolve, reject: (error) => resolve({ - // Handle internal errors by resolving outer promise llmContent: `Internal tool error for command: ${params.command}\nError: ${error.message}`, returnDisplay: `Internal Tool Error: ${error.message}`, }), - confirmationDetails: false, // Placeholder + confirmationDetails: false, }; this.commandQueue.push(queuedItem); - // Ensure queue processing is triggered *after* adding the item setImmediate(() => this.triggerQueueProcessing()); }); } @@ -417,24 +382,19 @@ Use this tool for running build steps (\`npm install\`, \`make\`), linters (\`es if (this.isExecuting || this.commandQueue.length === 0) { return; } - this.isExecuting = true; const { params, resolve, reject } = this.commandQueue.shift()!; - try { - await this.shellReady; // Wait for the shell to be ready (or reinitialized) + await this.shellReady; if (!this.bashProcess || this.bashProcess.killed) { - // Check if killed throw new Error( 'Persistent bash process is not available or was killed.', ); } - // **** Core execution logic call **** const result = await this.executeCommandInShell(params); - resolve(result); // Resolve the specific command's promise + resolve(result); } catch (error: unknown) { console.error(`Error executing command "${params.command}":`, error); - if (error instanceof Error) { reject(error); } else { @@ -442,46 +402,37 @@ Use this tool for running build steps (\`npm install\`, \`make\`), linters (\`es } } finally { this.isExecuting = false; - // Use setImmediate to avoid potential deep recursion setImmediate(() => this.triggerQueueProcessing()); } } - // --- **** MODIFIED: Core Command Execution Logic **** --- private executeCommandInShell( params: TerminalToolParams, ): Promise { - // Define temp file paths here to be accessible throughout let tempStdoutPath: string | null = null; let tempStderrPath: string | null = null; - let originalResolve: (value: ToolResult | PromiseLike) => void; // To pass to polling + let originalResolve: (value: ToolResult | PromiseLike) => void; let originalReject: (reason?: unknown) => void; - const promise = new Promise((resolve, reject) => { - originalResolve = resolve; // Assign outer scope resolve - originalReject = reject; // Assign outer scope reject - + originalResolve = resolve; + originalReject = reject; if (!this.bashProcess) { return reject( new Error('Bash process is not running. Cannot execute command.'), ); } - const isBackgroundTask = params.runInBackground ?? false; const commandUUID = crypto.randomUUID(); const startDelimiter = `::START_CMD_${commandUUID}::`; const endDelimiter = `::END_CMD_${commandUUID}::`; const exitCodeDelimiter = `::EXIT_CODE_${commandUUID}::`; - const pidDelimiter = `::PID_${commandUUID}::`; // For background PID - - // --- Initialize Temp Files for Background Task --- + const pidDelimiter = `::PID_${commandUUID}::`; if (isBackgroundTask) { try { const tempDir = os.tmpdir(); tempStdoutPath = path.join(tempDir, `term_out_${commandUUID}.log`); tempStderrPath = path.join(tempDir, `term_err_${commandUUID}.log`); } catch (err: unknown) { - // If temp dir setup fails, reject immediately return reject( new Error( `Failed to determine temporary directory: ${getErrorMessage(err)}`, @@ -489,44 +440,34 @@ Use this tool for running build steps (\`npm install\`, \`make\`), linters (\`es ); } } - // --- End Temp File Init --- - - let stdoutBuffer = ''; // For launch output - let stderrBuffer = ''; // For launch output + let stdoutBuffer = ''; + let stderrBuffer = ''; let commandOutputStarted = false; let exitCode: number | null = null; - let backgroundPid: number | null = null; // Store PID + let backgroundPid: number | null = null; let receivedEndDelimiter = false; - - // Timeout only applies to foreground execution or background *launch* phase const effectiveTimeout = isBackgroundTask ? BACKGROUND_LAUNCH_TIMEOUT_MS : Math.min( - params.timeout ?? DEFAULT_TIMEOUT_MS, // Use default timeout if not provided + params.timeout ?? DEFAULT_TIMEOUT_MS, MAX_TIMEOUT_OVERRIDE_MS, ); - let onStdoutData: ((data: Buffer) => void) | null = null; let onStderrData: ((data: Buffer) => void) | null = null; - let launchTimeoutId: NodeJS.Timeout | null = null; // Renamed for clarity - + let launchTimeoutId: NodeJS.Timeout | null = null; launchTimeoutId = setTimeout(() => { const timeoutMessage = isBackgroundTask ? `Background command launch timed out after ${effectiveTimeout}ms.` : `Command timed out after ${effectiveTimeout}ms.`; - if (!isBackgroundTask && this.bashProcess && !this.bashProcess.killed) { try { - this.bashProcess.stdin.write('\x03'); // Ctrl+C for foreground timeout + this.bashProcess.stdin.write('\x03'); } catch (e: unknown) { console.error('Error writing SIGINT on timeout:', e); } } - // Store listeners before calling cleanup, as cleanup nullifies them const listenersToClean = { onStdoutData, onStderrData }; - cleanupListeners(listenersToClean); // Clean up listeners for this command - - // Clean up temp files if background launch timed out + cleanupListeners(listenersToClean); if (isBackgroundTask && tempStdoutPath && tempStderrPath) { this.cleanupTempFiles(tempStdoutPath, tempStderrPath).catch((err) => { console.warn( @@ -534,18 +475,13 @@ Use this tool for running build steps (\`npm install\`, \`make\`), linters (\`es ); }); } - - // Resolve the main promise with timeout info originalResolve({ llmContent: `Command execution failed: ${timeoutMessage}\nCommand: ${params.command}\nExecuted in: ${this.currentCwd}\n${isBackgroundTask ? 'Mode: Background Launch' : `Mode: Foreground\nTimeout Limit: ${effectiveTimeout}ms`}\nPartial Stdout (Launch):\n${this.truncateOutput(stdoutBuffer)}\nPartial Stderr (Launch):\n${this.truncateOutput(stderrBuffer)}\nNote: ${isBackgroundTask ? 'Launch failed or took too long.' : 'Attempted interrupt (SIGINT). Shell state might be unpredictable if command ignored interrupt.'}`, returnDisplay: `Timeout: ${timeoutMessage}`, }); }, effectiveTimeout); - - // --- Data processing logic (refined slightly) --- const processDataChunk = (chunk: string, isStderr: boolean): boolean => { let dataToProcess = chunk; - if (!commandOutputStarted) { const startIndex = dataToProcess.indexOf(startDelimiter); if (startIndex !== -1) { @@ -554,14 +490,11 @@ Use this tool for running build steps (\`npm install\`, \`make\`), linters (\`es startIndex + startDelimiter.length, ); } else { - return false; // Still waiting for start delimiter + return false; } } - - // Process PID delimiter (mostly expected on stderr for background) const pidIndex = dataToProcess.indexOf(pidDelimiter); if (pidIndex !== -1) { - // Extract PID value strictly between delimiter and newline/end const pidMatch = dataToProcess .substring(pidIndex + pidDelimiter.length) .match(/^(\d+)/); @@ -574,7 +507,6 @@ Use this tool for running build steps (\`npm install\`, \`make\`), linters (\`es else stdoutBuffer += beforePid; dataToProcess = dataToProcess.substring(pidEndIndex); } else { - // Consume delimiter even if no number followed const beforePid = dataToProcess.substring(0, pidIndex); if (isStderr) stderrBuffer += beforePid; else stdoutBuffer += beforePid; @@ -583,8 +515,6 @@ Use this tool for running build steps (\`npm install\`, \`make\`), linters (\`es ); } } - - // Process Exit Code delimiter const exitCodeIndex = dataToProcess.indexOf(exitCodeDelimiter); if (exitCodeIndex !== -1) { const exitCodeMatch = dataToProcess @@ -609,8 +539,6 @@ Use this tool for running build steps (\`npm install\`, \`make\`), linters (\`es ); } } - - // Process End delimiter const endDelimiterIndex = dataToProcess.indexOf(endDelimiter); if (endDelimiterIndex !== -1) { receivedEndDelimiter = true; @@ -620,7 +548,6 @@ Use this tool for running build steps (\`npm install\`, \`make\`), linters (\`es ); if (isStderr) stderrBuffer += beforeEndDelimiter; else stdoutBuffer += beforeEndDelimiter; - // Consume delimiter and potentially the exit code echoed after it const afterEndDelimiter = dataToProcess.substring( endDelimiterIndex + endDelimiter.length, ); @@ -629,64 +556,44 @@ Use this tool for running build steps (\`npm install\`, \`make\`), linters (\`es ? afterEndDelimiter.substring(exitCodeEchoMatch[1].length) : afterEndDelimiter; } - - // Append remaining data if (dataToProcess.length > 0) { if (isStderr) stderrBuffer += dataToProcess; else stdoutBuffer += dataToProcess; } - - // Check completion criteria if (receivedEndDelimiter && exitCode !== null) { - setImmediate(cleanupAndResolve); // Use setImmediate - return true; // Signal completion of this command's stream processing + setImmediate(cleanupAndResolve); + return true; } - - return false; // More data or delimiters expected + return false; }; - - // Assign listeners onStdoutData = (data: Buffer) => processDataChunk(data.toString(), false); onStderrData = (data: Buffer) => processDataChunk(data.toString(), true); - - // --- Cleanup Logic --- - // Pass listeners to allow cleanup even if they are nullified later const cleanupListeners = (listeners?: { onStdoutData: ((data: Buffer) => void) | null; onStderrData: ((data: Buffer) => void) | null; }) => { if (launchTimeoutId) clearTimeout(launchTimeoutId); launchTimeoutId = null; - - // Use passed-in listeners if available, otherwise use current scope's const stdoutListener = listeners?.onStdoutData ?? onStdoutData; const stderrListener = listeners?.onStderrData ?? onStderrData; - if (this.bashProcess && !this.bashProcess.killed) { if (stdoutListener) this.bashProcess.stdout.removeListener('data', stdoutListener); if (stderrListener) this.bashProcess.stderr.removeListener('data', stderrListener); } - // Only nullify the *current command's* cleanup reference if it matches if (this.currentCommandCleanup === cleanupListeners) { this.currentCommandCleanup = null; } - // Nullify the listener references in the outer scope regardless onStdoutData = null; onStderrData = null; }; - // Store *this specific* cleanup function instance for the current command this.currentCommandCleanup = cleanupListeners; - - // --- Final Resolution / Polling Logic --- const cleanupAndResolve = async () => { - // Prevent double execution if cleanup was already called (e.g., by timeout) if ( !this.currentCommandCleanup || this.currentCommandCleanup !== cleanupListeners ) { - // Ensure temp files are cleaned if this command was superseded but might have created them if (isBackgroundTask && tempStdoutPath && tempStderrPath) { this.cleanupTempFiles(tempStdoutPath, tempStderrPath).catch( (err) => { @@ -698,16 +605,10 @@ Use this tool for running build steps (\`npm install\`, \`make\`), linters (\`es } return; } - - // Capture initial output *before* cleanup nullifies buffers indirectly const launchStdout = this.truncateOutput(stdoutBuffer); const launchStderr = this.truncateOutput(stderrBuffer); - - // Store listeners before calling cleanup const listenersToClean = { onStdoutData, onStderrData }; - cleanupListeners(listenersToClean); // Remove listeners and clear launch timeout NOW - - // --- Error check for missing exit code --- + cleanupListeners(listenersToClean); if (exitCode === null) { console.error( `CRITICAL: Command "${params.command}" (background: ${isBackgroundTask}) finished delimiter processing but exitCode is null.`, @@ -719,18 +620,14 @@ Use this tool for running build steps (\`npm install\`, \`make\`), linters (\`es await this.cleanupTempFiles(tempStdoutPath, tempStderrPath); } originalResolve({ - // Use originalResolve as this is a failure *before* polling starts llmContent: `Command: ${params.command}\nExecuted in: ${this.currentCwd}\nMode: ${errorMode}\nExit Code: -2 (Internal Error: Exit code not captured)\nStdout (during setup):\n${launchStdout}\nStderr (during setup):\n${launchStderr}`, returnDisplay: `Internal Error: Failed to capture command exit code.\n${launchStdout}\nStderr: ${launchStderr}`.trim(), }); return; } - - // --- CWD Update Logic (Only for Foreground Success or 'cd') --- let cwdUpdateError = ''; if (!isBackgroundTask) { - // Only run for foreground const mightChangeCwd = params.command.trim().startsWith('cd '); if (exitCode === 0 || mightChangeCwd) { try { @@ -740,7 +637,6 @@ Use this tool for running build steps (\`npm install\`, \`make\`), linters (\`es } } catch (e: unknown) { if (exitCode === 0) { - // Only warn if the command itself succeeded cwdUpdateError = `\nWarning: Failed to verify/update current working directory after command: ${getErrorMessage(e)}`; console.error( 'Failed to update CWD after successful command:', @@ -750,37 +646,27 @@ Use this tool for running build steps (\`npm install\`, \`make\`), linters (\`es } } } - // --- End CWD Update --- - - // --- Result Formatting & Polling Decision --- if (isBackgroundTask) { const launchSuccess = exitCode === 0; const pidString = backgroundPid !== null ? backgroundPid.toString() : 'Not Captured'; - - // Check if polling should start if ( launchSuccess && backgroundPid !== null && tempStdoutPath && tempStderrPath ) { - // --- START POLLING --- - // Don't await this, let it run in the background and resolve the original promise later this.inspectBackgroundProcess( backgroundPid, params.command, - this.currentCwd, // CWD at time of launch - launchStdout, // Initial output captured during launch - launchStderr, // Initial output captured during launch - tempStdoutPath, // Path for final stdout - tempStderrPath, // Path for final stderr - originalResolve, // The resolve function of the main promise + this.currentCwd, + launchStdout, + launchStderr, + tempStdoutPath, + tempStderrPath, + originalResolve, ); - // IMPORTANT: Do NOT resolve the promise here. pollBackgroundProcess will do it. - // --- END POLLING --- } else { - // Background launch failed OR PID was not captured OR temp files missing const reason = backgroundPid === null ? 'PID not captured' @@ -788,50 +674,39 @@ Use this tool for running build steps (\`npm install\`, \`make\`), linters (\`es const displayMessage = `Failed to launch process in background (${reason})`; console.error( `Background launch failed for command: ${params.command}. Reason: ${reason}`, - ); // ERROR LOG - // Ensure cleanup of temp files if launch failed + ); if (tempStdoutPath && tempStderrPath) { await this.cleanupTempFiles(tempStdoutPath, tempStderrPath); } originalResolve({ - // Use originalResolve as polling won't start llmContent: `Background Command Launch Failed: ${params.command}\nExecuted in: ${this.currentCwd}\nReason: ${reason}\nPID: ${pidString}\nExit Code (Launch): ${exitCode}\nStdout (During Launch):\n${launchStdout}\nStderr (During Launch):\n${launchStderr}`, returnDisplay: displayMessage, }); } } else { - // --- Foreground task result (resolve immediately) --- let displayOutput = ''; const stdoutTrimmed = launchStdout.trim(); const stderrTrimmed = launchStderr.trim(); - if (stderrTrimmed) { displayOutput = stderrTrimmed; } else if (stdoutTrimmed) { displayOutput = stdoutTrimmed; } - if (exitCode !== 0 && !displayOutput) { displayOutput = `Failed with exit code: ${exitCode}`; } else if (exitCode === 0 && !displayOutput) { displayOutput = `Success (no output)`; } - originalResolve({ - // Use originalResolve for foreground result llmContent: `Command: ${params.command}\nExecuted in: ${this.currentCwd}\nExit Code: ${exitCode}\nStdout:\n${launchStdout}\nStderr:\n${launchStderr}${cwdUpdateError}`, - returnDisplay: displayOutput.trim() || `Exit Code: ${exitCode}`, // Ensure some display + returnDisplay: displayOutput.trim() || `Exit Code: ${exitCode}`, }); - // --- End Foreground Result --- } - }; // End of cleanupAndResolve - - // --- Attach listeners --- + }; if (!this.bashProcess || this.bashProcess.killed) { console.error( 'Bash process lost or killed before listeners could be attached.', ); - // Ensure temp files are cleaned up if they exist if (isBackgroundTask && tempStdoutPath && tempStderrPath) { this.cleanupTempFiles(tempStdoutPath, tempStderrPath).catch((err) => { console.warn( @@ -845,34 +720,20 @@ Use this tool for running build steps (\`npm install\`, \`make\`), linters (\`es ), ); } - // Defensive remove shouldn't be strictly necessary with current cleanup logic, but harmless - // if (onStdoutData) this.bashProcess.stdout.removeListener('data', onStdoutData); - // if (onStderrData) this.bashProcess.stderr.removeListener('data', onStderrData); - - // Attach the fresh listeners if (onStdoutData) this.bashProcess.stdout.on('data', onStdoutData); if (onStderrData) this.bashProcess.stderr.on('data', onStderrData); - - // --- Construct and Write Command --- let commandToWrite: string; if (isBackgroundTask && tempStdoutPath && tempStderrPath) { - // Background: Redirect command's stdout/stderr to temp files. - // Use subshell { ... } > file 2> file to redirect the command inside. - // Capture PID of the subshell. Capture exit code of the subshell launch. - // Ensure the subshell itself doesn't interfere with delimiter capture on stderr. commandToWrite = `echo "${startDelimiter}"; { { ${params.command} > "${tempStdoutPath}" 2> "${tempStderrPath}"; } & } 2>/dev/null; __LAST_PID=$!; echo "${pidDelimiter}$__LAST_PID" >&2; echo "${exitCodeDelimiter}$?" >&2; echo "${endDelimiter}$?" >&1\n`; } else if (!isBackgroundTask) { - // Foreground: Original structure. Capture command exit code. commandToWrite = `echo "${startDelimiter}"; ${params.command}; __EXIT_CODE=$?; echo "${exitCodeDelimiter}$__EXIT_CODE" >&2; echo "${endDelimiter}$__EXIT_CODE" >&1\n`; } else { - // Should not happen if background task setup failed, but handle defensively return originalReject( new Error( 'Internal setup error: Missing temporary file paths for background execution.', ), ); } - try { if (this.bashProcess?.stdin?.writable) { this.bashProcess.stdin.write(commandToWrite, (err) => { @@ -881,12 +742,8 @@ Use this tool for running build steps (\`npm install\`, \`make\`), linters (\`es `Error writing command "${params.command}" to bash stdin (callback):`, err, ); - // Store listeners before calling cleanup - const listenersToClean = { - onStdoutData, - onStderrData, - }; - cleanupListeners(listenersToClean); // Attempt cleanup + const listenersToClean = { onStdoutData, onStderrData }; + cleanupListeners(listenersToClean); if (isBackgroundTask && tempStdoutPath && tempStderrPath) { this.cleanupTempFiles(tempStdoutPath, tempStderrPath).catch( (e) => console.warn(`Cleanup failed: ${e.message}`), @@ -909,9 +766,8 @@ Use this tool for running build steps (\`npm install\`, \`make\`), linters (\`es `Error writing command "${params.command}" to bash stdin (sync):`, e, ); - // Store listeners before calling cleanup const listenersToClean = { onStdoutData, onStderrData }; - cleanupListeners(listenersToClean); // Attempt cleanup + cleanupListeners(listenersToClean); if (isBackgroundTask && tempStdoutPath && tempStderrPath) { this.cleanupTempFiles(tempStdoutPath, tempStderrPath).catch((err) => console.warn(`Cleanup failed: ${err.message}`), @@ -923,29 +779,24 @@ Use this tool for running build steps (\`npm install\`, \`make\`), linters (\`es ), ); } - }); // End of main promise constructor + }); + return promise; + } - return promise; // Return the promise created at the top - } // End of executeCommandInShell - - // --- **** NEW: Background Process Polling **** --- private async inspectBackgroundProcess( pid: number, command: string, cwd: string, - initialStdout: string, // Stdout during launch phase - initialStderr: string, // Stderr during launch phase - tempStdoutPath: string, // Path to redirected stdout - tempStderrPath: string, // Path to redirected stderr - resolve: (value: ToolResult | PromiseLike) => void, // The original promise's resolve + initialStdout: string, + initialStderr: string, + tempStdoutPath: string, + tempStderrPath: string, + resolve: (value: ToolResult | PromiseLike) => void, ): Promise { - // This function manages its own lifecycle but resolves the outer promise let finalStdout = ''; let finalStderr = ''; let llmAnalysis = ''; let fileReadError = ''; - - // --- Call LLM Analysis --- try { const { status, summary } = await this.backgroundTerminalAnalyzer.analyze( pid, @@ -960,10 +811,8 @@ Use this tool for running build steps (\`npm install\`, \`make\`), linters (\`es `LLM analysis failed for PID ${pid} command "${command}":`, llmerror, ); - llmAnalysis = `LLM analysis failed: ${getErrorMessage(llmerror)}`; // Include error in analysis placeholder + llmAnalysis = `LLM analysis failed: ${getErrorMessage(llmerror)}`; } - // --- End LLM Call --- - try { finalStdout = await fs.readFile(tempStdoutPath, 'utf-8'); finalStderr = await fs.readFile(tempStderrPath, 'utf-8'); @@ -971,22 +820,15 @@ Use this tool for running build steps (\`npm install\`, \`make\`), linters (\`es console.error(`Error reading temp output files for PID ${pid}:`, err); fileReadError = `\nWarning: Failed to read temporary output files (${getErrorMessage(err)}). Final output may be incomplete.`; } - - // --- Clean up temp files --- await this.cleanupTempFiles(tempStdoutPath, tempStderrPath); - // --- End Cleanup --- - const truncatedFinalStdout = this.truncateOutput(finalStdout); const truncatedFinalStderr = this.truncateOutput(finalStderr); - - // Resolve the original promise passed into pollBackgroundProcess resolve({ llmContent: `Background Command: ${command}\nLaunched in: ${cwd}\nPID: ${pid}\n--- LLM Analysis ---\n${llmAnalysis}\n--- Final Stdout (from ${path.basename(tempStdoutPath)}) ---\n${truncatedFinalStdout}\n--- Final Stderr (from ${path.basename(tempStderrPath)}) ---\n${truncatedFinalStderr}\n--- Launch Stdout ---\n${initialStdout}\n--- Launch Stderr ---\n${initialStderr}${fileReadError}`, returnDisplay: `(PID: ${pid}): ${this.truncateOutput(llmAnalysis, 200)}`, }); - } // End of pollBackgroundProcess + } - // --- **** NEW: Helper to cleanup temp files **** --- private async cleanupTempFiles( stdoutPath: string | null, stderrPath: string | null, @@ -996,7 +838,6 @@ Use this tool for running build steps (\`npm install\`, \`make\`), linters (\`es try { await fs.unlink(filePath); } catch (err: unknown) { - // Ignore errors like file not found (it might have been deleted already or failed to create) if (!isNodeError(err) || err.code !== 'ENOENT') { console.warn( `Failed to delete temporary file '${filePath}': ${getErrorMessage(err)}`, @@ -1004,11 +845,9 @@ Use this tool for running build steps (\`npm install\`, \`make\`), linters (\`es } } }; - // Run deletions concurrently and wait for both await Promise.all([unlinkQuietly(stdoutPath), unlinkQuietly(stderrPath)]); } - // --- Get CWD (mostly unchanged, added robustness) --- private getCurrentShellCwd(): Promise { return new Promise((resolve, reject) => { if ( @@ -1022,57 +861,48 @@ Use this tool for running build steps (\`npm install\`, \`make\`), linters (\`es ), ); } - const pwdUuid = crypto.randomUUID(); const pwdDelimiter = `::PWD_${pwdUuid}::`; let pwdOutput = ''; let onPwdData: ((data: Buffer) => void) | null = null; - let onPwdError: ((data: Buffer) => void) | null = null; // To catch errors during pwd + let onPwdError: ((data: Buffer) => void) | null = null; let pwdTimeoutId: NodeJS.Timeout | null = null; - let finished = false; // Prevent double resolution/rejection - + let finished = false; const cleanupPwdListeners = (err?: Error) => { - if (finished) return; // Already handled + if (finished) return; finished = true; if (pwdTimeoutId) clearTimeout(pwdTimeoutId); pwdTimeoutId = null; - - const stdoutListener = onPwdData; // Capture current reference - const stderrListener = onPwdError; // Capture current reference - onPwdData = null; // Nullify before removing + const stdoutListener = onPwdData; + const stderrListener = onPwdError; + onPwdData = null; onPwdError = null; - if (this.bashProcess && !this.bashProcess.killed) { if (stdoutListener) this.bashProcess.stdout.removeListener('data', stdoutListener); if (stderrListener) this.bashProcess.stderr.removeListener('data', stderrListener); } - if (err) { reject(err); } else { - // Trim whitespace and trailing newlines robustly resolve(pwdOutput.trim()); } }; - onPwdData = (data: Buffer) => { - if (!onPwdData) return; // Listener removed + if (!onPwdData) return; const dataStr = data.toString(); const delimiterIndex = dataStr.indexOf(pwdDelimiter); if (delimiterIndex !== -1) { pwdOutput += dataStr.substring(0, delimiterIndex); - cleanupPwdListeners(); // Resolve successfully + cleanupPwdListeners(); } else { pwdOutput += dataStr; } }; - onPwdError = (data: Buffer) => { - if (!onPwdError) return; // Listener removed + if (!onPwdError) return; const dataStr = data.toString(); - // If delimiter appears on stderr, or any stderr occurs, treat as error console.error(`Error during PWD check: ${dataStr}`); cleanupPwdListeners( new Error( @@ -1080,24 +910,16 @@ Use this tool for running build steps (\`npm install\`, \`make\`), linters (\`es ), ); }; - - // Attach listeners this.bashProcess.stdout.on('data', onPwdData); this.bashProcess.stderr.on('data', onPwdError); - - // Set timeout pwdTimeoutId = setTimeout(() => { cleanupPwdListeners(new Error('Timeout waiting for pwd response')); - }, 5000); // 5 second timeout for pwd - - // Write command + }, 5000); try { - // Use printf for robustness against special characters in PWD and ensure newline const pwdCommand = `printf "%s" "$PWD"; printf "${pwdDelimiter}";\n`; if (this.bashProcess?.stdin?.writable) { this.bashProcess.stdin.write(pwdCommand, (err) => { if (err) { - // Error during write callback, likely means shell is unresponsive console.error('Error writing pwd command (callback):', err); cleanupPwdListeners( new Error(`Failed to write pwd command: ${err.message}`), @@ -1116,7 +938,6 @@ Use this tool for running build steps (\`npm install\`, \`make\`), linters (\`es }); } - // --- Truncate Output (unchanged) --- private truncateOutput(output: string, limit?: number): string { const effectiveLimit = limit ?? this.outputLimit; if (output.length > effectiveLimit) { @@ -1128,7 +949,6 @@ Use this tool for running build steps (\`npm install\`, \`make\`), linters (\`es return output; } - // --- Clear Queue (unchanged) --- private clearQueue(error: Error) { const queue = this.commandQueue; this.commandQueue = []; @@ -1140,56 +960,39 @@ Use this tool for running build steps (\`npm install\`, \`make\`), linters (\`es ); } - // --- Destroy (Added cleanup for pending background tasks if possible) --- destroy() { - // Reject any pending shell readiness promise this.rejectShellReady?.( new Error('BashTool destroyed during initialization or operation.'), ); - this.rejectShellReady = undefined; // Prevent further calls + this.rejectShellReady = undefined; this.resolveShellReady = undefined; - this.clearQueue(new Error('BashTool is being destroyed.')); - - // Attempt to cleanup listeners for the *currently executing* command, if any try { this.currentCommandCleanup?.(); } catch (e) { console.warn('Error during current command cleanup:', e); } - - // Handle the bash process itself if (this.bashProcess) { - const proc = this.bashProcess; // Reference before nullifying + const proc = this.bashProcess; const pid = proc.pid; - this.bashProcess = null; // Nullify reference immediately - + this.bashProcess = null; proc.stdout?.removeAllListeners(); proc.stderr?.removeAllListeners(); proc.removeAllListeners('error'); proc.removeAllListeners('close'); - - // Ensure stdin is closed proc.stdin?.end(); - try { - // Don't wait for these, just attempt - proc.kill('SIGTERM'); // Attempt graceful first + proc.kill('SIGTERM'); setTimeout(() => { if (!proc.killed) { - proc.kill('SIGKILL'); // Force kill if needed + proc.kill('SIGKILL'); } - }, 500); // 500ms grace period + }, 500); } catch (e: unknown) { - // Catch errors if process already exited etc. console.warn( `Error trying to kill bash process PID: ${pid}: ${getErrorMessage(e)}`, ); } } - - // Note: We cannot reliably clean up temp files for background tasks - // that were polling when destroy() was called without more complex state tracking. - // OS should eventually clean /tmp, or implement a startup cleanup routine if needed. } -} // End of TerminalTool class +} diff --git a/packages/cli/src/tools/tool-registry.ts b/packages/cli/src/tools/tool-registry.ts index a2723557..1c82aa12 100644 --- a/packages/cli/src/tools/tool-registry.ts +++ b/packages/cli/src/tools/tool-registry.ts @@ -25,27 +25,37 @@ class ToolRegistry { } /** - * Retrieves the list of tool schemas in the format required by Gemini. - * @returns A ToolListUnion containing the function declarations. + * Retrieves the list of tool schemas (FunctionDeclaration array). + * Extracts the declarations from the ToolListUnion structure. + * @returns An array of FunctionDeclarations. */ - getToolSchemas(): ToolListUnion { + getFunctionDeclarations(): FunctionDeclaration[] { const declarations: FunctionDeclaration[] = []; this.tools.forEach((tool) => { declarations.push(tool.schema); }); + return declarations; + } - // Return Gemini's expected format. Handle the case of no tools. + /** + * Deprecated/Internal? Retrieves schemas in the ToolListUnion format. + * Kept for reference, prefer getFunctionDeclarations. + */ + getToolSchemas(): ToolListUnion { + const declarations = this.getFunctionDeclarations(); if (declarations.length === 0) { - // Depending on the SDK version, you might need `undefined`, `[]`, or `[{ functionDeclarations: [] }]` - // Check the documentation for your @google/genai version. - // Let's assume an empty array works or signifies no tools. return []; - // Or if it requires the structure: - // return [{ functionDeclarations: [] }]; } return [{ functionDeclarations: declarations }]; } + /** + * Returns an array of all registered tool instances. + */ + getAllTools(): Tool[] { + return Array.from(this.tools.values()); + } + /** * Optional: Get a list of registered tool names. */ diff --git a/packages/cli/src/tools/web-fetch.tool.ts b/packages/cli/src/tools/web-fetch.tool.ts index cd5e01e8..b543dd90 100644 --- a/packages/cli/src/tools/web-fetch.tool.ts +++ b/packages/cli/src/tools/web-fetch.tool.ts @@ -4,169 +4,61 @@ * SPDX-License-Identifier: Apache-2.0 */ -import { SchemaValidator } from '../utils/schemaValidator.js'; -import { BaseTool, ToolResult } from './tools.js'; -import { ToolCallConfirmationDetails } from '../ui/types.js'; // Added for shouldConfirmExecute -import { getErrorMessage } from '../utils/errors.js'; +// Import core logic and types from the server package +import { + WebFetchLogic, + WebFetchToolParams, + ToolResult, +} from '@gemini-code/server'; + +// Import CLI-specific base class and UI types +import { BaseTool } from './tools.js'; +import { ToolCallConfirmationDetails } from '../ui/types.js'; /** - * Parameters for the WebFetch tool - */ -export interface WebFetchToolParams { - /** - * The URL to fetch content from. - */ - url: string; -} - -/** - * Implementation of the WebFetch tool that reads content from a URL. + * CLI wrapper for the WebFetch tool. */ export class WebFetchTool extends BaseTool { - static readonly Name: string = 'web_fetch'; + static readonly Name: string = WebFetchLogic.Name; // Use name from logic + + // Core logic instance from the server package + private coreLogic: WebFetchLogic; - /** - * Creates a new instance of the WebFetchTool - */ constructor() { + const coreLogicInstance = new WebFetchLogic(); super( WebFetchTool.Name, - 'WebFetch', - 'Fetches text content from a given URL. Handles potential network errors and non-success HTTP status codes.', - { - properties: { - url: { - description: - "The URL to fetch. Must be an absolute URL (e.g., 'https://example.com/file.txt').", - type: 'string', - }, - }, - required: ['url'], - type: 'object', - }, + 'WebFetch', // Define display name here + 'Fetches text content from a given URL. Handles potential network errors and non-success HTTP status codes.', // Define description here + (coreLogicInstance.schema.parameters as Record) ?? {}, ); - // No rootDirectory needed for web fetching + this.coreLogic = coreLogicInstance; } - /** - * Validates the parameters for the WebFetch tool - * @param params Parameters to validate - * @returns An error message string if invalid, null otherwise - */ - invalidParams(params: WebFetchToolParams): string | null { - // 1. Validate against the basic schema first - if ( - this.schema.parameters && - !SchemaValidator.validate( - this.schema.parameters as Record, - params, - ) - ) { - return 'Parameters failed schema validation.'; - } - - // 2. Validate the URL format and protocol - try { - const parsedUrl = new URL(params.url); - // Ensure it's an HTTP or HTTPS URL - if (!['http:', 'https:'].includes(parsedUrl.protocol)) { - return `Invalid URL protocol: "${parsedUrl.protocol}". Only 'http:' and 'https:' are supported.`; - } - } catch { - // The URL constructor throws if the format is invalid - return `Invalid URL format: "${params.url}". Please provide a valid absolute URL (e.g., 'https://example.com').`; - } - - // If all checks pass, the parameters are valid - return null; + validateToolParams(params: WebFetchToolParams): string | null { + // Delegate validation to core logic + return this.coreLogic.validateParams(params); } - /** - * Gets a description of the web fetch operation. - * @param params Parameters for the web fetch. - * @returns A string describing the operation. - */ getDescription(params: WebFetchToolParams): string { - // Shorten long URLs for display - const displayUrl = - params.url.length > 80 ? params.url.substring(0, 77) + '...' : params.url; - return `Fetching content from ${displayUrl}`; + // Delegate description generation to core logic + return this.coreLogic.getDescription(params); } /** - * Determines if the tool should prompt for confirmation before execution. - * Web fetches are generally safe, so default to false. - * @param params Parameters for the tool execution - * @returns Whether execute should be confirmed. + * Define confirmation behavior (WebFetch likely doesn't need confirmation) */ async shouldConfirmExecute( // eslint-disable-next-line @typescript-eslint/no-unused-vars params: WebFetchToolParams, ): Promise { - // Could add logic here to confirm based on domain, etc. if needed return Promise.resolve(false); } /** - * Fetches content from the specified URL. - * @param params Parameters for the web fetch operation. - * @returns Result with the fetched content or an error message. + * Delegates execution to the core logic. */ async execute(params: WebFetchToolParams): Promise { - const validationError = this.invalidParams(params); - if (validationError) { - return { - llmContent: `Error: Invalid parameters provided. Reason: ${validationError}`, - returnDisplay: `**Error:** Invalid parameters. ${validationError}`, - }; - } - - const url = params.url; - - try { - const response = await fetch(url, { - headers: { - 'User-Agent': 'GeminiCode-CLI/1.0', - }, - signal: AbortSignal.timeout(15000), // 15 seconds timeout - }); - - if (!response.ok) { - // fetch doesn't throw on bad HTTP status codes (4xx, 5xx) - const errorText = `Failed to fetch data from ${url}. Status: ${response.status} ${response.statusText}`; - return { - llmContent: `Error: ${errorText}`, - returnDisplay: `**Error:** ${errorText}`, - }; - } - - // Assuming the response is text. Add checks for content-type if needed. - const data = await response.text(); - let llmContent = ''; - // Truncate very large responses for the LLM context - const MAX_LLM_CONTENT_LENGTH = 200000; - if (data) { - llmContent = `Fetched data from ${url}:\n\n${ - data.length > MAX_LLM_CONTENT_LENGTH - ? data.substring(0, MAX_LLM_CONTENT_LENGTH) + - '\n... [Content truncated]' - : data - }`; - } else { - llmContent = `No data fetched from ${url}. Status: ${response.status}`; - } - return { - llmContent, - returnDisplay: `Fetched content from ${url}`, // Simple display message - }; - } catch (error: unknown) { - // This catches network errors (DNS resolution, connection refused, etc.) - // and errors from the URL constructor if somehow bypassed validation (unlikely) - const errorMessage = `Failed to fetch data from ${url}. Error: ${getErrorMessage(error)}`; - return { - llmContent: `Error: ${errorMessage}`, - returnDisplay: `**Error:** ${errorMessage}`, - }; - } + return this.coreLogic.execute(params); } } diff --git a/packages/cli/src/tools/write-file.tool.ts b/packages/cli/src/tools/write-file.tool.ts index c4649a1f..a55be8a0 100644 --- a/packages/cli/src/tools/write-file.tool.ts +++ b/packages/cli/src/tools/write-file.tool.ts @@ -6,127 +6,51 @@ import fs from 'fs'; import path from 'path'; -import { BaseTool, ToolResult } from './tools.js'; -import { SchemaValidator } from '../utils/schemaValidator.js'; -import { makeRelative, shortenPath } from '../utils/paths.js'; +import * as Diff from 'diff'; +import { + WriteFileLogic, + WriteFileToolParams, + ToolResult, + makeRelative, + shortenPath, +} from '@gemini-code/server'; +import { BaseTool } from './tools.js'; import { ToolCallConfirmationDetails, ToolConfirmationOutcome, ToolEditConfirmationDetails, } from '../ui/types.js'; -import * as Diff from 'diff'; /** - * Parameters for the WriteFile tool - */ -export interface WriteFileToolParams { - /** - * The absolute path to the file to write to - */ - file_path: string; - - /** - * The content to write to the file - */ - content: string; -} - -/** - * Implementation of the WriteFile tool that writes files to the filesystem + * CLI wrapper for the WriteFile tool. */ export class WriteFileTool extends BaseTool { - static readonly Name: string = 'write_file'; + static readonly Name: string = WriteFileLogic.Name; private shouldAlwaysWrite = false; - /** - * The root directory that this tool is grounded in. - * All file operations will be restricted to this directory. - */ - private rootDirectory: string; + private coreLogic: WriteFileLogic; - /** - * Creates a new instance of the WriteFileTool - * @param rootDirectory Root directory to ground this tool in. All operations will be restricted to this directory. - */ constructor(rootDirectory: string) { + const coreLogicInstance = new WriteFileLogic(rootDirectory); super( WriteFileTool.Name, 'WriteFile', 'Writes content to a specified file in the local filesystem.', - { - properties: { - filePath: { - description: - "The absolute path to the file to write to (e.g., '/home/user/project/file.txt'). Relative paths are not supported.", - type: 'string', - }, - content: { - description: 'The content to write to the file.', - type: 'string', - }, - }, - required: ['filePath', 'content'], - type: 'object', - }, + (coreLogicInstance.schema.parameters as Record) ?? {}, ); - - // Set the root directory - this.rootDirectory = path.resolve(rootDirectory); + this.coreLogic = coreLogicInstance; } - /** - * Checks if a path is within the root directory - * @param pathToCheck The path to check - * @returns True if the path is within the root directory, false otherwise - */ - private isWithinRoot(pathToCheck: string): boolean { - const normalizedPath = path.normalize(pathToCheck); - const normalizedRoot = path.normalize(this.rootDirectory); - - // Ensure the normalizedRoot ends with a path separator for proper path comparison - const rootWithSep = normalizedRoot.endsWith(path.sep) - ? normalizedRoot - : normalizedRoot + path.sep; - - return ( - normalizedPath === normalizedRoot || - normalizedPath.startsWith(rootWithSep) - ); - } - - /** - * Validates the parameters for the WriteFile tool - * @param params Parameters to validate - * @returns True if parameters are valid, false otherwise - */ validateToolParams(params: WriteFileToolParams): string | null { - if ( - this.schema.parameters && - !SchemaValidator.validate( - this.schema.parameters as Record, - params, - ) - ) { - return 'Parameters failed schema validation.'; - } + return this.coreLogic.validateParams(params); + } - // Ensure path is absolute - if (!path.isAbsolute(params.file_path)) { - return `File path must be absolute: ${params.file_path}`; - } - - // Ensure path is within the root directory - if (!this.isWithinRoot(params.file_path)) { - return `File path must be within the root directory (${this.rootDirectory}): ${params.file_path}`; - } - - return null; + getDescription(params: WriteFileToolParams): string { + return this.coreLogic.getDescription(params); } /** - * Determines if the tool should prompt for confirmation before execution - * @param params Parameters for the tool execution - * @returns Whether or not execute should be confirmed by the user. + * Handles the confirmation prompt for the WriteFile tool in the CLI. */ async shouldConfirmExecute( params: WriteFileToolParams, @@ -135,14 +59,25 @@ export class WriteFileTool extends BaseTool { return false; } - const relativePath = makeRelative(params.file_path, this.rootDirectory); + const validationError = this.validateToolParams(params); + if (validationError) { + console.error( + `[WriteFile Wrapper] Attempted confirmation with invalid parameters: ${validationError}`, + ); + return false; + } + + const relativePath = makeRelative( + params.file_path, + this.coreLogic['rootDirectory'], + ); const fileName = path.basename(params.file_path); let currentContent = ''; try { currentContent = fs.readFileSync(params.file_path, 'utf8'); } catch { - // File may not exist, which is fine + // File might not exist, that's okay for write/create } const fileDiff = Diff.createPatch( @@ -151,7 +86,7 @@ export class WriteFileTool extends BaseTool { params.content, 'Current', 'Proposed', - { context: 3, ignoreWhitespace: true }, + { context: 3 }, ); const confirmationDetails: ToolEditConfirmationDetails = { @@ -168,49 +103,9 @@ export class WriteFileTool extends BaseTool { } /** - * Gets a description of the file writing operation - * @param params Parameters for the file writing - * @returns A string describing the file being written to - */ - getDescription(params: WriteFileToolParams): string { - const relativePath = makeRelative(params.file_path, this.rootDirectory); - return `Writing to ${shortenPath(relativePath)}`; - } - - /** - * Executes the file writing operation - * @param params Parameters for the file writing - * @returns Result of the file writing operation + * Delegates execution to the core logic. */ async execute(params: WriteFileToolParams): Promise { - const validationError = this.validateToolParams(params); - if (validationError) { - return { - llmContent: `Error: Invalid parameters provided. Reason: ${validationError}`, - returnDisplay: '**Error:** Failed to execute tool.', - }; - } - - try { - // Ensure parent directories exist - const dirName = path.dirname(params.file_path); - if (!fs.existsSync(dirName)) { - fs.mkdirSync(dirName, { recursive: true }); - } - - // Write the file - fs.writeFileSync(params.file_path, params.content, 'utf8'); - - return { - llmContent: `Successfully wrote to file: ${params.file_path}`, - returnDisplay: `Wrote to ${shortenPath(makeRelative(params.file_path, this.rootDirectory))}`, - }; - } catch (error) { - const errorMsg = `Error writing to file: ${error instanceof Error ? error.message : String(error)}`; - return { - llmContent: `Error writing to file ${params.file_path}: ${errorMsg}`, - returnDisplay: `Failed to write to file: ${errorMsg}`, - }; - } + return this.coreLogic.execute(params); } } diff --git a/packages/cli/src/ui/App.tsx b/packages/cli/src/ui/App.tsx index e1b45af9..fa9b6f9b 100644 --- a/packages/cli/src/ui/App.tsx +++ b/packages/cli/src/ui/App.tsx @@ -22,16 +22,20 @@ import { useStartupWarnings, useInitializationErrorEffect, } from './hooks/useAppEffects.js'; +import type { Config } from '@gemini-code/server'; interface AppProps { - directory: string; + config: Config; } -export const App = ({ directory }: AppProps) => { +export const App = ({ config }: AppProps) => { const [history, setHistory] = useState([]); const [startupWarnings, setStartupWarnings] = useState([]); - const { streamingState, submitQuery, initError } = - useGeminiStream(setHistory); + const { streamingState, submitQuery, initError } = useGeminiStream( + setHistory, + config.getApiKey(), + config.getModel(), + ); const { elapsedTime, currentLoadingPhrase } = useLoadingIndicator(streamingState); @@ -61,12 +65,7 @@ export const App = ({ directory }: AppProps) => { !initError && !isWaitingForToolConfirmation; - const { - query, - setQuery, - handleSubmit: handleHistorySubmit, - inputKey, - } = useInputHistory({ + const { query, handleSubmit: handleHistorySubmit } = useInputHistory({ userMessages, onSubmit: submitQuery, isActive: isInputActive, @@ -74,7 +73,7 @@ export const App = ({ directory }: AppProps) => { return ( -
+
{startupWarnings.length > 0 && ( { /> - {isInputActive && ( - - )} + {isInputActive && }