From add233c5043264d47ecc6d3339a383f41a241ae8 Mon Sep 17 00:00:00 2001 From: Taylor Mullen Date: Tue, 15 Apr 2025 21:41:08 -0700 Subject: [PATCH] Initial commit of Gemini Code CLI This commit introduces the initial codebase for the Gemini Code CLI, a command-line interface designed to facilitate interaction with the Gemini API for software engineering tasks. The code was migrated from a previous git repository as a single squashed commit. Core Features & Components: * **Gemini Integration:** Leverages the `@google/genai` SDK to interact with the Gemini models, supporting chat history, streaming responses, and function calling (tools). * **Terminal UI:** Built with Ink (React for CLIs) providing an interactive chat interface within the terminal, including input prompts, message display, loading indicators, and tool interaction elements. * **Tooling Framework:** Implements a robust tool system allowing Gemini to interact with the local environment. Includes tools for: * File system listing (`ls`) * File reading (`read-file`) * Content searching (`grep`) * File globbing (`glob`) * File editing (`edit`) * File writing (`write-file`) * Executing bash commands (`terminal`) * **State Management:** Handles the streaming state of Gemini responses and manages the conversation history. * **Configuration:** Parses command-line arguments (`yargs`) and loads environment variables (`dotenv`) for setup. * **Project Structure:** Organized into `core`, `ui`, `tools`, `config`, and `utils` directories using TypeScript. Includes basic build (`tsc`) and start scripts. This initial version establishes the foundation for a powerful CLI tool enabling developers to use Gemini for coding assistance directly in their terminal environment. --- Created by yours truly: __Gemini Code__ --- .gitignore | 17 + .vscode/launch.json | 29 + README.md | 3 + package-lock.json | 1669 +++++++++++++++++ package.json | 13 + packages/cli/package.json | 38 + packages/cli/src/config/args.ts | 34 + packages/cli/src/config/env.ts | 46 + packages/cli/src/core/GeminiClient.ts | 383 ++++ packages/cli/src/core/GeminiStream.ts | 22 + packages/cli/src/core/StreamingState.ts | 4 + packages/cli/src/core/agent.ts | 0 packages/cli/src/core/constants.ts | 1 + .../cli/src/core/geminiStreamProcessor.ts | 142 ++ packages/cli/src/core/historyUpdater.ts | 173 ++ packages/cli/src/core/prompts.ts | 93 + packages/cli/src/gemini.ts | 57 + packages/cli/src/tools/BaseTool.ts | 73 + packages/cli/src/tools/Tool.ts | 57 + packages/cli/src/tools/ToolResult.ts | 22 + packages/cli/src/tools/edit.tool.ts | 369 ++++ packages/cli/src/tools/glob.tool.ts | 227 +++ packages/cli/src/tools/grep.tool.ts | 493 +++++ packages/cli/src/tools/ls.tool.ts | 306 +++ packages/cli/src/tools/read-file.tool.ts | 296 +++ packages/cli/src/tools/terminal.tool.ts | 960 ++++++++++ packages/cli/src/tools/tool-registry.ts | 58 + packages/cli/src/tools/write-file.tool.ts | 201 ++ packages/cli/src/ui/App.tsx | 90 + packages/cli/src/ui/components/Footer.tsx | 21 + packages/cli/src/ui/components/Header.tsx | 38 + .../cli/src/ui/components/HistoryDisplay.tsx | 39 + .../cli/src/ui/components/InputPrompt.tsx | 39 + .../src/ui/components/LoadingIndicator.tsx | 32 + packages/cli/src/ui/components/Tips.tsx | 17 + .../ui/components/messages/DiffRenderer.tsx | 152 ++ .../ui/components/messages/ErrorMessage.tsx | 24 + .../ui/components/messages/GeminiMessage.tsx | 44 + .../ui/components/messages/InfoMessage.tsx | 24 + .../messages/ToolConfirmationMessage.tsx | 101 + .../components/messages/ToolGroupMessage.tsx | 47 + .../ui/components/messages/ToolMessage.tsx | 53 + .../ui/components/messages/UserMessage.tsx | 24 + packages/cli/src/ui/constants.ts | 26 + packages/cli/src/ui/hooks/useGeminiStream.ts | 142 ++ .../cli/src/ui/hooks/useLoadingIndicator.ts | 53 + packages/cli/src/ui/types.ts | 62 + .../cli/src/ui/utils/MarkdownRenderer.tsx | 249 +++ .../src/utils/BackgroundTerminalAnalyzer.ts | 325 ++++ packages/cli/src/utils/getFolderStructure.ts | 349 ++++ packages/cli/src/utils/paths.ts | 102 + packages/cli/src/utils/schemaValidator.ts | 49 + packages/cli/tsconfig.json | 22 + tsconfig.json | 10 + 54 files changed, 7920 insertions(+) create mode 100644 .gitignore create mode 100644 .vscode/launch.json create mode 100644 README.md create mode 100644 package-lock.json create mode 100644 package.json create mode 100644 packages/cli/package.json create mode 100644 packages/cli/src/config/args.ts create mode 100644 packages/cli/src/config/env.ts create mode 100644 packages/cli/src/core/GeminiClient.ts create mode 100644 packages/cli/src/core/GeminiStream.ts create mode 100644 packages/cli/src/core/StreamingState.ts create mode 100644 packages/cli/src/core/agent.ts create mode 100644 packages/cli/src/core/constants.ts create mode 100644 packages/cli/src/core/geminiStreamProcessor.ts create mode 100644 packages/cli/src/core/historyUpdater.ts create mode 100644 packages/cli/src/core/prompts.ts create mode 100644 packages/cli/src/gemini.ts create mode 100644 packages/cli/src/tools/BaseTool.ts create mode 100644 packages/cli/src/tools/Tool.ts create mode 100644 packages/cli/src/tools/ToolResult.ts create mode 100644 packages/cli/src/tools/edit.tool.ts create mode 100644 packages/cli/src/tools/glob.tool.ts create mode 100644 packages/cli/src/tools/grep.tool.ts create mode 100644 packages/cli/src/tools/ls.tool.ts create mode 100644 packages/cli/src/tools/read-file.tool.ts create mode 100644 packages/cli/src/tools/terminal.tool.ts create mode 100644 packages/cli/src/tools/tool-registry.ts create mode 100644 packages/cli/src/tools/write-file.tool.ts create mode 100644 packages/cli/src/ui/App.tsx create mode 100644 packages/cli/src/ui/components/Footer.tsx create mode 100644 packages/cli/src/ui/components/Header.tsx create mode 100644 packages/cli/src/ui/components/HistoryDisplay.tsx create mode 100644 packages/cli/src/ui/components/InputPrompt.tsx create mode 100644 packages/cli/src/ui/components/LoadingIndicator.tsx create mode 100644 packages/cli/src/ui/components/Tips.tsx create mode 100644 packages/cli/src/ui/components/messages/DiffRenderer.tsx create mode 100644 packages/cli/src/ui/components/messages/ErrorMessage.tsx create mode 100644 packages/cli/src/ui/components/messages/GeminiMessage.tsx create mode 100644 packages/cli/src/ui/components/messages/InfoMessage.tsx create mode 100644 packages/cli/src/ui/components/messages/ToolConfirmationMessage.tsx create mode 100644 packages/cli/src/ui/components/messages/ToolGroupMessage.tsx create mode 100644 packages/cli/src/ui/components/messages/ToolMessage.tsx create mode 100644 packages/cli/src/ui/components/messages/UserMessage.tsx create mode 100644 packages/cli/src/ui/constants.ts create mode 100644 packages/cli/src/ui/hooks/useGeminiStream.ts create mode 100644 packages/cli/src/ui/hooks/useLoadingIndicator.ts create mode 100644 packages/cli/src/ui/types.ts create mode 100644 packages/cli/src/ui/utils/MarkdownRenderer.tsx create mode 100644 packages/cli/src/utils/BackgroundTerminalAnalyzer.ts create mode 100644 packages/cli/src/utils/getFolderStructure.ts create mode 100644 packages/cli/src/utils/paths.ts create mode 100644 packages/cli/src/utils/schemaValidator.ts create mode 100644 packages/cli/tsconfig.json create mode 100644 tsconfig.json diff --git a/.gitignore b/.gitignore new file mode 100644 index 00000000..febac64c --- /dev/null +++ b/.gitignore @@ -0,0 +1,17 @@ +# API keys and secrets +.env + +# Dependency directory +node_modules +bower_components + +# Editors +.idea +*.iml + +# OS metadata +.DS_Store +Thumbs.db + +# Ignore built ts files +dist \ No newline at end of file diff --git a/.vscode/launch.json b/.vscode/launch.json new file mode 100644 index 00000000..8a8daaf1 --- /dev/null +++ b/.vscode/launch.json @@ -0,0 +1,29 @@ +{ + // Use IntelliSense to learn about possible attributes. + // Hover to view descriptions of existing attributes. + // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 + "version": "0.2.0", + "configurations": [ + { + "name": "Attach", + "port": 9229, + "request": "attach", + "skipFiles": [ + "/**" + ], + "type": "node" + }, + { + "type": "node", + "request": "launch", + "name": "Launch Program", + "skipFiles": [ + "/**" + ], + "program": "${file}", + "outFiles": [ + "${workspaceFolder}/**/*.js" + ] + } + ] +} \ No newline at end of file diff --git a/README.md b/README.md new file mode 100644 index 00000000..ca33215e --- /dev/null +++ b/README.md @@ -0,0 +1,3 @@ +# Gemini Code + +TBD \ No newline at end of file diff --git a/package-lock.json b/package-lock.json new file mode 100644 index 00000000..e5789ca8 --- /dev/null +++ b/package-lock.json @@ -0,0 +1,1669 @@ +{ + "name": "gemini-code", + "version": "1.0.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "gemini-code", + "version": "1.0.0", + "workspaces": [ + "packages/*" + ] + }, + "node_modules/@alcalzone/ansi-tokenize": { + "version": "0.1.3", + "resolved": "https://registry.npmjs.org/@alcalzone/ansi-tokenize/-/ansi-tokenize-0.1.3.tgz", + "integrity": "sha512-3yWxPTq3UQ/FY9p1ErPxIyfT64elWaMvM9lIHnaqpyft63tkxodF5aUElYHrdisWve5cETkh1+KBw1yJuW0aRw==", + "license": "MIT", + "dependencies": { + "ansi-styles": "^6.2.1", + "is-fullwidth-code-point": "^4.0.0" + }, + "engines": { + "node": ">=14.13.1" + } + }, + "node_modules/@alcalzone/ansi-tokenize/node_modules/ansi-styles": { + "version": "6.2.1", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-6.2.1.tgz", + "integrity": "sha512-bN798gFfQX+viw3R7yrGWRqnrN2oRkEkUjjl4JNn4E8GxxbjtG3FbrEIIY3l8/hrwUwIeCZvi4QuOTP4MErVug==", + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/@alcalzone/ansi-tokenize/node_modules/is-fullwidth-code-point": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-4.0.0.tgz", + "integrity": "sha512-O4L094N2/dZ7xqVdrXhh9r1KODPJpFms8B5sGdJLPy664AgvXsreZUyCQQNItZRDlYug4xStLjNp/sz3HvBowQ==", + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/@google/genai": { + "version": "0.8.0", + "resolved": "https://registry.npmjs.org/@google/genai/-/genai-0.8.0.tgz", + "integrity": "sha512-Zs+OGyZKyMbFofGJTR9/jTQSv8kITh735N3tEuIZj4VlMQXTC0soCFahysJ9NaeenRlD7xGb6fyqmX+FwrpU6Q==", + "license": "Apache-2.0", + "dependencies": { + "google-auth-library": "^9.14.2", + "ws": "^8.18.0" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@nodelib/fs.scandir": { + "version": "2.1.5", + "resolved": "https://registry.npmjs.org/@nodelib/fs.scandir/-/fs.scandir-2.1.5.tgz", + "integrity": "sha512-vq24Bq3ym5HEQm2NKCr3yXDwjc7vTsEThRDnkp2DK9p1uqLR+DHurm/NOTo0KG7HYHU7eppKZj3MyqYuMBf62g==", + "license": "MIT", + "dependencies": { + "@nodelib/fs.stat": "2.0.5", + "run-parallel": "^1.1.9" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/@nodelib/fs.stat": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/@nodelib/fs.stat/-/fs.stat-2.0.5.tgz", + "integrity": "sha512-RkhPPp2zrqDAQA/2jNhnztcPAlv64XdhIp7a7454A5ovI7Bukxgt7MX7udwAu3zg1DcpPU0rz3VV1SeaqvY4+A==", + "license": "MIT", + "engines": { + "node": ">= 8" + } + }, + "node_modules/@nodelib/fs.walk": { + "version": "1.2.8", + "resolved": "https://registry.npmjs.org/@nodelib/fs.walk/-/fs.walk-1.2.8.tgz", + "integrity": "sha512-oGB+UxlgWcgQkgwo8GcEGwemoTFt3FIO9ababBmaGwXIoBKZ+GTy0pP185beGg7Llih/NSHSV2XAs1lnznocSg==", + "license": "MIT", + "dependencies": { + "@nodelib/fs.scandir": "2.1.5", + "fastq": "^1.6.0" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/@types/diff": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@types/diff/-/diff-7.0.2.tgz", + "integrity": "sha512-JSWRMozjFKsGlEjiiKajUjIJVKuKdE3oVy2DNtK+fUo8q82nhFZ2CPQwicAIkXrofahDXrWJ7mjelvZphMS98Q==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/dotenv": { + "version": "6.1.1", + "resolved": "https://registry.npmjs.org/@types/dotenv/-/dotenv-6.1.1.tgz", + "integrity": "sha512-ftQl3DtBvqHl9L16tpqqzA4YzCSXZfi7g8cQceTz5rOlYtk/IZbFjAv3mLOQlNIgOaylCQWQoBdDQHPgEBJPHg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/node": "*" + } + }, + "node_modules/@types/node": { + "version": "20.17.30", + "dev": true, + "license": "MIT", + "dependencies": { + "undici-types": "~6.19.2" + } + }, + "node_modules/@types/react": { + "version": "19.1.0", + "resolved": "https://registry.npmjs.org/@types/react/-/react-19.1.0.tgz", + "integrity": "sha512-UaicktuQI+9UKyA4njtDOGBD/67t8YEBt2xdfqu8+gP9hqPUPsiXlNPcpS2gVdjmis5GKPG3fCxbQLVgxsQZ8w==", + "devOptional": true, + "license": "MIT", + "dependencies": { + "csstype": "^3.0.2" + } + }, + "node_modules/@types/yargs": { + "version": "17.0.33", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/yargs-parser": "*" + } + }, + "node_modules/@types/yargs-parser": { + "version": "21.0.3", + "dev": true, + "license": "MIT" + }, + "node_modules/agent-base": { + "version": "7.1.3", + "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-7.1.3.tgz", + "integrity": "sha512-jRR5wdylq8CkOe6hei19GGZnxM6rBGwFl3Bg0YItGDimvjGtAvdZk4Pu6Cl4u4Igsws4a1fd1Vq3ezrhn4KmFw==", + "license": "MIT", + "engines": { + "node": ">= 14" + } + }, + "node_modules/ansi-escapes": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/ansi-escapes/-/ansi-escapes-7.0.0.tgz", + "integrity": "sha512-GdYO7a61mR0fOlAsvC9/rIHf7L96sBc6dEWzeOu+KAea5bZyQRPIpojrVoI4AXGJS/ycu/fBTdLrUkA4ODrvjw==", + "license": "MIT", + "dependencies": { + "environment": "^1.0.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/ansi-regex": { + "version": "5.0.1", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/ansi-styles": { + "version": "4.3.0", + "license": "MIT", + "dependencies": { + "color-convert": "^2.0.1" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/auto-bind": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/auto-bind/-/auto-bind-5.0.1.tgz", + "integrity": "sha512-ooviqdwwgfIfNmDwo94wlshcdzfO64XV0Cg6oDsDYBJfITDz1EngD2z7DkbvCWn+XIMsIqW27sEVF6qcpJrRcg==", + "license": "MIT", + "engines": { + "node": "^12.20.0 || ^14.13.1 || >=16.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/base64-js": { + "version": "1.5.1", + "resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz", + "integrity": "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT" + }, + "node_modules/bignumber.js": { + "version": "9.2.1", + "resolved": "https://registry.npmjs.org/bignumber.js/-/bignumber.js-9.2.1.tgz", + "integrity": "sha512-+NzaKgOUvInq9TIUZ1+DRspzf/HApkCwD4btfuasFTdrfnOxqx853TgDpMolp+uv4RpRp7bPcEU2zKr9+fRmyw==", + "license": "MIT", + "engines": { + "node": "*" + } + }, + "node_modules/braces": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/braces/-/braces-3.0.3.tgz", + "integrity": "sha512-yQbXgO/OSZVD2IsiLlro+7Hf6Q18EJrKSEsdoMzKePKXct3gvD8oLcOQdIzGupr5Fj+EDe8gO/lxc1BzfMpxvA==", + "license": "MIT", + "dependencies": { + "fill-range": "^7.1.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/buffer-equal-constant-time": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/buffer-equal-constant-time/-/buffer-equal-constant-time-1.0.1.tgz", + "integrity": "sha512-zRpUiDwd/xk6ADqPMATG8vc9VPrkck7T07OIx0gnjmJAnHnTVXNQG3vfvWNuiZIkwu9KrKdA1iJKfsfTVxE6NA==", + "license": "BSD-3-Clause" + }, + "node_modules/cli-boxes": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/cli-boxes/-/cli-boxes-3.0.0.tgz", + "integrity": "sha512-/lzGpEWL/8PfI0BmBOPRwp0c/wFNX1RdUML3jK/RcSBA9T8mZDdQpqYBKtCFTOfQbwPqWEOpjqW+Fnayc0969g==", + "license": "MIT", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/cli-spinners": { + "version": "2.9.2", + "resolved": "https://registry.npmjs.org/cli-spinners/-/cli-spinners-2.9.2.tgz", + "integrity": "sha512-ywqV+5MmyL4E7ybXgKys4DugZbX0FC6LnwrhjuykIjnK9k8OQacQ7axGKnjDXWNhns0xot3bZI5h55H8yo9cJg==", + "license": "MIT", + "engines": { + "node": ">=6" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/cli-truncate": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/cli-truncate/-/cli-truncate-4.0.0.tgz", + "integrity": "sha512-nPdaFdQ0h/GEigbPClz11D0v/ZJEwxmeVZGeMo3Z5StPtUTkA9o1lD6QwoirYiSDzbcwn2XcjwmCp68W1IS4TA==", + "license": "MIT", + "dependencies": { + "slice-ansi": "^5.0.0", + "string-width": "^7.0.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/cli-truncate/node_modules/ansi-regex": { + "version": "6.1.0", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-6.1.0.tgz", + "integrity": "sha512-7HSX4QQb4CspciLpVFwyRe79O3xsIZDDLER21kERQ71oaPodF8jL725AgJMFAYbooIqolJoRLuM81SpeUkpkvA==", + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/ansi-regex?sponsor=1" + } + }, + "node_modules/cli-truncate/node_modules/ansi-styles": { + "version": "6.2.1", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-6.2.1.tgz", + "integrity": "sha512-bN798gFfQX+viw3R7yrGWRqnrN2oRkEkUjjl4JNn4E8GxxbjtG3FbrEIIY3l8/hrwUwIeCZvi4QuOTP4MErVug==", + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/cli-truncate/node_modules/emoji-regex": { + "version": "10.4.0", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-10.4.0.tgz", + "integrity": "sha512-EC+0oUMY1Rqm4O6LLrgjtYDvcVYTy7chDnM4Q7030tP4Kwj3u/pR6gP9ygnp2CJMK5Gq+9Q2oqmrFJAz01DXjw==", + "license": "MIT" + }, + "node_modules/cli-truncate/node_modules/is-fullwidth-code-point": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-4.0.0.tgz", + "integrity": "sha512-O4L094N2/dZ7xqVdrXhh9r1KODPJpFms8B5sGdJLPy664AgvXsreZUyCQQNItZRDlYug4xStLjNp/sz3HvBowQ==", + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/cli-truncate/node_modules/slice-ansi": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/slice-ansi/-/slice-ansi-5.0.0.tgz", + "integrity": "sha512-FC+lgizVPfie0kkhqUScwRu1O/lF6NOgJmlCgK+/LYxDCTk8sGelYaHDhFcDN+Sn3Cv+3VSa4Byeo+IMCzpMgQ==", + "license": "MIT", + "dependencies": { + "ansi-styles": "^6.0.0", + "is-fullwidth-code-point": "^4.0.0" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/slice-ansi?sponsor=1" + } + }, + "node_modules/cli-truncate/node_modules/string-width": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-7.2.0.tgz", + "integrity": "sha512-tsaTIkKW9b4N+AEj+SVA+WhJzV7/zMhcSu78mLKWSk7cXMOSHsBKFWUs0fWwq8QyK3MgJBQRX6Gbi4kYbdvGkQ==", + "license": "MIT", + "dependencies": { + "emoji-regex": "^10.3.0", + "get-east-asian-width": "^1.0.0", + "strip-ansi": "^7.1.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/cli-truncate/node_modules/strip-ansi": { + "version": "7.1.0", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-7.1.0.tgz", + "integrity": "sha512-iq6eVVI64nQQTRYq2KtEg2d2uU7LElhTJwsH4YzIHZshxlgZms/wIc4VoDQTlG/IvVIrBKG06CrZnp0qv7hkcQ==", + "license": "MIT", + "dependencies": { + "ansi-regex": "^6.0.1" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/strip-ansi?sponsor=1" + } + }, + "node_modules/cliui": { + "version": "8.0.1", + "license": "ISC", + "dependencies": { + "string-width": "^4.2.0", + "strip-ansi": "^6.0.1", + "wrap-ansi": "^7.0.0" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/code-excerpt": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/code-excerpt/-/code-excerpt-4.0.0.tgz", + "integrity": "sha512-xxodCmBen3iy2i0WtAK8FlFNrRzjUqjRsMfho58xT/wvZU1YTM3fCnRjcy1gJPMepaRlgm/0e6w8SpWHpn3/cA==", + "license": "MIT", + "dependencies": { + "convert-to-spaces": "^2.0.1" + }, + "engines": { + "node": "^12.20.0 || ^14.13.1 || >=16.0.0" + } + }, + "node_modules/color-convert": { + "version": "2.0.1", + "license": "MIT", + "dependencies": { + "color-name": "~1.1.4" + }, + "engines": { + "node": ">=7.0.0" + } + }, + "node_modules/color-name": { + "version": "1.1.4", + "license": "MIT" + }, + "node_modules/convert-to-spaces": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/convert-to-spaces/-/convert-to-spaces-2.0.1.tgz", + "integrity": "sha512-rcQ1bsQO9799wq24uE5AM2tAILy4gXGIK/njFWcVQkGNZ96edlpY+A7bjwvzjYvLDyzmG1MmMLZhpcsb+klNMQ==", + "license": "MIT", + "engines": { + "node": "^12.20.0 || ^14.13.1 || >=16.0.0" + } + }, + "node_modules/csstype": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/csstype/-/csstype-3.1.3.tgz", + "integrity": "sha512-M1uQkMl8rQK/szD0LNhtqxIPLpimGm8sOBwU7lLnCpSbTyY3yeU1Vc7l4KT5zT4s/yOxHH5O7tIuuLOCnLADRw==", + "devOptional": true, + "license": "MIT" + }, + "node_modules/debug": { + "version": "4.4.0", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.0.tgz", + "integrity": "sha512-6WTZ/IxCY/T6BALoZHaE4ctp9xm+Z5kY/pzYaCHRFeyVhojxlrm+46y68HA6hr0TcwEssoxNiDEUJQjfPZ/RYA==", + "license": "MIT", + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/diff": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/diff/-/diff-7.0.0.tgz", + "integrity": "sha512-PJWHUb1RFevKCwaFA9RlG5tCd+FO5iRh9A8HEtkmBH2Li03iJriB6m6JIN4rGz3K3JLawI7/veA1xzRKP6ISBw==", + "license": "BSD-3-Clause", + "engines": { + "node": ">=0.3.1" + } + }, + "node_modules/dotenv": { + "version": "16.4.7", + "resolved": "https://registry.npmjs.org/dotenv/-/dotenv-16.4.7.tgz", + "integrity": "sha512-47qPchRCykZC03FhkYAhrvwU4xDBFIj1QPqaarj6mdM/hgUzfPHcpkHJOn3mJAufFeeAxAzeGsr5X0M4k6fLZQ==", + "license": "BSD-2-Clause", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://dotenvx.com" + } + }, + "node_modules/ecdsa-sig-formatter": { + "version": "1.0.11", + "resolved": "https://registry.npmjs.org/ecdsa-sig-formatter/-/ecdsa-sig-formatter-1.0.11.tgz", + "integrity": "sha512-nagl3RYrbNv6kQkeJIpt6NJZy8twLB/2vtz6yN9Z4vRKHN4/QZJIEbqohALSgwKdnksuY3k5Addp5lg8sVoVcQ==", + "license": "Apache-2.0", + "dependencies": { + "safe-buffer": "^5.0.1" + } + }, + "node_modules/emoji-regex": { + "version": "8.0.0", + "license": "MIT" + }, + "node_modules/environment": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/environment/-/environment-1.1.0.tgz", + "integrity": "sha512-xUtoPkMggbz0MPyPiIWr1Kp4aeWJjDZ6SMvURhimjdZgsRuDplF5/s9hcgGhyXMhs+6vpnuoiZ2kFiu3FMnS8Q==", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/es-toolkit": { + "version": "1.34.1", + "resolved": "https://registry.npmjs.org/es-toolkit/-/es-toolkit-1.34.1.tgz", + "integrity": "sha512-OA6cd94fJV9bm8dWhIySkWq4xV+rAQnBZUr2dnpXam0QJ8c+hurLbKA8/QooL9Mx4WCAxvIDsiEkid5KPQ5xgQ==", + "license": "MIT", + "workspaces": [ + "docs", + "benchmarks" + ] + }, + "node_modules/escalade": { + "version": "3.2.0", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/escape-string-regexp": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-2.0.0.tgz", + "integrity": "sha512-UpzcLCXolUWcNu5HtVMHYdXJjArjsF9C0aNnquZYY4uW/Vu0miy5YoWvbV345HauVvcAUnpRuhMMcqTcGOY2+w==", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/extend": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/extend/-/extend-3.0.2.tgz", + "integrity": "sha512-fjquC59cD7CyW6urNXK0FBufkZcoiGG80wTuPujX590cB5Ttln20E2UB4S/WARVqhXffZl2LNgS+gQdPIIim/g==", + "license": "MIT" + }, + "node_modules/fast-glob": { + "version": "3.3.3", + "resolved": "https://registry.npmjs.org/fast-glob/-/fast-glob-3.3.3.tgz", + "integrity": "sha512-7MptL8U0cqcFdzIzwOTHoilX9x5BrNqye7Z/LuC7kCMRio1EMSyqRK3BEAUD7sXRq4iT4AzTVuZdhgQ2TCvYLg==", + "license": "MIT", + "dependencies": { + "@nodelib/fs.stat": "^2.0.2", + "@nodelib/fs.walk": "^1.2.3", + "glob-parent": "^5.1.2", + "merge2": "^1.3.0", + "micromatch": "^4.0.8" + }, + "engines": { + "node": ">=8.6.0" + } + }, + "node_modules/fastq": { + "version": "1.19.1", + "resolved": "https://registry.npmjs.org/fastq/-/fastq-1.19.1.tgz", + "integrity": "sha512-GwLTyxkCXjXbxqIhTsMI2Nui8huMPtnxg7krajPJAjnEG/iiOS7i+zCtWGZR9G0NBKbXKh6X9m9UIsYX/N6vvQ==", + "license": "ISC", + "dependencies": { + "reusify": "^1.0.4" + } + }, + "node_modules/figures": { + "version": "6.1.0", + "resolved": "https://registry.npmjs.org/figures/-/figures-6.1.0.tgz", + "integrity": "sha512-d+l3qxjSesT4V7v2fh+QnmFnUWv9lSpjarhShNTgBOfA0ttejbQUAlHLitbjkoRiDulW0OPoQPYIGhIC8ohejg==", + "license": "MIT", + "dependencies": { + "is-unicode-supported": "^2.0.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/fill-range": { + "version": "7.1.1", + "resolved": "https://registry.npmjs.org/fill-range/-/fill-range-7.1.1.tgz", + "integrity": "sha512-YsGpe3WHLK8ZYi4tWDg2Jy3ebRz2rXowDxnld4bkQB00cc/1Zw9AWnC0i9ztDJitivtQvaI9KaLyKrc+hBW0yg==", + "license": "MIT", + "dependencies": { + "to-regex-range": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/gaxios": { + "version": "6.7.1", + "resolved": "https://registry.npmjs.org/gaxios/-/gaxios-6.7.1.tgz", + "integrity": "sha512-LDODD4TMYx7XXdpwxAVRAIAuB0bzv0s+ywFonY46k126qzQHT9ygyoa9tncmOiQmmDrik65UYsEkv3lbfqQ3yQ==", + "license": "Apache-2.0", + "dependencies": { + "extend": "^3.0.2", + "https-proxy-agent": "^7.0.1", + "is-stream": "^2.0.0", + "node-fetch": "^2.6.9", + "uuid": "^9.0.1" + }, + "engines": { + "node": ">=14" + } + }, + "node_modules/gcp-metadata": { + "version": "6.1.1", + "resolved": "https://registry.npmjs.org/gcp-metadata/-/gcp-metadata-6.1.1.tgz", + "integrity": "sha512-a4tiq7E0/5fTjxPAaH4jpjkSv/uCaU2p5KC6HVGrvl0cDjA8iBZv4vv1gyzlmK0ZUKqwpOyQMKzZQe3lTit77A==", + "license": "Apache-2.0", + "dependencies": { + "gaxios": "^6.1.1", + "google-logging-utils": "^0.0.2", + "json-bigint": "^1.0.0" + }, + "engines": { + "node": ">=14" + } + }, + "node_modules/gemini-code-cli": { + "resolved": "packages/cli", + "link": true + }, + "node_modules/get-caller-file": { + "version": "2.0.5", + "license": "ISC", + "engines": { + "node": "6.* || 8.* || >= 10.*" + } + }, + "node_modules/get-east-asian-width": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/get-east-asian-width/-/get-east-asian-width-1.3.0.tgz", + "integrity": "sha512-vpeMIQKxczTD/0s2CdEWHcb0eeJe6TFjxb+J5xgX7hScxqrGuyjmv4c1D4A/gelKfyox0gJJwIHF+fLjeaM8kQ==", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/glob-parent": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-5.1.2.tgz", + "integrity": "sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow==", + "license": "ISC", + "dependencies": { + "is-glob": "^4.0.1" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/google-auth-library": { + "version": "9.15.1", + "resolved": "https://registry.npmjs.org/google-auth-library/-/google-auth-library-9.15.1.tgz", + "integrity": "sha512-Jb6Z0+nvECVz+2lzSMt9u98UsoakXxA2HGHMCxh+so3n90XgYWkq5dur19JAJV7ONiJY22yBTyJB1TSkvPq9Ng==", + "license": "Apache-2.0", + "dependencies": { + "base64-js": "^1.3.0", + "ecdsa-sig-formatter": "^1.0.11", + "gaxios": "^6.1.1", + "gcp-metadata": "^6.1.0", + "gtoken": "^7.0.0", + "jws": "^4.0.0" + }, + "engines": { + "node": ">=14" + } + }, + "node_modules/google-logging-utils": { + "version": "0.0.2", + "resolved": "https://registry.npmjs.org/google-logging-utils/-/google-logging-utils-0.0.2.tgz", + "integrity": "sha512-NEgUnEcBiP5HrPzufUkBzJOD/Sxsco3rLNo1F1TNf7ieU8ryUzBhqba8r756CjLX7rn3fHl6iLEwPYuqpoKgQQ==", + "license": "Apache-2.0", + "engines": { + "node": ">=14" + } + }, + "node_modules/gtoken": { + "version": "7.1.0", + "resolved": "https://registry.npmjs.org/gtoken/-/gtoken-7.1.0.tgz", + "integrity": "sha512-pCcEwRi+TKpMlxAQObHDQ56KawURgyAf6jtIY046fJ5tIv3zDe/LEIubckAO8fj6JnAxLdmWkUfNyulQ2iKdEw==", + "license": "MIT", + "dependencies": { + "gaxios": "^6.0.0", + "jws": "^4.0.0" + }, + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/https-proxy-agent": { + "version": "7.0.6", + "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-7.0.6.tgz", + "integrity": "sha512-vK9P5/iUfdl95AI+JVyUuIcVtd4ofvtrOr3HNtM2yxC9bnMbEdp3x01OhQNnjb8IJYi38VlTE3mBXwcfvywuSw==", + "license": "MIT", + "dependencies": { + "agent-base": "^7.1.2", + "debug": "4" + }, + "engines": { + "node": ">= 14" + } + }, + "node_modules/indent-string": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/indent-string/-/indent-string-5.0.0.tgz", + "integrity": "sha512-m6FAo/spmsW2Ab2fU35JTYwtOKa2yAwXSwgjSv1TJzh4Mh7mC3lzAOVLBprb72XsTrgkEIsl7YrFNAiDiRhIGg==", + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/ink": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/ink/-/ink-5.2.0.tgz", + "integrity": "sha512-gHzSBBvsh/1ZYuGi+aKzU7RwnYIr6PSz56or9T90i4DDS99euhN7nYKOMR3OTev0dKIB6Zod3vSapYzqoilQcg==", + "license": "MIT", + "dependencies": { + "@alcalzone/ansi-tokenize": "^0.1.3", + "ansi-escapes": "^7.0.0", + "ansi-styles": "^6.2.1", + "auto-bind": "^5.0.1", + "chalk": "^5.3.0", + "cli-boxes": "^3.0.0", + "cli-cursor": "^4.0.0", + "cli-truncate": "^4.0.0", + "code-excerpt": "^4.0.0", + "es-toolkit": "^1.22.0", + "indent-string": "^5.0.0", + "is-in-ci": "^1.0.0", + "patch-console": "^2.0.0", + "react-reconciler": "^0.29.0", + "scheduler": "^0.23.0", + "signal-exit": "^3.0.7", + "slice-ansi": "^7.1.0", + "stack-utils": "^2.0.6", + "string-width": "^7.2.0", + "type-fest": "^4.27.0", + "widest-line": "^5.0.0", + "wrap-ansi": "^9.0.0", + "ws": "^8.18.0", + "yoga-layout": "~3.2.1" + }, + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "@types/react": ">=18.0.0", + "react": ">=18.0.0", + "react-devtools-core": "^4.19.1" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "react-devtools-core": { + "optional": true + } + } + }, + "node_modules/ink-select-input": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/ink-select-input/-/ink-select-input-6.0.0.tgz", + "integrity": "sha512-2mCbn1b9xeguA3qJiaf8Sx8W4MM005wACcLKwHWWJmJ8BapjsahmQPuY2U2qyGc817IdWFjNk/K41Vn39UlO4Q==", + "license": "MIT", + "dependencies": { + "figures": "^6.1.0", + "lodash.isequal": "^4.5.0", + "to-rotated": "^1.0.0" + }, + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "ink": ">=5.0.0", + "react": ">=18.0.0" + } + }, + "node_modules/ink-spinner": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/ink-spinner/-/ink-spinner-5.0.0.tgz", + "integrity": "sha512-EYEasbEjkqLGyPOUc8hBJZNuC5GvXGMLu0w5gdTNskPc7Izc5vO3tdQEYnzvshucyGCBXc86ig0ujXPMWaQCdA==", + "license": "MIT", + "dependencies": { + "cli-spinners": "^2.7.0" + }, + "engines": { + "node": ">=14.16" + }, + "peerDependencies": { + "ink": ">=4.0.0", + "react": ">=18.0.0" + } + }, + "node_modules/ink-text-input": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/ink-text-input/-/ink-text-input-6.0.0.tgz", + "integrity": "sha512-Fw64n7Yha5deb1rHY137zHTAbSTNelUKuB5Kkk2HACXEtwIHBCf9OH2tP/LQ9fRYTl1F0dZgbW0zPnZk6FA9Lw==", + "license": "MIT", + "dependencies": { + "chalk": "^5.3.0", + "type-fest": "^4.18.2" + }, + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "ink": ">=5", + "react": ">=18" + } + }, + "node_modules/ink-text-input/node_modules/chalk": { + "version": "5.4.1", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-5.4.1.tgz", + "integrity": "sha512-zgVZuo2WcZgfUEmsn6eO3kINexW8RAE4maiQ8QNs8CtpPCSyMiYsULR3HQYkm3w8FIA3SberyMJMSldGsW+U3w==", + "license": "MIT", + "engines": { + "node": "^12.17.0 || ^14.13 || >=16.0.0" + }, + "funding": { + "url": "https://github.com/chalk/chalk?sponsor=1" + } + }, + "node_modules/ink/node_modules/ansi-regex": { + "version": "6.1.0", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-6.1.0.tgz", + "integrity": "sha512-7HSX4QQb4CspciLpVFwyRe79O3xsIZDDLER21kERQ71oaPodF8jL725AgJMFAYbooIqolJoRLuM81SpeUkpkvA==", + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/ansi-regex?sponsor=1" + } + }, + "node_modules/ink/node_modules/ansi-styles": { + "version": "6.2.1", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-6.2.1.tgz", + "integrity": "sha512-bN798gFfQX+viw3R7yrGWRqnrN2oRkEkUjjl4JNn4E8GxxbjtG3FbrEIIY3l8/hrwUwIeCZvi4QuOTP4MErVug==", + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/ink/node_modules/chalk": { + "version": "5.4.1", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-5.4.1.tgz", + "integrity": "sha512-zgVZuo2WcZgfUEmsn6eO3kINexW8RAE4maiQ8QNs8CtpPCSyMiYsULR3HQYkm3w8FIA3SberyMJMSldGsW+U3w==", + "license": "MIT", + "engines": { + "node": "^12.17.0 || ^14.13 || >=16.0.0" + }, + "funding": { + "url": "https://github.com/chalk/chalk?sponsor=1" + } + }, + "node_modules/ink/node_modules/cli-cursor": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/cli-cursor/-/cli-cursor-4.0.0.tgz", + "integrity": "sha512-VGtlMu3x/4DOtIUwEkRezxUZ2lBacNJCHash0N0WeZDBS+7Ux1dm3XWAgWYxLJFMMdOeXMHXorshEFhbMSGelg==", + "license": "MIT", + "dependencies": { + "restore-cursor": "^4.0.0" + }, + "engines": { + "node": "^12.20.0 || ^14.13.1 || >=16.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/ink/node_modules/emoji-regex": { + "version": "10.4.0", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-10.4.0.tgz", + "integrity": "sha512-EC+0oUMY1Rqm4O6LLrgjtYDvcVYTy7chDnM4Q7030tP4Kwj3u/pR6gP9ygnp2CJMK5Gq+9Q2oqmrFJAz01DXjw==", + "license": "MIT" + }, + "node_modules/ink/node_modules/onetime": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/onetime/-/onetime-5.1.2.tgz", + "integrity": "sha512-kbpaSSGJTWdAY5KPVeMOKXSrPtr8C8C7wodJbcsd51jRnmD+GZu8Y0VoU6Dm5Z4vWr0Ig/1NKuWRKf7j5aaYSg==", + "license": "MIT", + "dependencies": { + "mimic-fn": "^2.1.0" + }, + "engines": { + "node": ">=6" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/ink/node_modules/restore-cursor": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/restore-cursor/-/restore-cursor-4.0.0.tgz", + "integrity": "sha512-I9fPXU9geO9bHOt9pHHOhOkYerIMsmVaWB0rA2AI9ERh/+x/i7MV5HKBNrg+ljO5eoPVgCcnFuRjJ9uH6I/3eg==", + "license": "MIT", + "dependencies": { + "onetime": "^5.1.0", + "signal-exit": "^3.0.2" + }, + "engines": { + "node": "^12.20.0 || ^14.13.1 || >=16.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/ink/node_modules/signal-exit": { + "version": "3.0.7", + "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-3.0.7.tgz", + "integrity": "sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ==", + "license": "ISC" + }, + "node_modules/ink/node_modules/string-width": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-7.2.0.tgz", + "integrity": "sha512-tsaTIkKW9b4N+AEj+SVA+WhJzV7/zMhcSu78mLKWSk7cXMOSHsBKFWUs0fWwq8QyK3MgJBQRX6Gbi4kYbdvGkQ==", + "license": "MIT", + "dependencies": { + "emoji-regex": "^10.3.0", + "get-east-asian-width": "^1.0.0", + "strip-ansi": "^7.1.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/ink/node_modules/strip-ansi": { + "version": "7.1.0", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-7.1.0.tgz", + "integrity": "sha512-iq6eVVI64nQQTRYq2KtEg2d2uU7LElhTJwsH4YzIHZshxlgZms/wIc4VoDQTlG/IvVIrBKG06CrZnp0qv7hkcQ==", + "license": "MIT", + "dependencies": { + "ansi-regex": "^6.0.1" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/strip-ansi?sponsor=1" + } + }, + "node_modules/ink/node_modules/wrap-ansi": { + "version": "9.0.0", + "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-9.0.0.tgz", + "integrity": "sha512-G8ura3S+3Z2G+mkgNRq8dqaFZAuxfsxpBB8OCTGRTCtp+l/v9nbFNmCUP1BZMts3G1142MsZfn6eeUKrr4PD1Q==", + "license": "MIT", + "dependencies": { + "ansi-styles": "^6.2.1", + "string-width": "^7.0.0", + "strip-ansi": "^7.1.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/chalk/wrap-ansi?sponsor=1" + } + }, + "node_modules/is-extglob": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-2.1.1.tgz", + "integrity": "sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/is-fullwidth-code-point": { + "version": "3.0.0", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/is-glob": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-4.0.3.tgz", + "integrity": "sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg==", + "license": "MIT", + "dependencies": { + "is-extglob": "^2.1.1" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/is-in-ci": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/is-in-ci/-/is-in-ci-1.0.0.tgz", + "integrity": "sha512-eUuAjybVTHMYWm/U+vBO1sY/JOCgoPCXRxzdju0K+K0BiGW0SChEL1MLC0PoCIR1OlPo5YAp8HuQoUlsWEICwg==", + "license": "MIT", + "bin": { + "is-in-ci": "cli.js" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/is-number": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/is-number/-/is-number-7.0.0.tgz", + "integrity": "sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng==", + "license": "MIT", + "engines": { + "node": ">=0.12.0" + } + }, + "node_modules/is-stream": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/is-stream/-/is-stream-2.0.1.tgz", + "integrity": "sha512-hFoiJiTl63nn+kstHGBtewWSKnQLpyb155KHheA1l39uvtO9nWIop1p3udqPcUd/xbF1VLMO4n7OI6p7RbngDg==", + "license": "MIT", + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/is-unicode-supported": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/is-unicode-supported/-/is-unicode-supported-2.1.0.tgz", + "integrity": "sha512-mE00Gnza5EEB3Ds0HfMyllZzbBrmLOX3vfWoj9A9PEnTfratQ/BcaJOuMhnkhjXvb2+FkY3VuHqtAGpTPmglFQ==", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/js-tokens": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz", + "integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==", + "license": "MIT" + }, + "node_modules/json-bigint": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/json-bigint/-/json-bigint-1.0.0.tgz", + "integrity": "sha512-SiPv/8VpZuWbvLSMtTDU8hEfrZWg/mH/nV/b4o0CYbSxu1UIQPLdwKOCIyLQX+VIPO5vrLX3i8qtqFyhdPSUSQ==", + "license": "MIT", + "dependencies": { + "bignumber.js": "^9.0.0" + } + }, + "node_modules/jwa": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/jwa/-/jwa-2.0.0.tgz", + "integrity": "sha512-jrZ2Qx916EA+fq9cEAeCROWPTfCwi1IVHqT2tapuqLEVVDKFDENFw1oL+MwrTvH6msKxsd1YTDVw6uKEcsrLEA==", + "license": "MIT", + "dependencies": { + "buffer-equal-constant-time": "1.0.1", + "ecdsa-sig-formatter": "1.0.11", + "safe-buffer": "^5.0.1" + } + }, + "node_modules/jws": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/jws/-/jws-4.0.0.tgz", + "integrity": "sha512-KDncfTmOZoOMTFG4mBlG0qUIOlc03fmzH+ru6RgYVZhPkyiy/92Owlt/8UEN+a4TXR1FQetfIpJE8ApdvdVxTg==", + "license": "MIT", + "dependencies": { + "jwa": "^2.0.0", + "safe-buffer": "^5.0.1" + } + }, + "node_modules/lodash.isequal": { + "version": "4.5.0", + "resolved": "https://registry.npmjs.org/lodash.isequal/-/lodash.isequal-4.5.0.tgz", + "integrity": "sha512-pDo3lu8Jhfjqls6GkMgpahsF9kCyayhgykjyLMNFTKWrpVdAQtYyB4muAMWozBB4ig/dtWAmsMxLEI8wuz+DYQ==", + "deprecated": "This package is deprecated. Use require('node:util').isDeepStrictEqual instead.", + "license": "MIT" + }, + "node_modules/loose-envify": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/loose-envify/-/loose-envify-1.4.0.tgz", + "integrity": "sha512-lyuxPGr/Wfhrlem2CL/UcnUc1zcqKAImBDzukY7Y5F/yQiNdko6+fRLevlw1HgMySw7f611UIY408EtxRSoK3Q==", + "license": "MIT", + "dependencies": { + "js-tokens": "^3.0.0 || ^4.0.0" + }, + "bin": { + "loose-envify": "cli.js" + } + }, + "node_modules/merge2": { + "version": "1.4.1", + "resolved": "https://registry.npmjs.org/merge2/-/merge2-1.4.1.tgz", + "integrity": "sha512-8q7VEgMJW4J8tcfVPy8g09NcQwZdbwFEqhe/WZkoIzjn/3TGDwtOCYtXGxA3O8tPzpczCCDgv+P2P5y00ZJOOg==", + "license": "MIT", + "engines": { + "node": ">= 8" + } + }, + "node_modules/micromatch": { + "version": "4.0.8", + "resolved": "https://registry.npmjs.org/micromatch/-/micromatch-4.0.8.tgz", + "integrity": "sha512-PXwfBhYu0hBCPw8Dn0E+WDYb7af3dSLVWKi3HGv84IdF4TyFoC0ysxFd0Goxw7nSv4T/PzEJQxsYsEiFCKo2BA==", + "license": "MIT", + "dependencies": { + "braces": "^3.0.3", + "picomatch": "^2.3.1" + }, + "engines": { + "node": ">=8.6" + } + }, + "node_modules/mimic-fn": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/mimic-fn/-/mimic-fn-2.1.0.tgz", + "integrity": "sha512-OqbOk5oEQeAZ8WXWydlu9HJjz9WVdEIvamMCcXmuqUYjTknH/sqsWvhQ3vgwKFRR1HpjvNBKQ37nbJgYzGqGcg==", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", + "license": "MIT" + }, + "node_modules/node-fetch": { + "version": "2.7.0", + "resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-2.7.0.tgz", + "integrity": "sha512-c4FRfUm/dbcWZ7U+1Wq0AwCyFL+3nt2bEw05wfxSz+DWpWsitgmSgYmy2dQdWyKC1694ELPqMs/YzUSNozLt8A==", + "license": "MIT", + "dependencies": { + "whatwg-url": "^5.0.0" + }, + "engines": { + "node": "4.x || >=6.0.0" + }, + "peerDependencies": { + "encoding": "^0.1.0" + }, + "peerDependenciesMeta": { + "encoding": { + "optional": true + } + } + }, + "node_modules/patch-console": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/patch-console/-/patch-console-2.0.0.tgz", + "integrity": "sha512-0YNdUceMdaQwoKce1gatDScmMo5pu/tfABfnzEqeG0gtTmd7mh/WcwgUjtAeOU7N8nFFlbQBnFK2gXW5fGvmMA==", + "license": "MIT", + "engines": { + "node": "^12.20.0 || ^14.13.1 || >=16.0.0" + } + }, + "node_modules/picomatch": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.1.tgz", + "integrity": "sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA==", + "license": "MIT", + "engines": { + "node": ">=8.6" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/queue-microtask": { + "version": "1.2.3", + "resolved": "https://registry.npmjs.org/queue-microtask/-/queue-microtask-1.2.3.tgz", + "integrity": "sha512-NuaNSa6flKT5JaSYQzJok04JzTL1CA6aGhv5rfLW3PgqA+M2ChpZQnAC8h8i4ZFkBS8X5RqkDBHA7r4hej3K9A==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT" + }, + "node_modules/react": { + "version": "18.3.1", + "resolved": "https://registry.npmjs.org/react/-/react-18.3.1.tgz", + "integrity": "sha512-wS+hAgJShR0KhEvPJArfuPVN1+Hz1t0Y6n5jLrGQbkb4urgPE/0Rve+1kMB1v/oWgHgm4WIcV+i7F2pTVj+2iQ==", + "license": "MIT", + "dependencies": { + "loose-envify": "^1.1.0" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/react-devtools-core": { + "version": "4.28.5", + "resolved": "https://registry.npmjs.org/react-devtools-core/-/react-devtools-core-4.28.5.tgz", + "integrity": "sha512-cq/o30z9W2Wb4rzBefjv5fBalHU0rJGZCHAkf/RHSBWSSYwh8PlQTqqOJmgIIbBtpj27T6FIPXeomIjZtCNVqA==", + "license": "MIT", + "optional": true, + "peer": true, + "dependencies": { + "shell-quote": "^1.6.1", + "ws": "^7" + } + }, + "node_modules/react-devtools-core/node_modules/ws": { + "version": "7.5.10", + "resolved": "https://registry.npmjs.org/ws/-/ws-7.5.10.tgz", + "integrity": "sha512-+dbF1tHwZpXcbOJdVOkzLDxZP1ailvSxM6ZweXTegylPny803bFhA+vqBYw4s31NSAk4S2Qz+AKXK9a4wkdjcQ==", + "license": "MIT", + "optional": true, + "peer": true, + "engines": { + "node": ">=8.3.0" + }, + "peerDependencies": { + "bufferutil": "^4.0.1", + "utf-8-validate": "^5.0.2" + }, + "peerDependenciesMeta": { + "bufferutil": { + "optional": true + }, + "utf-8-validate": { + "optional": true + } + } + }, + "node_modules/react-reconciler": { + "version": "0.29.2", + "resolved": "https://registry.npmjs.org/react-reconciler/-/react-reconciler-0.29.2.tgz", + "integrity": "sha512-zZQqIiYgDCTP/f1N/mAR10nJGrPD2ZR+jDSEsKWJHYC7Cm2wodlwbR3upZRdC3cjIjSlTLNVyO7Iu0Yy7t2AYg==", + "license": "MIT", + "dependencies": { + "loose-envify": "^1.1.0", + "scheduler": "^0.23.2" + }, + "engines": { + "node": ">=0.10.0" + }, + "peerDependencies": { + "react": "^18.3.1" + } + }, + "node_modules/require-directory": { + "version": "2.1.1", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/reusify": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/reusify/-/reusify-1.1.0.tgz", + "integrity": "sha512-g6QUff04oZpHs0eG5p83rFLhHeV00ug/Yf9nZM6fLeUrPguBTkTQOdpAWWspMh55TZfVQDPaN3NQJfbVRAxdIw==", + "license": "MIT", + "engines": { + "iojs": ">=1.0.0", + "node": ">=0.10.0" + } + }, + "node_modules/run-parallel": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/run-parallel/-/run-parallel-1.2.0.tgz", + "integrity": "sha512-5l4VyZR86LZ/lDxZTR6jqL8AFE2S0IFLMP26AbjsLVADxHdhB/c0GUsH+y39UfCi3dzz8OlQuPmnaJOMoDHQBA==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT", + "dependencies": { + "queue-microtask": "^1.2.2" + } + }, + "node_modules/safe-buffer": { + "version": "5.2.1", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz", + "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT" + }, + "node_modules/scheduler": { + "version": "0.23.2", + "resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.23.2.tgz", + "integrity": "sha512-UOShsPwz7NrMUqhR6t0hWjFduvOzbtv7toDH1/hIrfRNIDBnnBWd0CwJTGvTpngVlmwGCdP9/Zl/tVrDqcuYzQ==", + "license": "MIT", + "dependencies": { + "loose-envify": "^1.1.0" + } + }, + "node_modules/shell-quote": { + "version": "1.8.2", + "resolved": "https://registry.npmjs.org/shell-quote/-/shell-quote-1.8.2.tgz", + "integrity": "sha512-AzqKpGKjrj7EM6rKVQEPpB288oCfnrEIuyoT9cyF4nmGa7V8Zk6f7RRqYisX8X9m+Q7bd632aZW4ky7EhbQztA==", + "license": "MIT", + "optional": true, + "peer": true, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/slice-ansi": { + "version": "7.1.0", + "resolved": "https://registry.npmjs.org/slice-ansi/-/slice-ansi-7.1.0.tgz", + "integrity": "sha512-bSiSngZ/jWeX93BqeIAbImyTbEihizcwNjFoRUIY/T1wWQsfsm2Vw1agPKylXvQTU7iASGdHhyqRlqQzfz+Htg==", + "license": "MIT", + "dependencies": { + "ansi-styles": "^6.2.1", + "is-fullwidth-code-point": "^5.0.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/chalk/slice-ansi?sponsor=1" + } + }, + "node_modules/slice-ansi/node_modules/ansi-styles": { + "version": "6.2.1", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-6.2.1.tgz", + "integrity": "sha512-bN798gFfQX+viw3R7yrGWRqnrN2oRkEkUjjl4JNn4E8GxxbjtG3FbrEIIY3l8/hrwUwIeCZvi4QuOTP4MErVug==", + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/slice-ansi/node_modules/is-fullwidth-code-point": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-5.0.0.tgz", + "integrity": "sha512-OVa3u9kkBbw7b8Xw5F9P+D/T9X+Z4+JruYVNapTjPYZYUznQ5YfWeFkOj606XYYW8yugTfC8Pj0hYqvi4ryAhA==", + "license": "MIT", + "dependencies": { + "get-east-asian-width": "^1.0.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/stack-utils": { + "version": "2.0.6", + "resolved": "https://registry.npmjs.org/stack-utils/-/stack-utils-2.0.6.tgz", + "integrity": "sha512-XlkWvfIm6RmsWtNJx+uqtKLS8eqFbxUg0ZzLXqY0caEy9l7hruX8IpiDnjsLavoBgqCCR71TqWO8MaXYheJ3RQ==", + "license": "MIT", + "dependencies": { + "escape-string-regexp": "^2.0.0" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/string-width": { + "version": "4.2.3", + "license": "MIT", + "dependencies": { + "emoji-regex": "^8.0.0", + "is-fullwidth-code-point": "^3.0.0", + "strip-ansi": "^6.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/strip-ansi": { + "version": "6.0.1", + "license": "MIT", + "dependencies": { + "ansi-regex": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/to-regex-range": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/to-regex-range/-/to-regex-range-5.0.1.tgz", + "integrity": "sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ==", + "license": "MIT", + "dependencies": { + "is-number": "^7.0.0" + }, + "engines": { + "node": ">=8.0" + } + }, + "node_modules/to-rotated": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/to-rotated/-/to-rotated-1.0.0.tgz", + "integrity": "sha512-KsEID8AfgUy+pxVRLsWp0VzCa69wxzUDZnzGbyIST/bcgcrMvTYoFBX/QORH4YApoD89EDuUovx4BTdpOn319Q==", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/tr46": { + "version": "0.0.3", + "resolved": "https://registry.npmjs.org/tr46/-/tr46-0.0.3.tgz", + "integrity": "sha512-N3WMsuqV66lT30CrXNbEjx4GEwlow3v6rr4mCcv6prnfwhS01rkgyFdjPNBYd9br7LpXV1+Emh01fHnq2Gdgrw==", + "license": "MIT" + }, + "node_modules/type-fest": { + "version": "4.39.1", + "resolved": "https://registry.npmjs.org/type-fest/-/type-fest-4.39.1.tgz", + "integrity": "sha512-uW9qzd66uyHYxwyVBYiwS4Oi0qZyUqwjU+Oevr6ZogYiXt99EOYtwvzMSLw1c3lYo2HzJsep/NB23iEVEgjG/w==", + "license": "(MIT OR CC0-1.0)", + "engines": { + "node": ">=16" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/typescript": { + "version": "5.8.3", + "dev": true, + "license": "Apache-2.0", + "bin": { + "tsc": "bin/tsc", + "tsserver": "bin/tsserver" + }, + "engines": { + "node": ">=14.17" + } + }, + "node_modules/undici-types": { + "version": "6.19.8", + "dev": true, + "license": "MIT" + }, + "node_modules/uuid": { + "version": "9.0.1", + "resolved": "https://registry.npmjs.org/uuid/-/uuid-9.0.1.tgz", + "integrity": "sha512-b+1eJOlsR9K8HJpow9Ok3fiWOWSIcIzXodvv0rQjVoOVNpWMpxf1wZNpt4y9h10odCNrqnYp1OBzRktckBe3sA==", + "funding": [ + "https://github.com/sponsors/broofa", + "https://github.com/sponsors/ctavan" + ], + "license": "MIT", + "bin": { + "uuid": "dist/bin/uuid" + } + }, + "node_modules/webidl-conversions": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-3.0.1.tgz", + "integrity": "sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ==", + "license": "BSD-2-Clause" + }, + "node_modules/whatwg-url": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-5.0.0.tgz", + "integrity": "sha512-saE57nupxk6v3HY35+jzBwYa0rKSy0XR8JSxZPwgLr7ys0IBzhGviA1/TUGJLmSVqs8pb9AnvICXEuOHLprYTw==", + "license": "MIT", + "dependencies": { + "tr46": "~0.0.3", + "webidl-conversions": "^3.0.0" + } + }, + "node_modules/widest-line": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/widest-line/-/widest-line-5.0.0.tgz", + "integrity": "sha512-c9bZp7b5YtRj2wOe6dlj32MK+Bx/M/d+9VB2SHM1OtsUHR0aV0tdP6DWh/iMt0kWi1t5g1Iudu6hQRNd1A4PVA==", + "license": "MIT", + "dependencies": { + "string-width": "^7.0.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/widest-line/node_modules/ansi-regex": { + "version": "6.1.0", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-6.1.0.tgz", + "integrity": "sha512-7HSX4QQb4CspciLpVFwyRe79O3xsIZDDLER21kERQ71oaPodF8jL725AgJMFAYbooIqolJoRLuM81SpeUkpkvA==", + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/ansi-regex?sponsor=1" + } + }, + "node_modules/widest-line/node_modules/emoji-regex": { + "version": "10.4.0", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-10.4.0.tgz", + "integrity": "sha512-EC+0oUMY1Rqm4O6LLrgjtYDvcVYTy7chDnM4Q7030tP4Kwj3u/pR6gP9ygnp2CJMK5Gq+9Q2oqmrFJAz01DXjw==", + "license": "MIT" + }, + "node_modules/widest-line/node_modules/string-width": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-7.2.0.tgz", + "integrity": "sha512-tsaTIkKW9b4N+AEj+SVA+WhJzV7/zMhcSu78mLKWSk7cXMOSHsBKFWUs0fWwq8QyK3MgJBQRX6Gbi4kYbdvGkQ==", + "license": "MIT", + "dependencies": { + "emoji-regex": "^10.3.0", + "get-east-asian-width": "^1.0.0", + "strip-ansi": "^7.1.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/widest-line/node_modules/strip-ansi": { + "version": "7.1.0", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-7.1.0.tgz", + "integrity": "sha512-iq6eVVI64nQQTRYq2KtEg2d2uU7LElhTJwsH4YzIHZshxlgZms/wIc4VoDQTlG/IvVIrBKG06CrZnp0qv7hkcQ==", + "license": "MIT", + "dependencies": { + "ansi-regex": "^6.0.1" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/strip-ansi?sponsor=1" + } + }, + "node_modules/wrap-ansi": { + "version": "7.0.0", + "license": "MIT", + "dependencies": { + "ansi-styles": "^4.0.0", + "string-width": "^4.1.0", + "strip-ansi": "^6.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/wrap-ansi?sponsor=1" + } + }, + "node_modules/ws": { + "version": "8.18.1", + "resolved": "https://registry.npmjs.org/ws/-/ws-8.18.1.tgz", + "integrity": "sha512-RKW2aJZMXeMxVpnZ6bck+RswznaxmzdULiBr6KY7XkTnW8uvt0iT9H5DkHUChXrc+uurzwa0rVI16n/Xzjdz1w==", + "license": "MIT", + "engines": { + "node": ">=10.0.0" + }, + "peerDependencies": { + "bufferutil": "^4.0.1", + "utf-8-validate": ">=5.0.2" + }, + "peerDependenciesMeta": { + "bufferutil": { + "optional": true + }, + "utf-8-validate": { + "optional": true + } + } + }, + "node_modules/y18n": { + "version": "5.0.8", + "license": "ISC", + "engines": { + "node": ">=10" + } + }, + "node_modules/yargs": { + "version": "17.7.2", + "license": "MIT", + "dependencies": { + "cliui": "^8.0.1", + "escalade": "^3.1.1", + "get-caller-file": "^2.0.5", + "require-directory": "^2.1.1", + "string-width": "^4.2.3", + "y18n": "^5.0.5", + "yargs-parser": "^21.1.1" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/yargs-parser": { + "version": "21.1.1", + "license": "ISC", + "engines": { + "node": ">=12" + } + }, + "node_modules/yoga-layout": { + "version": "3.2.1", + "resolved": "https://registry.npmjs.org/yoga-layout/-/yoga-layout-3.2.1.tgz", + "integrity": "sha512-0LPOt3AxKqMdFBZA3HBAt/t/8vIKq7VaQYbuA8WxCgung+p9TVyKRYdpvCb80HcdTN2NkbIKbhNwKUfm3tQywQ==", + "license": "MIT" + }, + "packages/cli": { + "name": "gemini-code-cli", + "version": "1.0.0", + "dependencies": { + "@google/genai": "^0.8.0", + "diff": "^7.0.0", + "dotenv": "^16.4.7", + "fast-glob": "^3.3.3", + "ink": "^5.2.0", + "ink-select-input": "^6.0.0", + "ink-spinner": "^5.0.0", + "ink-text-input": "^6.0.0", + "react": "^18.3.1", + "yargs": "^17.7.2" + }, + "devDependencies": { + "@types/diff": "^7.0.2", + "@types/dotenv": "^6.1.1", + "@types/node": "^20.11.24", + "@types/react": "^19.1.0", + "@types/yargs": "^17.0.32", + "typescript": "^5.3.3" + }, + "engines": { + "node": ">=18" + } + } + } +} diff --git a/package.json b/package.json new file mode 100644 index 00000000..afa76ce4 --- /dev/null +++ b/package.json @@ -0,0 +1,13 @@ +{ + "name": "gemini-code", + "version": "1.0.0", + "private": true, + "workspaces": [ + "packages/*" + ], + "scripts": { + "build": "npm run build --workspaces", + "test": "npm run test --workspaces", + "start": "npm run start --workspace=gemini-code-cli" + } +} diff --git a/packages/cli/package.json b/packages/cli/package.json new file mode 100644 index 00000000..79fa8883 --- /dev/null +++ b/packages/cli/package.json @@ -0,0 +1,38 @@ +{ + "name": "gemini-code-cli", + "version": "1.0.0", + "description": "Gemini Code CLI", + "type": "module", + "main": "dist/gemini.js", + "scripts": { + "build": "tsc", + "start": "node dist/gemini.js", + "debug": "node --inspect-brk dist/gemini.js" + }, + "files": [ + "dist" + ], + "dependencies": { + "@google/genai": "^0.8.0", + "diff": "^7.0.0", + "dotenv": "^16.4.7", + "fast-glob": "^3.3.3", + "ink": "^5.2.0", + "ink-select-input": "^6.0.0", + "ink-spinner": "^5.0.0", + "ink-text-input": "^6.0.0", + "react": "^18.3.1", + "yargs": "^17.7.2" + }, + "devDependencies": { + "@types/diff": "^7.0.2", + "@types/dotenv": "^6.1.1", + "@types/node": "^20.11.24", + "@types/react": "^19.1.0", + "@types/yargs": "^17.0.32", + "typescript": "^5.3.3" + }, + "engines": { + "node": ">=18" + } +} diff --git a/packages/cli/src/config/args.ts b/packages/cli/src/config/args.ts new file mode 100644 index 00000000..45f654db --- /dev/null +++ b/packages/cli/src/config/args.ts @@ -0,0 +1,34 @@ +import yargs from 'yargs/yargs'; +import { hideBin } from 'yargs/helpers'; + +export interface CliArgs { + target_dir: string | undefined; + _: (string | number)[]; // Captures positional arguments + // Add other expected args here if needed + // e.g., verbose?: boolean; +} + +export async function parseArguments(): Promise { + const argv = await yargs(hideBin(process.argv)) + .option('target_dir', { + alias: 'd', + type: 'string', + description: + 'The target directory for Gemini operations. Defaults to the current working directory.', + }) + .help() + .alias('h', 'help') + .strict() // Keep strict mode to error on unknown options + .parseAsync(); + + // Handle warnings for extra arguments here + if (argv._ && argv._.length > 0) { + console.warn( + `Warning: Additional arguments provided (${argv._.join(', ')}), but will be ignored.` + ); + } + + // Cast to the interface to ensure the structure aligns with expectations + // Use `unknown` first for safer casting if types might not perfectly match + return argv as unknown as CliArgs; +} \ No newline at end of file diff --git a/packages/cli/src/config/env.ts b/packages/cli/src/config/env.ts new file mode 100644 index 00000000..8a15fd6e --- /dev/null +++ b/packages/cli/src/config/env.ts @@ -0,0 +1,46 @@ +import * as dotenv from 'dotenv'; +import * as fs from 'node:fs'; +import * as path from 'node:path'; +import process from 'node:process'; + +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; + } + + const parentDir = path.dirname(currentDir); + if (parentDir === currentDir || !parentDir) { + return null; + } + currentDir = parentDir; + } +} + +export function loadEnvironment(): void { + // Start searching from the current working directory by default + const envFilePath = findEnvFile(process.cwd()); + + if (!envFilePath) { + return; + } + + dotenv.config({ path: envFilePath }); + + if (!process.env.GEMINI_API_KEY) { + console.error('Error: GEMINI_API_KEY environment variable is not set in the loaded .env file.'); + process.exit(1); + } +} + +export function getApiKey(): string { + loadEnvironment(); + const apiKey = process.env.GEMINI_API_KEY; + if (!apiKey) { + throw new Error('GEMINI_API_KEY is missing. Ensure loadEnvironment() was called successfully.'); + } + return apiKey; +} \ No newline at end of file diff --git a/packages/cli/src/core/GeminiClient.ts b/packages/cli/src/core/GeminiClient.ts new file mode 100644 index 00000000..0cdeed86 --- /dev/null +++ b/packages/cli/src/core/GeminiClient.ts @@ -0,0 +1,383 @@ +import { + GenerateContentConfig, GoogleGenAI, Part, Chat, + Type, + SchemaUnion, + PartListUnion, + Content +} from '@google/genai'; +import { getApiKey } from '../config/env.js'; +import { CoreSystemPrompt } from './prompts.js'; +import { type ToolCallEvent, type ToolCallConfirmationDetails, ToolCallStatus } from '../ui/types.js'; +import process from 'node:process'; +import { toolRegistry } from '../tools/tool-registry.js'; +import { ToolResult } from '../tools/ToolResult.js'; +import { getFolderStructure } from '../utils/getFolderStructure.js'; +import { GeminiEventType, GeminiStream } from './GeminiStream.js'; + +type ToolExecutionOutcome = { + callId: string; + name: string; + args: Record; + result?: ToolResult; + error?: any; + confirmationDetails?: ToolCallConfirmationDetails; +}; + +export class GeminiClient { + private ai: GoogleGenAI; + private defaultHyperParameters: GenerateContentConfig = { + temperature: 0, + topP: 1, + }; + private readonly MAX_TURNS = 100; + + constructor() { + const apiKey = getApiKey(); + this.ai = new GoogleGenAI({ apiKey }); + } + + public async startChat(): Promise { + const tools = toolRegistry.getToolSchemas(); + + // --- Get environmental information --- + const cwd = process.cwd(); + const today = new Date().toLocaleDateString(undefined, { // Use locale-aware date formatting + weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' + }); + const platform = process.platform; + + // --- Format information into a conversational multi-line string --- + const folderStructure = await getFolderStructure(cwd); + // --- End folder structure formatting ---) + const initialContextText = ` +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(); + + const initialContextPart: Part = { text: initialContextText }; + // --- End environmental information formatting --- + + try { + const chat = this.ai.chats.create({ + model: 'gemini-2.5-pro-preview-03-25',//'gemini-2.0-flash', + config: { + systemInstruction: CoreSystemPrompt, + ...this.defaultHyperParameters, + tools, + }, + history: [ + // --- Add the context as a single part in the initial user message --- + { + role: "user", + parts: [initialContextPart] // 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}`); + } + } + + public addMessageToHistory(chat: Chat, message: Content): void { + const history = chat.getHistory(); + history.push(message); + this.ai.chats + chat + } + + public async* sendMessageStream( + chat: Chat, + request: PartListUnion, + signal?: AbortSignal + ): GeminiStream { + let currentMessageToSend: PartListUnion = request; + let turns = 0; + + try { + while (turns < this.MAX_TURNS) { + turns++; + const resultStream = await chat.sendMessageStream({ message: currentMessageToSend }); + let functionResponseParts: Part[] = []; + let pendingToolCalls: Array<{ callId: string; name: string; args: Record }> = []; + let yieldedTextInTurn = false; + const chunksForDebug = []; + + for await (const chunk of resultStream) { + chunksForDebug.push(chunk); + if (signal?.aborted) { + const abortError = new Error("Request cancelled by user during stream."); + abortError.name = 'AbortError'; + throw abortError; + } + + const functionCalls = chunk.functionCalls; + if (functionCalls && functionCalls.length > 0) { + for (const call of functionCalls) { + const callId = call.id ?? `${call.name}-${Date.now()}-${Math.random().toString(16).slice(2)}`; + const name = call.name || 'undefined_tool_name'; + const args = (call.args || {}) as Record; + + pendingToolCalls.push({ callId, name, args }); + const evtValue: ToolCallEvent = { + type: 'tool_call', + status: ToolCallStatus.Pending, + callId, + name, + args, + resultDisplay: undefined, + confirmationDetails: undefined, + } + yield { + type: GeminiEventType.ToolCallInfo, + value: evtValue, + }; + } + } else { + const text = chunk.text; + if (text) { + yieldedTextInTurn = true; + yield { + type: GeminiEventType.Content, + value: text, + }; + } + } + } + + if (pendingToolCalls.length > 0) { + const toolPromises: Promise[] = pendingToolCalls.map(async pendingToolCall => { + const tool = toolRegistry.getTool(pendingToolCall.name); + + if (!tool) { + // Directly return error outcome if tool not found + return { ...pendingToolCall, error: new Error(`Tool "${pendingToolCall.name}" not found or is not registered.`) }; + } + + try { + const confirmation = await tool.shouldConfirmExecute(pendingToolCall.args); + if (confirmation) { + return { ...pendingToolCall, confirmationDetails: confirmation }; + } + } catch (error) { + return { ...pendingToolCall, error: new Error(`Tool failed to check tool confirmation: ${error}`) }; + } + + try { + const result = await tool.execute(pendingToolCall.args); + return { ...pendingToolCall, result }; + } catch (error) { + return { ...pendingToolCall, error: new Error(`Tool failed to execute: ${error}`) }; + } + }); + const toolExecutionOutcomes: ToolExecutionOutcome[] = await Promise.all(toolPromises); + + for (const executedTool of toolExecutionOutcomes) { + const { callId, name, args, result, error, confirmationDetails } = executedTool; + + if (error) { + const errorMessage = error?.message || String(error); + yield { + type: GeminiEventType.Content, + value: `[Error invoking tool ${name}: ${errorMessage}]`, + }; + } else 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}]`, + }; + } else { + const status = confirmationDetails ? ToolCallStatus.Confirming : ToolCallStatus.Invoked; + const evtValue: ToolCallEvent = { type: 'tool_call', status, callId, name, args, resultDisplay: result?.returnDisplay, confirmationDetails } + yield { + type: GeminiEventType.ToolCallInfo, + value: evtValue, + }; + } + } + + pendingToolCalls = []; + + const waitingOnConfirmations = toolExecutionOutcomes.filter(outcome => outcome.confirmationDetails).length > 0; + if (waitingOnConfirmations) { + // Stop processing content, wait for user. + // TODO: Kill token processing once API supports signals. + break; + } + + functionResponseParts = toolExecutionOutcomes.map((executedTool: ToolExecutionOutcome): Part => { + const { name, result, error } = executedTool; + const output = { "output": result?.llmContent }; + let toolOutcomePayload: any; + + if (error) { + const errorMessage = error?.message || String(error); + toolOutcomePayload = { error: `Invocation failed: ${errorMessage}` }; + console.error(`[Turn ${turns}] Critical error invoking tool ${name}:`, error); + } else if (result && typeof result === 'object' && result !== null && 'error' in result) { + toolOutcomePayload = output; + console.warn(`[Turn ${turns}] Tool ${name} returned an error structure:`, result.error); + } else { + toolOutcomePayload = output; + } + + return { + functionResponse: { + name: name, + id: executedTool.callId, + response: toolOutcomePayload, + }, + }; + }); + currentMessageToSend = functionResponseParts; + } else if (yieldedTextInTurn) { + 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') { + currentMessageToSend = { 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; + } + } else { + console.warn(`[Turn ${turns}] No text or function calls received from Gemini. Ending interaction.`); + 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) { + 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. + */ + public async generateJson(contents: Content[], schema: SchemaUnion): Promise { + try { + const result = await this.ai.models.generateContent({ + model: 'gemini-2.0-flash', // Using flash for potentially faster structured output + config: { + ...this.defaultHyperParameters, + systemInstruction: CoreSystemPrompt, + responseSchema: schema, + responseMimeType: 'application/json', + }, + contents: 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/GeminiStream.ts b/packages/cli/src/core/GeminiStream.ts new file mode 100644 index 00000000..28568306 --- /dev/null +++ b/packages/cli/src/core/GeminiStream.ts @@ -0,0 +1,22 @@ +import { ToolCallEvent } from "../ui/types.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; diff --git a/packages/cli/src/core/StreamingState.ts b/packages/cli/src/core/StreamingState.ts new file mode 100644 index 00000000..5aed1ff0 --- /dev/null +++ b/packages/cli/src/core/StreamingState.ts @@ -0,0 +1,4 @@ +export enum StreamingState { + Idle, + Responding, +} \ No newline at end of file diff --git a/packages/cli/src/core/agent.ts b/packages/cli/src/core/agent.ts new file mode 100644 index 00000000..e69de29b diff --git a/packages/cli/src/core/constants.ts b/packages/cli/src/core/constants.ts new file mode 100644 index 00000000..16ac74d1 --- /dev/null +++ b/packages/cli/src/core/constants.ts @@ -0,0 +1 @@ +export const MEMORY_FILE_NAME = 'GEMINI.md'; \ No newline at end of file diff --git a/packages/cli/src/core/geminiStreamProcessor.ts b/packages/cli/src/core/geminiStreamProcessor.ts new file mode 100644 index 00000000..12de49cb --- /dev/null +++ b/packages/cli/src/core/geminiStreamProcessor.ts @@ -0,0 +1,142 @@ +import { Part } from '@google/genai'; +import { HistoryItem } from '../ui/types.js'; +import { GeminiEventType, GeminiStream } from './GeminiStream.js'; +import { handleToolCallChunk, addErrorMessageToHistory } from './historyUpdater.js'; + +interface StreamProcessorParams { + stream: GeminiStream; + signal: AbortSignal; + setHistory: React.Dispatch>; + submitQuery: (query: Part) => Promise, + getNextMessageId: () => number; + addHistoryItem: (itemData: Omit, id: number) => void; + currentToolGroupIdRef: React.MutableRefObject; +} + +/** + * 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: any) { + if (renderTimeoutId) { // Ensure render loop stops on error + clearTimeout(renderTimeoutId); + renderTimeoutId = null; + } + // Delegate history update for error message + addErrorMessageToHistory(error, setHistory, getNextMessageId); + } finally { + isStreamComplete = true; // Signal stream end for render loop completion + if (renderTimeoutId) { + clearTimeout(renderTimeoutId); + renderTimeoutId = null; + } + + renderBufferedText(); // Force final render + } +}; \ No newline at end of file diff --git a/packages/cli/src/core/historyUpdater.ts b/packages/cli/src/core/historyUpdater.ts new file mode 100644 index 00000000..39eaca6a --- /dev/null +++ b/packages/cli/src/core/historyUpdater.ts @@ -0,0 +1,173 @@ +import { Part } from "@google/genai"; +import { toolRegistry } from "../tools/tool-registry.js"; +import { HistoryItem, IndividualToolCallDisplay, ToolCallEvent, ToolCallStatus, ToolConfirmationOutcome, ToolEditConfirmationDetails, ToolExecuteConfirmationDetails } from "../ui/types.js"; +import { ToolResultDisplay } from "../tools/ToolResult.js"; + +/** + * Processes a tool call chunk and updates the history state accordingly. + * Manages adding new tool groups or updating existing ones. + * Resides here as its primary effect is updating history based on tool events. + */ +export const handleToolCallChunk = ( + chunk: ToolCallEvent, + setHistory: React.Dispatch>, + submitQuery: (query: Part) => Promise, + getNextMessageId: () => number, + currentToolGroupIdRef: React.MutableRefObject +): void => { + const toolDefinition = toolRegistry.getTool(chunk.name); + const description = toolDefinition?.getDescription + ? toolDefinition.getDescription(chunk.args) + : ''; + const toolDisplayName = toolDefinition?.displayName ?? chunk.name; + let confirmationDetails = chunk.confirmationDetails; + if (confirmationDetails) { + const originalConfirmationDetails = confirmationDetails; + const historyUpdatingConfirm = async (outcome: ToolConfirmationOutcome) => { + originalConfirmationDetails.onConfirm(outcome); + + if (outcome === ToolConfirmationOutcome.Cancel) { + let resultDisplay: ToolResultDisplay | undefined; + if ('fileDiff' in originalConfirmationDetails) { + resultDisplay = { fileDiff: (originalConfirmationDetails as ToolEditConfirmationDetails).fileDiff }; + } else { + resultDisplay = `~~${(originalConfirmationDetails as ToolExecuteConfirmationDetails).command}~~`; + } + handleToolCallChunk({ ...chunk, status: ToolCallStatus.Canceled, confirmationDetails: undefined, resultDisplay, }, setHistory, submitQuery, getNextMessageId, currentToolGroupIdRef); + const functionResponse: Part = { + functionResponse: { + name: chunk.name, + response: { "error": "User rejected function call." }, + }, + } + await submitQuery(functionResponse); + } else { + const tool = toolRegistry.getTool(chunk.name) + if (!tool) { + throw new Error(`Tool "${chunk.name}" not found or is not registered.`); + } + + handleToolCallChunk({ ...chunk, status: ToolCallStatus.Invoked, resultDisplay: "Executing...", confirmationDetails: undefined }, setHistory, submitQuery, getNextMessageId, currentToolGroupIdRef); + + const result = await tool.execute(chunk.args); + + handleToolCallChunk({ ...chunk, status: ToolCallStatus.Invoked, resultDisplay: result.returnDisplay, confirmationDetails: undefined }, setHistory, submitQuery, getNextMessageId, currentToolGroupIdRef); + + const functionResponse: Part = { + functionResponse: { + name: chunk.name, + id: chunk.callId, + response: { "output": result.llmContent }, + }, + } + + await submitQuery(functionResponse); + } + } + + confirmationDetails = { + ...originalConfirmationDetails, + onConfirm: historyUpdatingConfirm, + }; + } + const toolDetail: IndividualToolCallDisplay = { + callId: chunk.callId, + name: toolDisplayName, + description, + resultDisplay: chunk.resultDisplay, + status: chunk.status, + confirmationDetails: confirmationDetails, + }; + + const activeGroupId = currentToolGroupIdRef.current; + setHistory(prev => { + if (chunk.status === ToolCallStatus.Pending) { + if (activeGroupId === null) { + // Start a new tool group + const newGroupId = getNextMessageId(); + currentToolGroupIdRef.current = newGroupId; + return [ + ...prev, + { id: newGroupId, type: 'tool_group', tools: [toolDetail] } as HistoryItem + ]; + } + + // Add to existing tool group + return prev.map(item => + item.id === activeGroupId && item.type === 'tool_group' + ? item.tools.some(t => t.callId === toolDetail.callId) + ? item // Tool already listed as pending + : { ...item, tools: [...item.tools, toolDetail] } + : item + ); + } + + // Update the status of a pending tool within the active group + if (activeGroupId === null) { + // Log if an invoked tool arrives without an active group context + console.warn("Received invoked tool status without an active tool group ID:", chunk); + return prev; + } + + return prev.map(item => + item.id === activeGroupId && item.type === 'tool_group' + ? { + ...item, + tools: item.tools.map(t => + t.callId === toolDetail.callId + ? { ...t, ...toolDetail, status: chunk.status } // Update details & status + : t + ) + } + : item + ); + }); +}; + +/** + * Appends an error or informational message to the history, attempting to attach + * it to the last non-user message or creating a new entry. + */ +export const addErrorMessageToHistory = ( + error: any, + setHistory: React.Dispatch>, + getNextMessageId: () => number +): void => { + const isAbort = error.name === 'AbortError'; + const errorType = isAbort ? 'info' : 'error'; + const errorText = isAbort + ? '[Request cancelled by user]' + : `[Error: ${error.message || 'Unknown error'}]`; + + setHistory(prev => { + const reversedHistory = [...prev].reverse(); + // Find the last message that isn't from the user to append the error/info to + const lastBotMessageIndex = reversedHistory.findIndex(item => item.type !== 'user'); + const originalIndex = lastBotMessageIndex !== -1 ? prev.length - 1 - lastBotMessageIndex : -1; + + if (originalIndex !== -1) { + // Append error to the last relevant message + return prev.map((item, index) => { + if (index === originalIndex) { + let baseText = ''; + // Determine base text based on item type + if (item.type === 'gemini') baseText = item.text ?? ''; + else if (item.type === 'tool_group') baseText = `Tool execution (${item.tools.length} calls)`; + else if (item.type === 'error' || item.type === 'info') baseText = item.text ?? ''; + // Safely handle potential undefined text + + const updatedText = (baseText + (baseText && !baseText.endsWith('\n') ? '\n' : '') + errorText).trim(); + // Reuse existing ID, update type and text + return { ...item, type: errorType, text: updatedText }; + } + return item; + }); + } else { + // No previous message to append to, add a new error item + return [ + ...prev, + { id: getNextMessageId(), type: errorType, text: errorText } as HistoryItem + ]; + } + }); +}; \ No newline at end of file diff --git a/packages/cli/src/core/prompts.ts b/packages/cli/src/core/prompts.ts new file mode 100644 index 00000000..9e1f994f --- /dev/null +++ b/packages/cli/src/core/prompts.ts @@ -0,0 +1,93 @@ +import { ReadFileTool } from "../tools/read-file.tool.js"; +import { TerminalTool } from "../tools/terminal.tool.js"; +import { MEMORY_FILE_NAME } from "./constants.js"; + +const contactEmail = 'ntaylormullen@google.com'; +export const CoreSystemPrompt = ` +You are an interactive CLI tool assistant specializing in software engineering tasks. Your primary goal is to help users safely and efficiently, adhering strictly to the following instructions and utilizing your available tools. + +# Core Directives & Safety Rules +1. **Explain Critical Commands:** Before executing any command (especially using \`${TerminalTool.Name}\`) that modifies the file system, codebase, or system state, you *must* provide a brief explanation of the command's purpose and potential impact. Prioritize user understanding and safety. +2. **NEVER Commit Changes:** Unless explicitly instructed by the user to do so, you MUST NOT commit changes to version control (e.g., git commit). This is critical for user control over their repository. +3. **Security First:** Always apply security best practices. Never introduce code that exposes, logs, or commits secrets, API keys, or other sensitive information. + +# Primary Workflow: Software Engineering Tasks +When requested to perform tasks like fixing bugs, adding features, refactoring, or explaining code, follow this sequence: +1. **Understand:** Analyze the user's request and the relevant codebase context. Check for project-specific information in \`${MEMORY_FILE_NAME}\` if it exists. Use search tools extensively (in parallel if independent) to understand file structures, existing code patterns, and conventions. +2. **Implement:** Use the available tools (e.g., file editing, \`${TerminalTool.Name}\`) to construct the solution, strictly adhering to the project's established conventions (see 'Following Conventions' below). + - If creating a new project rely on scaffolding commands do lay out the initial project structure (i.e. npm init ...) +3. **Verify (Tests):** If applicable and feasible, verify the changes using the project's testing procedures. Identify the correct test commands and frameworks by examining \`README\` files, \`${MEMORY_FILE_NAME}\`, build/package configuration (e.g., \`package.json\`), or existing test execution patterns. NEVER assume standard test commands. +4. **Verify (Standards):** VERY IMPORTANT: After making code changes, execute the project-specific linting and type-checking commands (e.g., \`npm run lint\`, \`ruff check .\`, \`tsc\`) that you have identified for this project (or obtained from the user). This ensures code quality and adherence to standards. If unsure about these commands, ask the user and propose adding them to \`${MEMORY_FILE_NAME}\` for future reference. + +# Key Operating Principles + +## Following Conventions +Rigorously adhere to existing project conventions when reading or modifying code. Analyze surrounding code and configuration first. +- **Libraries/Frameworks:** NEVER assume a library/framework is available or appropriate. Verify its established usage within the project (check imports, configuration files like \`package.json\`, \`Cargo.toml\`, \`requirements.txt\`, \`build.gradle\`, etc., or observe neighboring files) before employing it. +- **Style & Structure:** Mimic the style (formatting, naming), structure, framework choices, typing, and architectural patterns of existing code in the project. +- **Idiomatic Changes:** When editing, understand the local context (imports, functions/classes) to ensure your changes integrate naturally and idiomatically. +- **Comments:** Add code comments sparingly. Focus on *why* something is done, especially for complex logic, rather than *what* is done. Only add comments if necessary for clarity or if requested by the user. + +## Memory (${MEMORY_FILE_NAME}) +Utilize the \`${MEMORY_FILE_NAME}\` file in the current working directory for project-specific context: +- Reference stored commands, style preferences, and codebase notes when performing tasks. +- When you discover frequently used commands (build, test, lint, typecheck) or learn about specific project conventions or style preferences, proactively propose adding them to \`${MEMORY_FILE_NAME}\` for future sessions. + +## Tone and Style (CLI Interaction) +- **Concise & Direct:** Adopt a professional, direct, and concise tone suitable for a CLI environment. +- **Minimal Output:** Aim for fewer than 4 lines of text output (excluding tool use/code generation) per response whenever practical. Focus strictly on the user's query. +- **Clarity over Brevity (When Needed):** While conciseness is key, prioritize clarity for essential explanations (like pre-command warnings) or when seeking necessary clarification if a request is ambiguous. +- **No Chitchat:** Avoid conversational filler, preambles ("Okay, I will now..."), or postambles ("I have finished the changes..."). Get straight to the action or answer. +- **Formatting:** Use GitHub-flavored Markdown. Responses will be rendered in monospace. +- **Tools vs. Text:** Use tools for actions, text output *only* for communication. Do not add explanatory comments within tool calls or code blocks unless specifically part of the required code/command itself. +- **Handling Inability:** If unable/unwilling to fulfill a request, state so briefly (1-2 sentences) without excessive justification. Offer alternatives if appropriate. + +## Proactiveness +- **Act within Scope:** Fulfill the user's request thoroughly, including reasonable, directly implied follow-up actions. +- **Confirm Ambiguity/Expansion:** Do not take significant actions beyond the clear scope of the request without confirming with the user. If asked *how* to do something, explain first, don't just do it. +- **Stop After Action:** After completing a code modification or file operation, simply stop. Do not provide summaries unless asked. + +# Tool Usage +- **Search:** Prefer the Agent tool for file searching to optimize context usage. +- **Parallelism:** Execute multiple independent tool calls in parallel when feasible. +- **Command Execution:** Use the \`${TerminalTool.Name}\` tool for running shell commands, remembering the safety rule to explain modifying commands first. + +# Interaction Details +- **Help Command:** Use \`/help\` to display Gemini Code help. To get specific command/flag info, execute \`gemini -h\` via \`${TerminalTool.Name}\` and show the output. +- **Synthetic Messages:** Ignore system messages like \`++Request Cancelled++\`. Do not generate them. +- **Feedback:** Direct feedback to ${contactEmail}. + +# Examples (Illustrating Tone and Workflow) + +user: 1 + 2 +assistant: 3 + + + +user: is 13 a prime number? +assistant: true + + + +user: List files here. +assistant: [tool_call: execute_bash_command for 'ls -la']))] + + + +user: Refactor the auth logic in src/auth.py to use the 'requests' library. +assistant: Okay, I see src/auth.py currently uses 'urllib'. Before changing it, I need to check if 'requests' is already a project dependency. [tool_call: ${TerminalTool.Name} for grep 'requests', 'requirements.txt'] +(After confirming dependency or asking user to add it) +Okay, 'requests' is available. I will now refactor src/auth.py. +[tool_call: Uses read, edit tools following conventions] +(After editing) +[tool_call: Runs project-specific lint/typecheck commands found previously, e.g., ${TerminalTool.Name} for 'ruff', 'check', 'src/auth.py'] + + + +user: Delete the temp directory. +assistant: I can run \`rm -rf ./temp\`. This will permanently delete the directory and all its contents. Is it okay to proceed? + + +# Final Reminder +Your core function is efficient and safe assistance. Balance extreme conciseness with the crucial need for clarity, especially regarding safety and potential system modifications. Always prioritize user control and project conventions. Never make assumptions on the contents of files; instead use the ${ReadFileTool.Name} to ensure you aren't making too broad of assumptions. +`; \ No newline at end of file diff --git a/packages/cli/src/gemini.ts b/packages/cli/src/gemini.ts new file mode 100644 index 00000000..449f5096 --- /dev/null +++ b/packages/cli/src/gemini.ts @@ -0,0 +1,57 @@ +import React from 'react'; +import { render } from 'ink'; +import App from './ui/App.js'; +import { parseArguments } from './config/args.js'; +import { loadEnvironment } from './config/env.js'; +import { getTargetDirectory } from './utils/paths.js'; +import { toolRegistry } from './tools/tool-registry.js'; +import { LSTool } from './tools/ls.tool.js'; +import { ReadFileTool } from './tools/read-file.tool.js'; +import { GrepTool } from './tools/grep.tool.js'; +import { GlobTool } from './tools/glob.tool.js'; +import { EditTool } from './tools/edit.tool.js'; +import { TerminalTool } from './tools/terminal.tool.js'; +import { WriteFileTool } from './tools/write-file.tool.js'; + +async function main() { + // 1. Configuration + loadEnvironment(); + const argv = await parseArguments(); // Ensure args.ts imports printWarning from ui/display + const targetDir = getTargetDirectory(argv.target_dir); + + // 2. Configure tools + registerTools(targetDir); + + // 3. Render UI + render(React.createElement(App, { directory: targetDir })); +} + +// --- Global Entry Point --- +main().catch((error) => { + console.error('An unexpected critical error occurred:'); + if (error instanceof Error) { + console.error(error.message); + } else { + console.error(String(error)); + } + process.exit(1); +}); + +function registerTools(targetDir: string) { + 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 writeFileTool = new WriteFileTool(targetDir); + + toolRegistry.registerTool(lsTool); + toolRegistry.registerTool(readFileTool); + toolRegistry.registerTool(grepTool); + toolRegistry.registerTool(globTool); + toolRegistry.registerTool(editTool); + toolRegistry.registerTool(terminalTool); + toolRegistry.registerTool(writeFileTool); +} + diff --git a/packages/cli/src/tools/BaseTool.ts b/packages/cli/src/tools/BaseTool.ts new file mode 100644 index 00000000..1ab7fbf1 --- /dev/null +++ b/packages/cli/src/tools/BaseTool.ts @@ -0,0 +1,73 @@ +import type { FunctionDeclaration, Schema } from '@google/genai'; +import { ToolResult } from './ToolResult.js'; +import { Tool } from './Tool.js'; +import { ToolCallConfirmationDetails } from '../ui/types.js'; + +/** + * Base implementation for tools with common functionality + */ +export abstract class BaseTool implements Tool { + /** + * Creates a new instance of BaseTool + * @param name Internal name of the tool (used for API calls) + * @param displayName User-friendly display name of the tool + * @param description Description of what the tool does + * @param parameterSchema JSON Schema defining the parameters + */ + constructor( + public readonly name: string, + public readonly displayName: string, + public readonly description: string, + public readonly parameterSchema: Record + ) {} + + /** + * Function declaration schema computed from name, description, and parameterSchema + */ + get schema(): FunctionDeclaration { + return { + name: this.name, + description: this.description, + parameters: this.parameterSchema as Schema + }; + } + + /** + * Validates the parameters for the tool + * This is a placeholder implementation and should be overridden + * @param params Parameters to validate + * @returns An error message string if invalid, null otherwise + */ + invalidParams(params: TParams): string | null { + // Implementation would typically use a JSON Schema validator + // This is a placeholder that should be implemented by derived classes + return null; + } + + /** + * Gets a pre-execution description of the tool operation + * Default implementation that should be overridden by derived classes + * @param params Parameters for the tool execution + * @returns A markdown string describing what the tool will do + */ + getDescription(params: TParams): string { + return JSON.stringify(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. + */ + shouldConfirmExecute(params: TParams): Promise { + return Promise.resolve(false); + } + + /** + * Abstract method to execute the tool with the given parameters + * Must be implemented by derived classes + * @param params Parameters for the tool execution + * @returns Result of the tool execution + */ + abstract execute(params: TParams): Promise; +} \ No newline at end of file diff --git a/packages/cli/src/tools/Tool.ts b/packages/cli/src/tools/Tool.ts new file mode 100644 index 00000000..c1ef26ec --- /dev/null +++ b/packages/cli/src/tools/Tool.ts @@ -0,0 +1,57 @@ +import { FunctionDeclaration } from "@google/genai"; +import { ToolResult } from "./ToolResult.js"; +import { ToolCallConfirmationDetails } from "../ui/types.js"; + +/** + * Interface representing the base Tool functionality + */ +export interface Tool { + /** + * The internal name of the tool (used for API calls) + */ + name: string; + + /** + * The user-friendly display name of the tool + */ + displayName: string; + + /** + * Description of what the tool does + */ + description: string; + + /** + * Function declaration schema from @google/genai + */ + schema: FunctionDeclaration; + + /** + * Validates the parameters for the tool + * @param params Parameters to validate + * @returns An error message string if invalid, null otherwise + */ + invalidParams(params: TParams): string | null; + + /** + * Gets a pre-execution description of the tool operation + * @param params Parameters for the tool execution + * @returns A markdown string describing what the tool will do + * Optional for backward compatibility + */ + getDescription(params: TParams): string; + + /** + * Determines if the tool should prompt for confirmation before execution + * @param params Parameters for the tool execution + * @returns Whether execute should be confirmed. + */ + shouldConfirmExecute(params: TParams): Promise; + + /** + * Executes the tool with the given parameters + * @param params Parameters for the tool execution + * @returns Result of the tool execution + */ + execute(params: TParams): Promise; +} diff --git a/packages/cli/src/tools/ToolResult.ts b/packages/cli/src/tools/ToolResult.ts new file mode 100644 index 00000000..674e2fcb --- /dev/null +++ b/packages/cli/src/tools/ToolResult.ts @@ -0,0 +1,22 @@ +/** + * Standard tool result interface that all tools should implement + */ +export interface ToolResult { + /** + * Content meant to be included in LLM history. + * This should represent the factual outcome of the tool execution. + */ + llmContent: string; + + /** + * Markdown string for user display. + * This provides a user-friendly summary or visualization of the result. + */ + returnDisplay: ToolResultDisplay; +} + +export type ToolResultDisplay = string | FileDiff; + +export interface FileDiff { + fileDiff: string +} diff --git a/packages/cli/src/tools/edit.tool.ts b/packages/cli/src/tools/edit.tool.ts new file mode 100644 index 00000000..28199c24 --- /dev/null +++ b/packages/cli/src/tools/edit.tool.ts @@ -0,0 +1,369 @@ +import fs from 'fs'; +import path from 'path'; +import * as Diff from 'diff'; +import { SchemaValidator } from '../utils/schemaValidator.js'; +import { ToolResult } from './ToolResult.js'; +import { BaseTool } from './BaseTool.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'; + +/** + * 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; +} + +/** + * Result from the Edit tool + */ +export interface EditToolResult extends ToolResult { +} + +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. + */ +export class EditTool extends BaseTool { + private shouldAlwaysEdit = false; + private readonly rootDirectory: string; + + /** + * Creates a new instance of the EditTool + * @param rootDirectory Root directory to ground this tool in. + */ + constructor(rootDirectory: string) { + super( + 'replace', + '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' + } + ); + this.rootDirectory = path.resolve(rootDirectory); + } + + /** + * 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. + */ + 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); + } + + /** + * Validates the parameters for the Edit tool + * @param params Parameters to validate + * @returns True if parameters are valid, false otherwise + */ + 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; + } + + /** + * 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: any) { + if (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. + */ + async shouldConfirmExecute(params: EditToolParams): Promise { + if (this.shouldAlwaysEdit) { + return false; + } + + if (!this.validateParams(params)) { + console.error("[EditTool] Attempted confirmation with invalid parameters."); + return false; + } + + let calculatedEdit: CalculatedEdit; + try { + calculatedEdit = this.calculateEdit(params); + } catch (error) { + console.error(`Error calculating edit for confirmation: ${error instanceof Error ? error.message : String(error)}`); + return false; + } + + if (calculatedEdit.error) { + return false; + } + + const fileName = path.basename(params.file_path); + const fileDiff = Diff.createPatch( + fileName, + calculatedEdit.currentContent ?? '', + calculatedEdit.newContent, + 'Current', + 'Proposed', + { context: 3, ignoreWhitespace: true, } + ); + + const confirmationDetails: ToolEditConfirmationDetails = { + title: `Confirm Edit: ${shortenPath(makeRelative(params.file_path, this.rootDirectory))}`, + fileName, + fileDiff, + onConfirm: async (outcome: ToolConfirmationOutcome) => { + if (outcome === ToolConfirmationOutcome.ProceedAlways) { + this.shouldAlwaysEdit = true; + } + }, + }; + 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 + */ + 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 }); + } + } +} diff --git a/packages/cli/src/tools/glob.tool.ts b/packages/cli/src/tools/glob.tool.ts new file mode 100644 index 00000000..e6bf1747 --- /dev/null +++ b/packages/cli/src/tools/glob.tool.ts @@ -0,0 +1,227 @@ +import fs from 'fs'; +import path from 'path'; +import fg from 'fast-glob'; +import { SchemaValidator } from '../utils/schemaValidator.js'; +import { BaseTool } from './BaseTool.js'; +import { ToolResult } from './ToolResult.js'; +import { shortenPath, makeRelative } from '../utils/paths.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; +} + +/** + * Result from the GlobTool + */ +export interface GlobToolResult extends ToolResult { +} + +/** + * Implementation of the GlobTool that finds files matching patterns, + * sorted by modification time (newest first). + */ +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; + + /** + * Creates a new instance of the GlobTool + * @param rootDirectory Root directory to ground this tool in. All operations will be restricted to this directory. + */ + constructor(rootDirectory: string) { + 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' + } + ); + + // Set the root directory + this.rootDirectory = path.resolve(rootDirectory); + } + + /** + * 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 + */ + invalidParams(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: any) { + // Catch potential permission errors during sync checks + return `Error accessing search path: ${e.message}`; + } + + // 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 + } + + /** + * Gets a description of the glob operation. + * @param params Parameters for the glob operation. + * @returns A string describing the glob operation. + */ + 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; + } + + /** + * Executes the glob search with the given parameters + * @param params Parameters for the glob search + * @returns Result of the glob search + */ + async execute(params: GlobToolParams): Promise { + const validationError = this.invalidParams(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.` + }; + } + } +} \ No newline at end of file diff --git a/packages/cli/src/tools/grep.tool.ts b/packages/cli/src/tools/grep.tool.ts new file mode 100644 index 00000000..50a62c47 --- /dev/null +++ b/packages/cli/src/tools/grep.tool.ts @@ -0,0 +1,493 @@ +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 { ToolResult } from './ToolResult.js'; +import { BaseTool } from './BaseTool.js'; +import { SchemaValidator } from '../utils/schemaValidator.js'; +import { makeRelative, shortenPath } from '../utils/paths.js'; + +// --- Interfaces (kept separate for clarity) --- + +/** + * 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; +} + +/** + * Result from the GrepTool + */ +export interface GrepToolResult extends ToolResult { +} + +// --- GrepTool Class --- + +/** + * Implementation of the GrepTool that searches file contents using git grep, system grep, or JS fallback. + */ +export class GrepTool extends BaseTool { + private rootDirectory: string; + + /** + * Creates a new instance of the GrepTool + * @param rootDirectory Root directory to ground this tool in. All operations will be restricted to this directory. + */ + constructor(rootDirectory: string) { + 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' + } + ); + // 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 (err: any) { + if (err.code === 'ENOENT') { + throw new Error(`Path does not exist: ${targetPath}`); + } + throw new Error(`Failed to access path stats for ${targetPath}: ${err.message}`); + } + + return targetPath; + } + + /** + * Validates the parameters for the tool + * @param params Parameters to validate + * @returns An error message string if invalid, null otherwise + */ + invalidParams(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.invalidParams(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 (e) { + resolve(false); + } + }); + } + + /** + * 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 (err: any) { + if (err.code !== 'ENOENT') { + console.error(`Error checking for .git in ${currentPath}: ${err.message}`); + return false; + } + } + + if (currentPath === root) { + break; + } + currentPath = path.dirname(currentPath); + } + } catch (err: any) { + console.error(`Error traversing directory structure upwards from ${dirPath}: ${err instanceof Error ? err.message : String(err)}`); + } + 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: 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 + */ + 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; + } + + /** + * 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. + */ + 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: any) { + console.error(`GrepTool: git grep strategy failed: ${gitError.message}. 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: any) { + console.error(`GrepTool: System grep strategy failed: ${grepError.message}. 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: line, + }); + } + }); + } catch (readError: any) { + if (readError.code !== 'ENOENT') { + console.error(`GrepTool: Could not read or process file ${fileAbsolutePath}: ${readError.message}`); + } + } + } + + return allMatches; + + } catch (error: any) { + console.error(`GrepTool: Error during performGrepSearch (Strategy: ${strategyUsed}): ${error.message}`); + throw error; // Re-throw to be caught by the execute method's handler + } + } +} \ No newline at end of file diff --git a/packages/cli/src/tools/ls.tool.ts b/packages/cli/src/tools/ls.tool.ts new file mode 100644 index 00000000..f76c8472 --- /dev/null +++ b/packages/cli/src/tools/ls.tool.ts @@ -0,0 +1,306 @@ +import fs from 'fs'; +import path from 'path'; +import { BaseTool } from './BaseTool.js'; +import { SchemaValidator } from '../utils/schemaValidator.js'; +import { ToolResult } from './ToolResult.js'; +import { makeRelative, shortenPath } from '../utils/paths.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; +} + +/** + * Result from the LS tool + */ +export interface LSToolResult extends ToolResult { + /** + * List of file entries + */ + entries: FileEntry[]; + + /** + * The directory that was listed + */ + listedPath: string; + + /** + * Total number of entries found + */ + totalEntries: number; +} + +/** + * Implementation of the LS tool that lists directory contents + */ +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; + + /** + * Creates a new instance of the LSTool + * @param rootDirectory Root directory to ground this tool in. All operations will be restricted to this directory. + */ + constructor(rootDirectory: string) { + 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' + } + ); + + // Set the root directory + this.rootDirectory = path.resolve(rootDirectory); + } + + /** + * 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 tool + * @param params Parameters to validate + * @returns An error message string if invalid, null otherwise + */ + invalidParams(params: LSToolParams): string | null { + if (this.schema.parameters && !SchemaValidator.validate(this.schema.parameters as Record, params)) { + return "Parameters failed schema validation."; + } + + // Ensure path is absolute + if (!path.isAbsolute(params.path)) { + return `Path must be absolute: ${params.path}`; + } + + // Ensure path is within the root directory + if (!this.isWithinRoot(params.path)) { + return `Path must be within the root directory (${this.rootDirectory}): ${params.path}`; + } + + return null; + } + + /** + * 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 + */ + getDescription(params: LSToolParams): string { + const relativePath = makeRelative(params.path, this.rootDirectory); + return shortenPath(relativePath); + } + + /** + * Executes the LS operation with the given parameters + * @param params Parameters for the LS operation + * @returns Result of the LS operation + */ + async execute(params: LSToolParams): Promise { + const validationError = this.invalidParams(params); + if (validationError) { + return { + entries: [], + listedPath: params.path, + totalEntries: 0, + llmContent: `Error: Invalid parameters provided. Reason: ${validationError}`, + returnDisplay: "**Error:** Failed to execute tool." + }; + } + + try { + // Check if path exists + if (!fs.existsSync(params.path)) { + return { + entries: [], + listedPath: params.path, + totalEntries: 0, + llmContent: `Directory does not exist: ${params.path}`, + returnDisplay: `Directory does not exist` + }; + } + + // Check if path is a directory + const stats = fs.statSync(params.path); + if (!stats.isDirectory()) { + return { + entries: [], + listedPath: params.path, + totalEntries: 0, + llmContent: `Path is not a directory: ${params.path}`, + returnDisplay: `Path is not a directory` + }; + } + + // Read directory contents + const files = fs.readdirSync(params.path); + const entries: FileEntry[] = []; + + if (files.length === 0) { + return { + entries: [], + listedPath: params.path, + totalEntries: 0, + llmContent: `Directory is empty: ${params.path}`, + returnDisplay: `Directory is empty.` + }; + } + + // Process each entry + for (const file of files) { + // Skip if the file matches ignore patterns + 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) { + // Skip entries that can't be accessed + 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 { + entries, + listedPath: params.path, + totalEntries: entries.length, + llmContent: `Directory listing for ${params.path}:\n${directoryContent}`, + returnDisplay: `Found ${entries.length} item(s).` + }; + } catch (error) { + const errorMessage = `Error listing directory: ${error instanceof Error ? error.message : String(error)}`; + return { + entries: [], + listedPath: params.path, + totalEntries: 0, + llmContent: errorMessage, + returnDisplay: `**Error:** ${errorMessage}` + }; + } + } +} \ No newline at end of file diff --git a/packages/cli/src/tools/read-file.tool.ts b/packages/cli/src/tools/read-file.tool.ts new file mode 100644 index 00000000..7cbacd96 --- /dev/null +++ b/packages/cli/src/tools/read-file.tool.ts @@ -0,0 +1,296 @@ +import fs from 'fs'; +import path from 'path'; +import { ToolResult } from './ToolResult.js'; +import { BaseTool } from './BaseTool.js'; +import { SchemaValidator } from '../utils/schemaValidator.js'; +import { makeRelative, shortenPath } from '../utils/paths.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; +} + +/** + * Standardized result from the ReadFile tool + */ +export interface ReadFileToolResult extends ToolResult { +} + +/** + * Implementation of the ReadFile tool that reads files from the filesystem + */ +export class ReadFileTool extends BaseTool { + public 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; + + /** + * 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. + */ + constructor(rootDirectory: string) { + 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' + } + ); + + // Set the root directory + this.rootDirectory = path.resolve(rootDirectory); + } + + /** + * 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 ReadFile tool + * @param params Parameters to validate + * @returns True if parameters are valid, false otherwise + */ + invalidParams(params: ReadFileToolParams): string | null { + if (this.schema.parameters && !SchemaValidator.validate(this.schema.parameters as Record, params)) { + return "Parameters failed schema validation."; + } + + // 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}`; + } + + // Validate offset and limit if provided + 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'; + } + + 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 + */ + 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 (error) { + return false; + } + } + + /** + * Detects the type of file based on extension and content + * @param filePath Path to the file + * @returns File type description + */ + 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'; + } + + /** + * 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 + */ + async execute(params: ReadFileToolParams): Promise { + const validationError = this.invalidParams(params); + if (validationError) { + return { + llmContent: `Error: Invalid parameters provided. Reason: ${validationError}`, + returnDisplay: "**Error:** Failed to execute tool." + }; + } + + try { + // Check if file exists + if (!fs.existsSync(params.file_path)) { + return { + llmContent: `File not found: ${params.file_path}`, + returnDisplay: `File not found.`, + }; + } + + // Check if it's a directory + const stats = fs.statSync(params.file_path); + if (stats.isDirectory()) { + return { + llmContent: `Path is a directory, not a file: ${params.file_path}`, + returnDisplay: `File is directory.`, + }; + } + + // Detect file type + const fileType = this.detectFileType(params.file_path); + + // Handle binary files differently + if (fileType !== 'text') { + return { + llmContent: `Binary file: ${params.file_path} (${fileType})`, + returnDisplay: ``, + }; + } + + // Read and process text file + const content = fs.readFileSync(params.file_path, 'utf8'); + const lines = content.split('\n'); + + // Apply offset and limit + const startLine = params.offset || 0; + // Use the default max lines if no limit is provided + const endLine = params.limit + ? startLine + params.limit + : Math.min(startLine + ReadFileTool.DEFAULT_MAX_LINES, lines.length); + const selectedLines = lines.slice(startLine, endLine); + + // Format with line numbers and handle line truncation + let truncated = false; + const formattedLines = selectedLines.map((line) => { + // Calculate actual line number (1-based) + // Truncate long lines + let processedLine = line; + if (line.length > ReadFileTool.MAX_LINE_LENGTH) { + processedLine = line.substring(0, ReadFileTool.MAX_LINE_LENGTH) + '... [truncated]'; + truncated = true; + } + + return processedLine; + }); + + // Check if content was truncated due to line limit or max lines limit + const contentTruncated = (endLine < lines.length) || truncated; + + // Create llmContent with truncation info if needed + 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 ${params.file_path}: ${errorMsg}`, + returnDisplay: `Failed to read file: ${errorMsg}`, + }; + } + } +} \ No newline at end of file diff --git a/packages/cli/src/tools/terminal.tool.ts b/packages/cli/src/tools/terminal.tool.ts new file mode 100644 index 00000000..ae33c107 --- /dev/null +++ b/packages/cli/src/tools/terminal.tool.ts @@ -0,0 +1,960 @@ +import { spawn, SpawnOptions, ChildProcessWithoutNullStreams, exec } from 'child_process'; // Added 'exec' +import path from 'path'; +import os from 'os'; +import crypto from 'crypto'; +import { promises as fs } from 'fs'; // Added fs.promises +import { BaseTool } from './BaseTool.js'; // Adjust path as needed +import { ToolResult } from './ToolResult.js'; // Adjust path as needed +import { SchemaValidator } from '../utils/schemaValidator.js'; // Adjust path as needed +import { ToolCallConfirmationDetails, ToolConfirmationOutcome, ToolExecuteConfirmationDetails } from '../ui/types.js'; // Adjust path as needed +import { GeminiClient } from '../core/GeminiClient.js'; +import { SchemaUnion, Type } from '@google/genai'; +import { BackgroundTerminalAnalyzer } from '../utils/BackgroundTerminalAnalyzer.js'; + +// --- Interfaces --- +export interface TerminalToolParams { + command: string; + description?: string; + timeout?: number; + runInBackground?: boolean; +} + +export interface TerminalToolResult extends ToolResult { + // Add specific fields if needed for structured output from polling/LLM + // finalStdout?: string; + // finalStderr?: string; + // llmAnalysis?: string; +} + +// --- 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_INTERVAL_MS = 5000; // 5 seconds interval for checking background process status +const BACKGROUND_POLL_TIMEOUT_MS = 30000; // 30 seconds total polling time for background process status + +const BANNED_COMMAND_ROOTS = [ + // Session/flow control (excluding cd) + 'alias', 'bg', 'command', 'declare', 'dirs', 'disown', 'enable', 'eval', 'exec', + 'exit', 'export', 'fc', 'fg', 'getopts', 'hash', 'history', 'jobs', 'kill', 'let', + 'local', 'logout', 'popd', 'printf', 'pushd', /* 'pwd' is safe */ 'read', 'readonly', 'set', + 'shift', 'shopt', 'source', 'suspend', 'test', 'times', 'trap', 'type', 'typeset', + 'ulimit', 'umask', 'unalias', 'unset', 'wait', + // Network commands + 'curl', 'wget', 'nc', 'telnet', 'ssh', 'scp', 'ftp', 'sftp', + 'http', 'https', 'ftp', 'rsync', + // Browsers/GUI launchers + 'lynx', 'w3m', 'links', 'elinks', 'httpie', 'xh', 'http-prompt', + 'chrome', 'firefox', 'safari', 'edge', 'xdg-open', 'open' +]; + + +// --- Helper Type for Command Queue --- +interface QueuedCommand { + params: TerminalToolParams; + resolve: (result: TerminalToolResult) => void; + reject: (error: Error) => void; + confirmationDetails: ToolExecuteConfirmationDetails | false; // Kept for potential future use +} + +/** + * Implementation of the terminal tool that executes shell commands within a persistent session. + */ +export class TerminalTool extends BaseTool { + public static Name: string = 'execute_bash_command'; + + private readonly rootDirectory: string; + private readonly outputLimit: number; + private bashProcess: ChildProcessWithoutNullStreams | null = null; + private currentCwd: string; + private isExecuting: boolean = false; + private commandQueue: QueuedCommand[] = []; + private currentCommandCleanup: (() => void) | null = null; + private shouldAlwaysExecuteCommands: Map = new Map(); // Track confirmation per root command + private shellReady: Promise; + private resolveShellReady: (() => void) | undefined; // Definite assignment assertion + private rejectShellReady: ((reason?: any) => void) | undefined; // Definite assignment assertion + private readonly backgroundTerminalAnalyzer: BackgroundTerminalAnalyzer; + + + constructor(rootDirectory: string, 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: +* Starts in project root: '${path.basename(rootDirectory)}'. Current Directory starts as: ${rootDirectory} (will update based on 'cd' commands). +* Persistent State: Environment variables and the current working directory (\`pwd\`) persist between calls to this tool. +* **Execution Modes:** + * **Foreground (default):** Waits for the command to complete. Captures stdout, stderr, and exit code. Output is truncated if it exceeds ${outputLimit} characters. + * **Background (\`runInBackground: true\`):** Appends \`&\` to the command and redirects its output to temporary files. Returns *after* the command is launched, providing the Process ID (PID) and launch status. Subsequently, the tool **polls** for the background process status for up to ${BACKGROUND_POLL_TIMEOUT_MS / 1000} seconds. Once the process finishes or polling times out, the tool reads the captured stdout/stderr from the temporary files, runs an internal LLM analysis on the output, cleans up the files, and returns the final status, captured output, and analysis. +* Timeout: Optional timeout per 'execute' call (default: ${DEFAULT_TIMEOUT_MS / 60000} min, max override: ${MAX_TIMEOUT_OVERRIDE_MS / 60000} min for foreground). Background *launch* has a fixed shorter timeout (${BACKGROUND_LAUNCH_TIMEOUT_MS / 1000}s) for the launch attempt itself. Background *polling* has its own timeout (${BACKGROUND_POLL_TIMEOUT_MS / 1000}s). Timeout attempts SIGINT for foreground commands. + +Usage Guidance & Restrictions: + +1. **Directory/File Verification (IMPORTANT):** + * BEFORE executing commands that create files or directories (e.g., \`mkdir foo/bar\`, \`touch new/file.txt\`, \`git clone ...\`), use the dedicated File System tool (e.g., 'list_directory') to verify the target parent directory exists and is the correct location. + * Example: Before running \`mkdir foo/bar\`, first use the File System tool to check that \`foo\` exists in the current directory (\`${rootDirectory}\` initially, check current CWD if it changed). + +2. **Use Specialized Tools (CRITICAL):** + * Do NOT use this tool for filesystem searching (\`find\`, \`grep\`). Use the dedicated Search tool instead. + * Do NOT use this tool for reading files (\`cat\`, \`head\`, \`tail\`, \`less\`, \`more\`). Use the dedicated File Reader tool instead. + * Do NOT use this tool for listing files (\`ls\`). Use the dedicated File System tool ('list_directory') instead. Relying on this tool's output for directory structure is unreliable due to potential truncation and lack of structured data. + +3. **Security & Banned Commands:** + * Certain commands are banned for security (e.g., network: ${BANNED_COMMAND_ROOTS.filter(c => ['curl', 'wget', 'ssh'].includes(c)).join(', ')}; session: ${BANNED_COMMAND_ROOTS.filter(c => ['exit', 'export', 'kill'].includes(c)).join(', ')}; etc.). The full list is extensive. + * If you attempt a banned command, this tool will return an error explaining the restriction. You MUST relay this error clearly to the user. + +4. **Command Execution Notes:** + * Chain multiple commands using shell operators like ';' or '&&'. Do NOT use newlines within the 'command' parameter string itself (newlines are fine inside quoted arguments). + * The shell's current working directory is tracked internally. While \`cd\` is permitted if the user explicitly asks or it's necessary for a workflow, **strongly prefer** using absolute paths or paths relative to the *known* current working directory to avoid errors. Check the '(Executed in: ...)' part of the previous command's output for the CWD. + * Good example (if CWD is /workspace/project): \`pytest tests/unit\` or \`ls /workspace/project/data\` + * Less preferred: \`cd tests && pytest unit\` (only use if necessary or requested) + +5. **Background Tasks (\`runInBackground: true\`):** + * Use this for commands that are intended to run continuously (e.g., \`node server.js\`, \`npm start\`). + * The tool initially returns success if the process *launches* successfully, along with its PID. + * **Polling & Final Result:** The tool then monitors the process. The *final* result (delivered after polling completes or times out) will include: + * The final status (completed or timed out). + * The complete stdout and stderr captured in temporary files (truncated if necessary). + * An LLM-generated analysis/summary of the output. + * 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: { + command: { + description: `The exact bash command or sequence of commands (using ';' or '&&') to execute. Must adhere to usage guidelines. Example: 'npm install && npm run build'`, + type: 'string' + }, + description: { + description: `Optional: A brief, user-centric explanation of what the command does and why it's being run. Used for logging and confirmation prompts. Example: 'Install project dependencies'`, + type: 'string' + }, + timeout: { + description: `Optional execution time limit in milliseconds for FOREGROUND commands. Max ${MAX_TIMEOUT_OVERRIDE_MS}ms (${MAX_TIMEOUT_OVERRIDE_MS / 60000} min). Defaults to ${DEFAULT_TIMEOUT_MS}ms (${DEFAULT_TIMEOUT_MS / 60000} min) if not specified or invalid. Ignored if 'runInBackground' is true.`, + type: 'number' + }, + runInBackground: { + description: `If true, execute the command in the background using '&'. Defaults to false. Use for servers or long tasks.`, + type: 'boolean', + } + }, + required: ['command'] + }; + + + super( + TerminalTool.Name, + toolDisplayName, + toolDescription, + toolParameterSchema + ); + + this.rootDirectory = path.resolve(rootDirectory); + this.currentCwd = this.rootDirectory; + this.outputLimit = outputLimit; + this.shellReady = new Promise((resolve, reject) => { + this.resolveShellReady = resolve; + this.rejectShellReady = reject; + }); + this.backgroundTerminalAnalyzer = new BackgroundTerminalAnalyzer(); + + this.initializeShell(); + } + + // --- Shell Initialization and Management (largely unchanged) --- + private initializeShell() { + if (this.bashProcess) { + try { + this.bashProcess.kill(); + } catch (e) { /* 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(bashPath, ['-s'], spawnOptions) as ChildProcessWithoutNullStreams; + this.currentCwd = this.rootDirectory; // Reset CWD on restart + + this.bashProcess.on('error', (err) => { + console.error('Persistent Bash Error:', err); + this.rejectShellReady?.(err); // Use optional chaining as reject might be cleared + 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; + }); + this.clearQueue(new Error(`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 + } else if (!this.bashProcess) { + // Error likely already handled by 'error' or 'close' event + } else { + // Process was killed during init? + this.rejectShellReady?.(new Error("Shell killed during initialization")); + } + }, 1000); // Increase readiness check timeout slightly + + } catch (error: any) { + console.error("Failed to spawn persistent bash:", error); + this.rejectShellReady?.(error); // Use optional chaining + this.bashProcess = null; + this.clearQueue(new Error(`Failed to spawn persistent bash: ${error.message}`)); + } + } + + // --- Parameter Validation (unchanged) --- + invalidParams(params: TerminalToolParams): string | null { + if (!SchemaValidator.validate(this.parameterSchema as Record, params)) { + return `Parameters failed schema validation.`; + } + + const commandOriginal = params.command.trim(); + if (!commandOriginal) { + return "Command cannot be empty."; + } + const commandLower = commandOriginal.toLowerCase(); + 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]+/, '').split(/[\/\\]/).pop() || part.replace(/^[^a-zA-Z0-9]+/, ''); + if (cleanPart && BANNED_COMMAND_ROOTS.includes(cleanPart.toLowerCase())) { + 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.'; + } + + // Relax the absolute path restriction slightly if needed, but generally good practice + // const firstCommandPart = commandParts[0]; + // if (firstCommandPart && (firstCommandPart.startsWith('/') || firstCommandPart.startsWith('\\'))) { + // return 'Executing commands via absolute paths (starting with \'/\' or \'\\\') is restricted. Use commands available in PATH or relative paths.'; + // } + + return null; // Parameters are valid + } + + // --- Description and Confirmation (unchanged) --- + getDescription(params: TerminalToolParams): string { + return params.description || params.command; + } + + async shouldConfirmExecute(params: TerminalToolParams): Promise { + const rootCommand = params.command.trim().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, + rootCommand: rootCommand, + description: `Execute in '${this.currentCwd}':\n${description}`, + onConfirm: async (outcome: ToolConfirmationOutcome) => { + if (outcome === ToolConfirmationOutcome.ProceedAlways) { + this.shouldAlwaysExecuteCommands.set(rootCommand, true); + } + }, + }; + return confirmationDetails; + } + + // --- Command Execution and Queueing (unchanged structure) --- + async execute(params: TerminalToolParams): Promise { + const validationError = this.invalidParams(params); + if (validationError) { + return { + llmContent: `Command rejected: ${params.command}\nReason: ${validationError}`, + returnDisplay: `Error: ${validationError}`, + }; + } + + // Assume confirmation is handled before calling execute + + return new Promise((resolve) => { + const queuedItem: QueuedCommand = { + params, + resolve, // Resolve outer promise + 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 + }; + this.commandQueue.push(queuedItem); + // Ensure queue processing is triggered *after* adding the item + setImmediate(() => this.triggerQueueProcessing()); + }); + } + + private async triggerQueueProcessing(): Promise { + 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) + 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 + } catch (error: any) { + console.error(`Error executing command "${params.command}":`, error); + reject(error); // Use the specific command's reject handler + } 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: TerminalToolResult | PromiseLike) => void; // To pass to polling + let originalReject: (reason?: any) => void; + + const promise = new Promise((resolve, reject) => { + originalResolve = resolve; // Assign outer scope resolve + originalReject = reject; // Assign outer scope 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 --- + 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: any) { + // If temp dir setup fails, reject immediately + return reject(new Error(`Failed to determine temporary directory: ${err.message}`)); + } + } + // --- End Temp File Init --- + + let stdoutBuffer = ''; // For launch output + let stderrBuffer = ''; // For launch output + let commandOutputStarted = false; + let exitCode: number | null = null; + let backgroundPid: number | null = null; // Store PID + 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 + 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 + + 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 + } catch (e: any) { 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 + if (isBackgroundTask && tempStdoutPath && tempStderrPath) { + this.cleanupTempFiles(tempStdoutPath, tempStderrPath).catch(err => { + console.warn(`Error cleaning up temp files on timeout: ${err.message}`); + }); + } + + // 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) { + commandOutputStarted = true; + dataToProcess = dataToProcess.substring(startIndex + startDelimiter.length); + } else { + return false; // Still waiting for start delimiter + } + } + + // 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+)/); + if (pidMatch?.[1]) { + backgroundPid = parseInt(pidMatch[1], 10); + const pidEndIndex = pidIndex + pidDelimiter.length + pidMatch[1].length; + const beforePid = dataToProcess.substring(0, pidIndex); + if (isStderr) stderrBuffer += beforePid; 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; + dataToProcess = dataToProcess.substring(pidIndex + pidDelimiter.length); + } + } + + + // Process Exit Code delimiter + const exitCodeIndex = dataToProcess.indexOf(exitCodeDelimiter); + if (exitCodeIndex !== -1) { + const exitCodeMatch = dataToProcess.substring(exitCodeIndex + exitCodeDelimiter.length).match(/^(\d+)/); + if (exitCodeMatch?.[1]) { + exitCode = parseInt(exitCodeMatch[1], 10); + const beforeExitCode = dataToProcess.substring(0, exitCodeIndex); + if (isStderr) stderrBuffer += beforeExitCode; else stdoutBuffer += beforeExitCode; + dataToProcess = dataToProcess.substring(exitCodeIndex + exitCodeDelimiter.length + exitCodeMatch[1].length); + } else { + const beforeExitCode = dataToProcess.substring(0, exitCodeIndex); + if (isStderr) stderrBuffer += beforeExitCode; else stdoutBuffer += beforeExitCode; + dataToProcess = dataToProcess.substring(exitCodeIndex + exitCodeDelimiter.length); + } + } + + // Process End delimiter + const endDelimiterIndex = dataToProcess.indexOf(endDelimiter); + if (endDelimiterIndex !== -1) { + receivedEndDelimiter = true; + const beforeEndDelimiter = dataToProcess.substring(0, endDelimiterIndex); + if (isStderr) stderrBuffer += beforeEndDelimiter; else stdoutBuffer += beforeEndDelimiter; + // Consume delimiter and potentially the exit code echoed after it + const afterEndDelimiter = dataToProcess.substring(endDelimiterIndex + endDelimiter.length); + const exitCodeEchoMatch = afterEndDelimiter.match(/^(\d+)/); + dataToProcess = exitCodeEchoMatch ? 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 + } + + return false; // More data or delimiters expected + }; + + // 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: any, onStderrData: any }) => { + 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 => { + console.warn(`Error cleaning up temp files for superseded command: ${err.message}`); + }); + } + 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 --- + if (exitCode === null) { + console.error(`CRITICAL: Command "${params.command}" (background: ${isBackgroundTask}) finished delimiter processing but exitCode is null.`); + const errorMode = isBackgroundTask ? 'Background Launch' : 'Foreground'; + if (isBackgroundTask && tempStdoutPath && tempStderrPath) { + 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 { + const latestCwd = await this.getCurrentShellCwd(); + if (this.currentCwd !== latestCwd) { + this.currentCwd = latestCwd; + } + } catch (e: any) { + if (exitCode === 0) { // Only warn if the command itself succeeded + cwdUpdateError = `\nWarning: Failed to verify/update current working directory after command: ${e.message}`; + console.error("Failed to update CWD after successful command:", e); + } + } + } + } + // --- 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 + ); + // 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" : `Launch failed (Exit Code: ${exitCode})`; + 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 + }); + // --- 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(`Error cleaning up temp files on attach failure: ${err.message}`); + }); + } + return originalReject(new Error("Bash process lost or killed before listeners could be attached.")); + } + // 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) => { + if (err) { + console.error(`Error writing command "${params.command}" to bash stdin (callback):`, err); + // Store listeners before calling cleanup + const listenersToClean = { onStdoutData, onStderrData }; + cleanupListeners(listenersToClean); // Attempt cleanup + if (isBackgroundTask && tempStdoutPath && tempStderrPath) { + this.cleanupTempFiles(tempStdoutPath, tempStderrPath).catch(e => console.warn(`Cleanup failed: ${e.message}`)); + } + originalReject(new Error(`Shell stdin write error: ${err.message}. Command likely did not execute.`)); + } + }); + } else { + throw new Error("Shell stdin is not writable or process closed when attempting to write command."); + } + } catch (e: any) { + console.error(`Error writing command "${params.command}" to bash stdin (sync):`, e); + // Store listeners before calling cleanup + const listenersToClean = { onStdoutData, onStderrData }; + cleanupListeners(listenersToClean); // Attempt cleanup + if (isBackgroundTask && tempStdoutPath && tempStderrPath) { + this.cleanupTempFiles(tempStdoutPath, tempStderrPath).catch(err => console.warn(`Cleanup failed: ${err.message}`)); + } + originalReject(new Error(`Shell stdin write exception: ${e.message}. Command likely did not execute.`)); + } + }); // End of main promise constructor + + 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: TerminalToolResult | PromiseLike) => void // The original promise's resolve + ): 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, tempStdoutPath, tempStderrPath, command); + if (status === 'Unknown') + llmAnalysis = `LLM analysis failed: ${summary}`; + else + llmAnalysis = summary; + + } catch (llmError: any) { + console.error(`LLM analysis failed for PID ${pid} command "${command}":`, llmError); + llmAnalysis = `LLM analysis failed: ${llmError.message}`; // Include error in analysis placeholder + } + // --- End LLM Call --- + + try { + finalStdout = await fs.readFile(tempStdoutPath, 'utf-8'); + finalStderr = await fs.readFile(tempStderrPath, 'utf-8'); + } catch (err: any) { + console.error(`Error reading temp output files for PID ${pid}:`, err); + fileReadError = `\nWarning: Failed to read temporary output files (${err.message}). 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): Promise { + const unlinkQuietly = async (filePath: string | null) => { + if (!filePath) return; + try { + await fs.unlink(filePath); + } catch (err: any) { + // Ignore errors like file not found (it might have been deleted already or failed to create) + if (err.code !== 'ENOENT') { + console.warn(`Failed to delete temporary file '${filePath}': ${err.message}`); + } else { + } + } + }; + // 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 (!this.bashProcess || !this.bashProcess.stdin?.writable || this.bashProcess.killed) { + return reject(new Error("Shell not running, stdin not writable, or killed for PWD check")); + } + + 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 pwdTimeoutId: NodeJS.Timeout | null = null; + let finished = false; // Prevent double resolution/rejection + + const cleanupPwdListeners = (err?: Error) => { + if (finished) return; // Already handled + 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 + 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 + const dataStr = data.toString(); + const delimiterIndex = dataStr.indexOf(pwdDelimiter); + if (delimiterIndex !== -1) { + pwdOutput += dataStr.substring(0, delimiterIndex); + cleanupPwdListeners(); // Resolve successfully + } else { + pwdOutput += dataStr; + } + }; + + onPwdError = (data: Buffer) => { + if (!onPwdError) return; // Listener removed + 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(`Stderr received during pwd check: ${this.truncateOutput(dataStr, 100)}`)); + }; + + // 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 + 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}`)); + } + }); + } else { + throw new Error("Shell stdin not writable for pwd command."); + } + } catch (e: any) { + console.error("Exception writing pwd command:", e); + cleanupPwdListeners(new Error(`Exception writing pwd command: ${e.message}`)); + } + }); + } + + // --- Truncate Output (unchanged) --- + private truncateOutput(output: string, limit?: number): string { + const effectiveLimit = limit ?? this.outputLimit; + if (output.length > effectiveLimit) { + return output.substring(0, effectiveLimit) + `\n... [Output truncated at ${effectiveLimit} characters]`; + } + return output; + } + + // --- Clear Queue (unchanged) --- + private clearQueue(error: Error) { + const queuedCount = this.commandQueue.length; + const queue = this.commandQueue; + this.commandQueue = []; + queue.forEach(({ resolve, params }) => resolve({ + llmContent: `Command cancelled: ${params.command}\nReason: ${error.message}`, + returnDisplay: `Command Cancelled: ${error.message}` + })); + } + + // --- 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.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 pid = proc.pid; + this.bashProcess = null; // Nullify reference immediately + + 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 + setTimeout(() => { + if (!proc.killed) { + proc.kill('SIGKILL'); // Force kill if needed + } + }, 500); // 500ms grace period + + } catch (e: any) { + // Catch errors if process already exited etc. + console.warn(`Error trying to kill bash process PID: ${pid}: ${e.message}`); + } + } else { + } + + // 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 \ No newline at end of file diff --git a/packages/cli/src/tools/tool-registry.ts b/packages/cli/src/tools/tool-registry.ts new file mode 100644 index 00000000..f5d661e6 --- /dev/null +++ b/packages/cli/src/tools/tool-registry.ts @@ -0,0 +1,58 @@ +import { ToolListUnion, FunctionDeclaration } from '@google/genai'; +import { Tool } from './Tool.js'; +import { ToolResult } from './ToolResult.js'; + +class ToolRegistry { + private tools: Map = new Map(); + + /** + * Registers a tool definition. + * @param tool - The tool object containing schema and execution logic. + */ + registerTool(tool: Tool): void { + if (this.tools.has(tool.name)) { + // Decide on behavior: throw error, log warning, or allow overwrite + console.warn(`Tool with name "${tool.name}" is already registered. Overwriting.`); + } + this.tools.set(tool.name, tool); + } + + /** + * Retrieves the list of tool schemas in the format required by Gemini. + * @returns A ToolListUnion containing the function declarations. + */ + getToolSchemas(): ToolListUnion { + const declarations: FunctionDeclaration[] = []; + this.tools.forEach(tool => { + declarations.push(tool.schema); + }); + + // Return Gemini's expected format. Handle the case of no tools. + 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 }]; + } + + /** + * Optional: Get a list of registered tool names. + */ + listAvailableTools(): string[] { + return Array.from(this.tools.keys()); + } + + /** + * Get the definition of a specific tool. + */ + getTool(name: string): Tool | undefined { + return this.tools.get(name); + } +} + +// Export a singleton instance of the registry +export const toolRegistry = new ToolRegistry(); \ No newline at end of file diff --git a/packages/cli/src/tools/write-file.tool.ts b/packages/cli/src/tools/write-file.tool.ts new file mode 100644 index 00000000..e832357b --- /dev/null +++ b/packages/cli/src/tools/write-file.tool.ts @@ -0,0 +1,201 @@ +import fs from 'fs'; +import path from 'path'; +import { ToolResult } from './ToolResult.js'; +import { BaseTool } from './BaseTool.js'; +import { SchemaValidator } from '../utils/schemaValidator.js'; +import { makeRelative, shortenPath } from '../utils/paths.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; +} + +/** + * Standardized result from the WriteFile tool + */ +export interface WriteFileToolResult extends ToolResult { +} + +/** + * Implementation of the WriteFile tool that writes files to the filesystem + */ +export class WriteFileTool extends BaseTool { + public static readonly Name: string = 'write_file'; + private shouldAlwaysWrite = false; + + /** + * 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 WriteFileTool + * @param rootDirectory Root directory to ground this tool in. All operations will be restricted to this directory. + */ + constructor(rootDirectory: string) { + super( + WriteFileTool.Name, + 'WriteFile', + 'Writes content to a specified file in the local filesystem.', + { + properties: { + file_path: { + 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: ['file_path', 'content'], + type: 'object' + } + ); + + // Set the root directory + this.rootDirectory = path.resolve(rootDirectory); + } + + /** + * 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 + */ + invalidParams(params: WriteFileToolParams): string | null { + if (this.schema.parameters && !SchemaValidator.validate(this.schema.parameters as Record, params)) { + return 'Parameters failed schema validation.'; + } + + // 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; + } + + /** + * 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. + */ + async shouldConfirmExecute(params: WriteFileToolParams): Promise { + if (this.shouldAlwaysWrite) { + return false; + } + + const relativePath = makeRelative(params.file_path, this.rootDirectory); + const fileName = path.basename(params.file_path); + + let currentContent = ''; + try { + currentContent = fs.readFileSync(params.file_path, 'utf8'); + } catch (error) { + // File may not exist, which is fine + } + + const fileDiff = Diff.createPatch( + fileName, + currentContent, + params.content, + 'Current', + 'Proposed', + { context: 3, ignoreWhitespace: true} + ); + + const confirmationDetails: ToolEditConfirmationDetails = { + title: `Confirm Write: ${shortenPath(relativePath)}`, + fileName, + fileDiff, + onConfirm: async (outcome: ToolConfirmationOutcome) => { + if (outcome === ToolConfirmationOutcome.ProceedAlways) { + this.shouldAlwaysWrite = true; + } + }, + }; + return confirmationDetails; + } + + /** + * 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 + */ + async execute(params: WriteFileToolParams): Promise { + const validationError = this.invalidParams(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}` + }; + } + } +} diff --git a/packages/cli/src/ui/App.tsx b/packages/cli/src/ui/App.tsx new file mode 100644 index 00000000..32dcaac0 --- /dev/null +++ b/packages/cli/src/ui/App.tsx @@ -0,0 +1,90 @@ +import React, { useState, useEffect } from 'react'; +import { Box, Text } from 'ink'; +import type { HistoryItem } from './types.js'; +import { useGeminiStream } from './hooks/useGeminiStream.js'; +import { useLoadingIndicator } from './hooks/useLoadingIndicator.js'; +import Header from './components/Header.js'; +import Tips from './components/Tips.js'; +import HistoryDisplay from './components/HistoryDisplay.js'; +import LoadingIndicator from './components/LoadingIndicator.js'; +import InputPrompt from './components/InputPrompt.js'; +import Footer from './components/Footer.js'; +import { StreamingState } from '../core/StreamingState.js'; +import { PartListUnion } from '@google/genai'; + +interface AppProps { + directory: string; +} + +const App = ({ directory }: AppProps) => { + const [query, setQuery] = useState(''); + const [history, setHistory] = useState([]); + const { streamingState, submitQuery, initError } = useGeminiStream(setHistory); + const { elapsedTime, currentLoadingPhrase } = useLoadingIndicator(streamingState); + + const handleInputSubmit = (value: PartListUnion) => { + submitQuery(value).then(() => { + setQuery(''); + }).catch(() => { + setQuery(''); + }); + }; + + useEffect(() => { + if (initError && !history.some(item => item.type === 'error' && item.text?.includes(initError))) { + setHistory(prev => [ + ...prev, + { id: Date.now(), type: 'error', text: `Initialization Error: ${initError}. Please check API key and configuration.` } as HistoryItem + ]); + } + }, [initError, history]); + + const isWaitingForToolConfirmation = history.some(item => + item.type === 'tool_group' && item.tools.some(tool => tool.confirmationDetails !== undefined) + ); + const isInputActive = streamingState === StreamingState.Idle && !initError; + + + return ( + +
+ + + + {initError && streamingState !== StreamingState.Responding && !isWaitingForToolConfirmation && ( + + {history.find(item => item.type === 'error' && item.text?.includes(initError))?.text ? ( + {history.find(item => item.type === 'error' && item.text?.includes(initError))?.text} + ) : ( + <> + Initialization Error: {initError} + Please check API key and configuration. + + )} + + )} + + + + + + + {!isWaitingForToolConfirmation && isInputActive && ( + + )} + +