mirror of
https://github.com/cline/cline.git
synced 2026-09-06 12:28:08 +08:00
Compare commits
61 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 5e803ec473 | |||
| cafcb7f5d5 | |||
| 079d05c2cc | |||
| acc795ed69 | |||
| 1aaa30ecce | |||
| f7e5398ac8 | |||
| 1409c2d3cc | |||
| dce3b11f8b | |||
| 89f35b0800 | |||
| d7f30fdf73 | |||
| 0c6a4f9452 | |||
| c1e38e649c | |||
| b8a65a446a | |||
| 6626124bef | |||
| 80f67c3c89 | |||
| 01afe5ec53 | |||
| 83928ccecc | |||
| 38a1179e62 | |||
| e0f9eeaa79 | |||
| f10a82916f | |||
| da12437251 | |||
| fb3012f778 | |||
| 8336831d8f | |||
| ec064426b3 | |||
| 8f72bf11f7 | |||
| 915cf76f85 | |||
| f1fef24f25 | |||
| ceb0900bf6 | |||
| cc9fc9bd1f | |||
| dcf59bc29f | |||
| 5c3e7a38d4 | |||
| d6ccbcdf22 | |||
| e4e03fa0dd | |||
| 10892670be | |||
| 3c7a42c35d | |||
| abfaf6ca7a | |||
| f699f1fd80 | |||
| a6fbdcb5c1 | |||
| a4200869c9 | |||
| 9f59b6010e | |||
| 29d3175e0b | |||
| 600174322e | |||
| 9818d976dd | |||
| 3938e23cde | |||
| 86bb0c6ded | |||
| 36f57ce6c0 | |||
| ed0181a114 | |||
| 439c62935d | |||
| 9bc24ecd96 | |||
| 2150e4882e | |||
| ee347bfe9d | |||
| 08d86990e2 | |||
| f74a8ba82e | |||
| ad51b7a4e1 | |||
| 94516092b1 | |||
| adf25681cc | |||
| e2f73bce61 | |||
| fec8626291 | |||
| 6fa819a170 | |||
| 2ca3e9ac82 | |||
| 9d801a1a68 |
@@ -2,4 +2,4 @@
|
||||
"claude-dev": patch
|
||||
---
|
||||
|
||||
add back missing function
|
||||
add models to vertex ai
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
"claude-dev": minor
|
||||
---
|
||||
|
||||
Update `xaiModels` object and `xaiDefaultModelId` in `src/shared/api.ts`
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
"claude-dev": patch
|
||||
---
|
||||
|
||||
fixing token counting for xai provider
|
||||
@@ -1,5 +0,0 @@
|
||||
---
|
||||
"claude-dev": minor
|
||||
---
|
||||
|
||||
Migrate openExtensionSettings to protobus
|
||||
@@ -1,5 +0,0 @@
|
||||
---
|
||||
"claude-dev": minor
|
||||
---
|
||||
|
||||
Migrate showAccountViewClicked to protobus
|
||||
@@ -1,5 +0,0 @@
|
||||
---
|
||||
"claude-dev": patch
|
||||
---
|
||||
|
||||
Adding Telemetry for button clicks
|
||||
@@ -1,5 +0,0 @@
|
||||
---
|
||||
"claude-dev": patch
|
||||
---
|
||||
|
||||
openInBrowser protobus migration
|
||||
@@ -0,0 +1,7 @@
|
||||
---
|
||||
"claude-dev": patch
|
||||
---
|
||||
|
||||
fix(bedrock): Use ignoreCache for profile-based AWS credential loading
|
||||
|
||||
Ensures that AWS Bedrock provider always fetches fresh credentials when using IAM profiles by setting `ignoreCache: true` for `fromNodeProviderChain`. This resolves issues where externally updated credentials (e.g., by AWS Identity Manager) were not detected by Cline, requiring an extension restart. Manual credential handling remains unchanged.
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
"claude-dev": minor
|
||||
---
|
||||
|
||||
add suppport for parsing csv and xlsx
|
||||
@@ -1,5 +0,0 @@
|
||||
---
|
||||
"claude-dev": patch
|
||||
---
|
||||
|
||||
Use identify to enhance distinct user segmentation
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
"claude-dev": minor
|
||||
---
|
||||
|
||||
Add dev only button to open task conversation history
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
"claude-dev": minor
|
||||
---
|
||||
|
||||
update chat box ui
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
"claude-dev": patch
|
||||
---
|
||||
|
||||
bug fix for ollama
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
"claude-dev": patch
|
||||
---
|
||||
|
||||
update the openrouter model list when refreshing
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
"claude-dev": patch
|
||||
---
|
||||
|
||||
Fix Title for windows in cline
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
"claude-dev": minor
|
||||
---
|
||||
|
||||
scroll to task timeline
|
||||
@@ -1,5 +0,0 @@
|
||||
---
|
||||
"claude-dev": minor
|
||||
---
|
||||
|
||||
Migrate openMcpSettings to protobus
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
"claude-dev": patch
|
||||
---
|
||||
|
||||
optionsResponse protobus migration
|
||||
@@ -1,5 +0,0 @@
|
||||
---
|
||||
"claude-dev": patch
|
||||
---
|
||||
|
||||
requestTotalTasksSize protobus migration
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
"claude-dev": patch
|
||||
---
|
||||
|
||||
change proto type
|
||||
@@ -164,6 +164,7 @@ Key providers include:
|
||||
- **OpenRouter**: Meta-provider supporting multiple model providers
|
||||
- **AWS Bedrock**: Integration with Amazon's AI services
|
||||
- **Gemini**: Google's AI models
|
||||
- **Cerebras**: High-performance inference with Llama, Qwen, and DeepSeek models
|
||||
- **Ollama**: Local model hosting
|
||||
- **LM Studio**: Local model hosting
|
||||
- **VSCode LM**: VSCode's built-in language models
|
||||
|
||||
+3
-2
@@ -5,7 +5,7 @@
|
||||
"ecmaVersion": 6,
|
||||
"sourceType": "module"
|
||||
},
|
||||
"plugins": ["@typescript-eslint"],
|
||||
"plugins": ["@typescript-eslint", "eslint-rules"],
|
||||
"rules": {
|
||||
"@typescript-eslint/naming-convention": [
|
||||
"warn",
|
||||
@@ -19,7 +19,8 @@
|
||||
"eqeqeq": "warn",
|
||||
"no-throw-literal": "warn",
|
||||
"semi": "off",
|
||||
"react-hooks/exhaustive-deps": "off"
|
||||
"react-hooks/exhaustive-deps": "off",
|
||||
"eslint-rules/no-grpc-client-object-literals": "error"
|
||||
},
|
||||
"ignorePatterns": ["out", "dist", "**/*.d.ts"]
|
||||
}
|
||||
|
||||
@@ -3,3 +3,5 @@ node_modules
|
||||
webview-ui/build/
|
||||
*.md
|
||||
package-lock.json
|
||||
src/core/prompts/system.ts
|
||||
src/core/prompts/model_prompts/claude4.ts
|
||||
|
||||
@@ -1,5 +1,23 @@
|
||||
# Changelog
|
||||
|
||||
## [3.17.8]
|
||||
|
||||
- Fix bug where terminal would get stuck and output "capture failure"
|
||||
|
||||
## [3.17.7]
|
||||
|
||||
- Fix diff editing reliability for Claude 4 family models by adding constraints to prevent errors with large replacements
|
||||
|
||||
## [3.17.6]
|
||||
|
||||
- Add Cerebras as a new API provider with 5 high-performance models including reasoning-capable models (Thanks @kevint-cerebras!)
|
||||
- Add support for uploading various file types (XML, JSON, TXT, LOG, MD, DOCX, IPYNB, PDF) alongside images
|
||||
- Add improved onboarding experience for new users with guided setup
|
||||
- Add prompt cache indicator for Gemini 2.5 Flash models
|
||||
- Update SambaNova provider with new model list and documentation links (Thanks @luisfucros!)
|
||||
- Fix diff editing support for Claude 4 family of models
|
||||
- Improve telemetry and analytics for better user experience insights
|
||||
|
||||
## [3.17.5]
|
||||
|
||||
- Fix issue with Claude 4 models where after several conversation turns, it would start making invalid diff edits
|
||||
|
||||
@@ -51,7 +51,7 @@ Thanks to [Claude 3.7 Sonnet's agentic coding capabilities](https://www.anthrop
|
||||
|
||||
### Use any API and Model
|
||||
|
||||
Cline supports API providers like OpenRouter, Anthropic, OpenAI, Google Gemini, AWS Bedrock, Azure, and GCP Vertex. You can also configure any OpenAI compatible API, or use a local model through LM Studio/Ollama. If you're using OpenRouter, the extension fetches their latest model list, allowing you to use the newest models as soon as they're available.
|
||||
Cline supports API providers like OpenRouter, Anthropic, OpenAI, Google Gemini, AWS Bedrock, Azure, GCP Vertex, and Cerebras. You can also configure any OpenAI compatible API, or use a local model through LM Studio/Ollama. If you're using OpenRouter, the extension fetches their latest model list, allowing you to use the newest models as soon as they're available.
|
||||
|
||||
The extension also keeps track of total tokens and API usage cost for the entire task loop and individual requests, keeping you informed of spend every step of the way.
|
||||
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
---
|
||||
title: "VS Code Language Model API"
|
||||
description: "Learn how to use Cline with the experimental VS Code Language Model API, enabling access to models from GitHub Copilot and other compatible extensions."
|
||||
---
|
||||
|
||||
Cline offers _experimental_ support for the [VS Code Language Model API](https://code.visualstudio.com/api/extension-guides/language-model). This API enables extensions to grant access to language models directly within the VS Code environment. Consequently, you might be able to leverage models from:
|
||||
|
||||
- **GitHub Copilot:** Provided you have an active Copilot subscription and the extension installed.
|
||||
- **Other VS Code Extensions:** Any extension that implements the Language Model API.
|
||||
|
||||
**Important Note:** This integration is currently in an experimental phase and might not perform as anticipated. Its functionality relies on other extensions correctly implementing the VS Code Language Model API.
|
||||
|
||||
### Prerequisites
|
||||
|
||||
- **VS Code:** The Language Model API is accessible via VS Code (it is not currently supported by Cursor).
|
||||
- **A Language Model Provider Extension:** An extension that furnishes a language model is required. Examples include:
|
||||
- **GitHub Copilot:** With a Copilot subscription, the GitHub Copilot and GitHub Copilot Chat extensions can serve as model providers.
|
||||
- **Alternative Extensions:** Explore the VS Code Marketplace for extensions mentioning "Language Model API" or "lm". Other experimental options may be available.
|
||||
|
||||
### Configuration Steps
|
||||
|
||||
1. **Access Cline Settings:** Click the gear icon (⚙️) located in the Cline panel.
|
||||
2. **Choose Provider:** Select "VS Code LM API" from the "API Provider" dropdown menu.
|
||||
3. **Select Model:** The "Language Model" dropdown will (eventually) populate with available models. The naming convention is `vendor/family`. For instance, if Copilot is active, you might encounter options such as:
|
||||
- `copilot - claude-3.5-sonnet`
|
||||
- `copilot - o3-mini`
|
||||
- `copilot - o1-ga`
|
||||
- `copilot - gemini-2.0-flash`
|
||||
|
||||
### Current Limitations
|
||||
|
||||
- **Experimental API Status:** The VS Code Language Model API is still under active development. Anticipate potential changes and instability.
|
||||
- **Dependency on Extensions:** This feature is entirely contingent on other extensions making models available. Cline does not directly control the list of accessible models.
|
||||
- **Restricted Functionality:** The VS Code Language Model API might not encompass all features available through other API providers (e.g., image input capabilities, streaming responses, detailed usage metrics).
|
||||
- **No Direct Cost Management:** Users are subject to the pricing structures and terms of service of the extension providing the model. Cline cannot directly monitor or regulate associated costs.
|
||||
- **GitHub Copilot Rate Throttling:** When employing the VS Code LM API with GitHub Copilot, be mindful that GitHub may enforce rate limits on Copilot usage. These limitations are governed by GitHub, not Cline.
|
||||
|
||||
### Troubleshooting Tips
|
||||
|
||||
- **Models Not Appearing:**
|
||||
- Confirm that VS Code is installed.
|
||||
- Verify that a language model provider extension (e.g., GitHub Copilot, GitHub Copilot Chat) is installed and enabled.
|
||||
- If utilizing Copilot, ensure you have previously sent a Copilot Chat message using the desired model.
|
||||
- **Unexpected Operation:** Should you encounter unforeseen behavior, it is likely an issue stemming from the underlying Language Model API or the provider extension. Consider reporting the problem to the developers of the provider extension.
|
||||
+2
-1
@@ -148,7 +148,8 @@
|
||||
"custom-model-configs/aws-bedrock-with-credentials-authentication",
|
||||
"custom-model-configs/aws-bedrock-with-profile-authentication",
|
||||
"custom-model-configs/gcp-vertex-ai",
|
||||
"custom-model-configs/litellm-and-cline-using-codestral"
|
||||
"custom-model-configs/litellm-and-cline-using-codestral",
|
||||
"custom-model-configs/vscode-language-model-api"
|
||||
]
|
||||
},
|
||||
{
|
||||
|
||||
@@ -13,35 +13,13 @@ Before you jump into coding, make sure you have these essentials ready:
|
||||
|
||||
A popular, free, and powerful code editor.
|
||||
|
||||
- [Download VS Code](https://code.visualstudio.com/)
|
||||
- [<u>Download VS Code</u>](https://code.visualstudio.com/)
|
||||
|
||||
📺 **Recommended YouTube Tutorial:** [How to Install VS Code](https://www.youtube.com/watch?v=MlIzFUI1QGA)
|
||||
📺 **Recommended YouTube Tutorial:** [<u>How to Install VS Code</u>](https://www.youtube.com/watch?v=MlIzFUI1QGA)
|
||||
|
||||
> ✅ **Pro Tip:** Install VS Code in your Applications folder (macOS) or Program Files (Windows) for easy access from your dock or start menu.
|
||||
|
||||
#### 2. **Essential Development Tools**
|
||||
|
||||
Basic software required for coding efficiently:
|
||||
|
||||
- Homebrew (macOS)
|
||||
- Node.js
|
||||
- Git
|
||||
|
||||
👉 Follow our detailed guide on Installing Essential Development Tools with step-by-step help from Cline.
|
||||
|
||||
📺 **Recommended YouTube Tutorials:**
|
||||
|
||||
- **For macOS:**
|
||||
- [Install Homebrew on Mac](https://www.youtube.com/watch?v=hwGNgVbqasc)
|
||||
- [Install Git on MacOS 2024](https://www.youtube.com/watch?v=B4qsvQ5IqWk)
|
||||
- [Install Node.js on Mac (M1 | M2 | M3)](https://www.youtube.com/watch?v=I8H4wolRFBk)
|
||||
- **For Windows:**
|
||||
- [Install Git on Windows 10/11 (2024)](https://www.youtube.com/watch?v=yjxv1HuRQy0)
|
||||
- [Install Node.js in Windows 10/11](https://www.youtube.com/watch?v=uCgAuOYpJd0)
|
||||
|
||||
> ⚠️ **Note:** If you run into permission issues during installation, try running your terminal or command prompt as an administrator.
|
||||
|
||||
#### 3. **Organize Your Projects**
|
||||
#### 2. **Organize Your Projects**
|
||||
|
||||
Create a dedicated folder named `Cline` in your Documents folder for all your coding projects:
|
||||
|
||||
@@ -55,14 +33,36 @@ Inside your `Cline` folder, structure projects clearly:
|
||||
|
||||
> 💡 **Tip:** Keeping your projects organized from the start will save you time and confusion later!
|
||||
|
||||
#### 4. **Install the Cline VS Code Extension**
|
||||
#### 3. **Install the Cline VS Code Extension**
|
||||
|
||||
Enhance your coding workflow by installing the Cline extension directly within VS Code:
|
||||
|
||||
- Get Started with Cline Extension Tutorial
|
||||
|
||||
📺 **Recommended YouTube Tutorial:** [How To Install Extensions in VS Code](https://www.youtube.com/watch?v=E7trgwZa-mk)
|
||||
📺 **Recommended YouTube Tutorial:** [<u>How To Install Extensions in VS Code</u>](https://www.youtube.com/watch?v=E7trgwZa-mk)
|
||||
|
||||
> ✅ **Pro Tip:** After installing, reload VS Code to ensure the extension is activated properly.
|
||||
|
||||
#### 4. **Essential Development Tools**
|
||||
|
||||
Basic software required for coding efficiently:
|
||||
|
||||
- Homebrew (macOS)
|
||||
- Node.js
|
||||
- Git
|
||||
|
||||
👉 [<u>Follow our detailed guide on Installing Essential Development Tools with step-by-step help from Cline.</u>](https://docs.cline.bot/getting-started/installing-dev-essentials#installing-dev-essentials)
|
||||
|
||||
📺 **Recommended YouTube Tutorials for Manual Installation:**
|
||||
|
||||
- **For macOS:**
|
||||
- [<u>Install Homebrew on Mac</u>](https://www.youtube.com/watch?v=hwGNgVbqasc)
|
||||
- [<u>Install Git on macOS 2024</u>](https://www.youtube.com/watch?v=B4qsvQ5IqWk)
|
||||
- [<u>Install Node.js on Mac (M1 | M2 | M3)</u>](https://www.youtube.com/watch?v=I8H4wolRFBk)
|
||||
- **For Windows:**
|
||||
- [<u>Install Git on Windows 10/11 (2024)</u>](https://www.youtube.com/watch?v=yjxv1HuRQy0)
|
||||
- [<u>Install Node.js in Windows 10/11</u>](https://www.youtube.com/watch?v=uCgAuOYpJd0)
|
||||
|
||||
> ⚠️ **Note:** If you run into permission issues during installation, try running your terminal or command prompt as an administrator.
|
||||
|
||||
🎉 You're all set! Dive in and start coding smarter and faster with **Cline**.
|
||||
|
||||
@@ -69,9 +69,9 @@ Choose your AI assistant based on your needs:
|
||||
### Getting Started
|
||||
|
||||
1. Install the development essentials:
|
||||
- Follow our [Development Essentials Installation Guide](https://docs.cline.bot/getting-started/getting-started-new-coders/installing-dev-essentials)
|
||||
- Follow our [Development Essentials Installation Guide](https://docs.cline.bot/getting-started/installing-dev-essentials)
|
||||
2. Set up Cline's Memory Bank:
|
||||
- Follow the [Memory Bank setup instructions](https://docs.cline.bot/improving-your-prompting-skills/custom-instructions-library/cline-memory-bank)
|
||||
- Follow the [Memory Bank setup instructions](https://docs.cline.bot/prompting/cline-memory-bank)
|
||||
- Create an empty `cline_docs` folder in your project root
|
||||
- Create `projectBrief.md` in the `cline_docs` folder (see example below)
|
||||
- Tell Cline to "initialize memory bank"
|
||||
@@ -197,20 +197,20 @@ git push origin main # Upload to GitHub
|
||||
1. **Start of day**: Get latest changes
|
||||
|
||||
```bash
|
||||
bashCopygit pull origin main # Download latest code
|
||||
git pull origin main # Download latest code
|
||||
```
|
||||
|
||||
2. **During development**: Save work regularly
|
||||
|
||||
```bash
|
||||
bashCopygit add .
|
||||
git add .
|
||||
git commit -m "Clear message about changes"
|
||||
```
|
||||
|
||||
3. **End of day**: Share your progress
|
||||
|
||||
```bash
|
||||
bashCopygit push origin main # Upload to GitHub
|
||||
git push origin main # Upload to GitHub
|
||||
```
|
||||
|
||||
**Best Practices**
|
||||
|
||||
@@ -38,7 +38,7 @@ Cline actively builds context in two ways:
|
||||
- Guide focus areas
|
||||
- Share design thoughts and requirements
|
||||
|
||||
💡 **Key Point**: Cline isn't passive - it actively seeks to understand your project. You can either let it explore or guide its focus, especially in [Plan](https://docs.cline.bot/exploring-clines-tools/plan-and-act-modes-a-guide-to-effective-ai-development) mode.
|
||||
💡 **Key Point**: Cline isn't passive - it actively seeks to understand your project. You can either let it explore or guide its focus, especially in [Plan](https://docs.cline.bot/features/plan-and-act) mode.
|
||||
|
||||
### Context & Context Windows
|
||||
|
||||
@@ -93,7 +93,7 @@ Context files help maintain understanding across sessions. They serve as documen
|
||||
|
||||
#### Approaches to Context Files
|
||||
|
||||
1. **Evergreen Project Context (i.e.** [**Memory Bank**](https://docs.cline.bot/improving-your-prompting-skills/custom-instructions-library/cline-memory-bank)**)**
|
||||
1. **Evergreen Project Context (i.e.** [**Memory Bank**](https://docs.cline.bot/prompting/cline-memory-bank)**)**
|
||||
- Living documentation that evolves with your project
|
||||
- Updated as architecture and patterns emerge
|
||||
- Example: The Memory Bank pattern maintains files like `techContext.md` and `systemPatterns.md`
|
||||
@@ -151,7 +151,7 @@ Context files help maintain understanding across sessions. They serve as documen
|
||||
- Use Plan mode for complex discussions
|
||||
- Start fresh sessions when needed
|
||||
3. **Team Projects**
|
||||
- Share common context files (consider using [.clinerules](https://docs.cline.bot/improving-your-prompting-skills/prompting) files in project roots)
|
||||
- Share common context files (consider using [.clinerules](https://docs.cline.bot/features/cline-rules) files in project roots)
|
||||
- Document architectural decisions
|
||||
- Maintain consistent patterns
|
||||
- Keep documentation current
|
||||
|
||||
@@ -0,0 +1,174 @@
|
||||
const { RuleTester: GrpcRuleTester } = require("eslint")
|
||||
const grpcRule = require("../no-grpc-client-object-literals")
|
||||
|
||||
const grpcRuleTester = new GrpcRuleTester({
|
||||
parser: require.resolve("@typescript-eslint/parser"),
|
||||
parserOptions: {
|
||||
ecmaVersion: 2020,
|
||||
sourceType: "module",
|
||||
ecmaFeatures: {
|
||||
jsx: true,
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
grpcRuleTester.run("no-grpc-client-object-literals", grpcRule, {
|
||||
valid: [
|
||||
// Valid case: Using .create() method with gRPC client
|
||||
{
|
||||
code: `
|
||||
import { TogglePlanActModeRequest } from '@shared/proto/state';
|
||||
import { StateServiceClient } from '../services/grpc-client';
|
||||
|
||||
StateServiceClient.togglePlanActMode(
|
||||
TogglePlanActModeRequest.create({
|
||||
chatSettings: {
|
||||
mode: PlanActMode.PLAN,
|
||||
preferredLanguage: 'en',
|
||||
},
|
||||
})
|
||||
);
|
||||
`,
|
||||
},
|
||||
// Valid case: Using .fromPartial() method with gRPC client
|
||||
{
|
||||
code: `
|
||||
import { TogglePlanActModeRequest, ChatSettings } from '@shared/proto/state';
|
||||
import { StateServiceClient } from '../services/grpc-client';
|
||||
|
||||
const chatSettings = ChatSettings.fromPartial({
|
||||
mode: PlanActMode.PLAN,
|
||||
preferredLanguage: 'en',
|
||||
});
|
||||
|
||||
StateServiceClient.togglePlanActMode(
|
||||
TogglePlanActModeRequest.create({
|
||||
chatSettings: chatSettings,
|
||||
})
|
||||
);
|
||||
`,
|
||||
},
|
||||
// Valid case: Regular function call with object literal (not a gRPC client)
|
||||
{
|
||||
code: `
|
||||
function processData(data) {
|
||||
console.log(data);
|
||||
}
|
||||
|
||||
processData({
|
||||
id: 123,
|
||||
name: 'test',
|
||||
});
|
||||
`,
|
||||
},
|
||||
// Valid case: Using proper nested protobuf objects
|
||||
{
|
||||
code: `
|
||||
import { TogglePlanActModeRequest, ChatSettings } from '@shared/proto/state';
|
||||
import { StateServiceClient } from '../services/grpc-client';
|
||||
|
||||
// Using proper nested protobuf objects
|
||||
const chatSettings = ChatSettings.create({
|
||||
mode: 0,
|
||||
preferredLanguage: 'en',
|
||||
});
|
||||
|
||||
const request = TogglePlanActModeRequest.create({
|
||||
chatSettings: chatSettings,
|
||||
});
|
||||
|
||||
StateServiceClient.togglePlanActMode(request);
|
||||
`,
|
||||
},
|
||||
// Valid case: Object literal in second parameter (should not be checked)
|
||||
{
|
||||
code: `
|
||||
import { StateSubscribeRequest } from '@shared/proto/state';
|
||||
import { StateServiceClient } from '../services/grpc-client';
|
||||
|
||||
const request = StateSubscribeRequest.create({
|
||||
topics: ['apiConfig', 'tasks']
|
||||
});
|
||||
|
||||
// Second parameter is an object literal but should not trigger the rule
|
||||
StateServiceClient.subscribe(request, {
|
||||
metadata: {
|
||||
userId: 123,
|
||||
sessionId: "abc-123"
|
||||
}
|
||||
});
|
||||
`,
|
||||
},
|
||||
],
|
||||
invalid: [
|
||||
// Invalid case: Using object literal directly with gRPC client
|
||||
{
|
||||
code: `
|
||||
import { StateServiceClient } from '../services/grpc-client';
|
||||
|
||||
StateServiceClient.togglePlanActMode({
|
||||
chatSettings: {
|
||||
mode: 0,
|
||||
preferredLanguage: 'en',
|
||||
},
|
||||
});
|
||||
`,
|
||||
errors: [{ messageId: "useProtobufMethod" }],
|
||||
},
|
||||
// Invalid case: Using object literal with nested properties
|
||||
{
|
||||
code: `
|
||||
import { ChatSettings } from '@shared/proto/state';
|
||||
import { StateServiceClient } from '../services/grpc-client';
|
||||
|
||||
const chatSettings = ChatSettings.create({
|
||||
mode: 0,
|
||||
preferredLanguage: 'en',
|
||||
});
|
||||
|
||||
StateServiceClient.togglePlanActMode({
|
||||
chatSettings: {
|
||||
mode: 1,
|
||||
preferredLanguage: 'fr',
|
||||
},
|
||||
});
|
||||
`,
|
||||
errors: [{ messageId: "useProtobufMethod" }],
|
||||
},
|
||||
// Invalid case: Nested object literal in protobuf create method
|
||||
{
|
||||
code: `
|
||||
import { TogglePlanActModeRequest, ChatSettings } from '@shared/proto/state';
|
||||
import { StateServiceClient } from '../services/grpc-client';
|
||||
|
||||
// Using nested object literal instead of ChatSettings.create()
|
||||
const request = TogglePlanActModeRequest.create({
|
||||
chatSettings: {
|
||||
mode: 0,
|
||||
preferredLanguage: 'en',
|
||||
},
|
||||
});
|
||||
|
||||
StateServiceClient.togglePlanActMode(request);
|
||||
`,
|
||||
errors: [{ messageId: "useProtobufMethod" }],
|
||||
},
|
||||
// Invalid case: Object literal as first parameter to subscribe method
|
||||
{
|
||||
code: `
|
||||
import { StateServiceClient } from '../services/grpc-client';
|
||||
|
||||
// First parameter is an object literal, which should trigger the rule
|
||||
StateServiceClient.subscribe({
|
||||
topics: ['apiConfig', 'tasks']
|
||||
}, {
|
||||
metadata: {
|
||||
userId: 123,
|
||||
sessionId: "abc-123"
|
||||
}
|
||||
});
|
||||
`,
|
||||
errors: [{ messageId: "useProtobufMethod" }],
|
||||
},
|
||||
],
|
||||
})
|
||||
@@ -0,0 +1,16 @@
|
||||
// eslint-rules/index.js
|
||||
const noGrpcClientObjectLiterals = require("./no-grpc-client-object-literals")
|
||||
|
||||
module.exports = {
|
||||
rules: {
|
||||
"no-grpc-client-object-literals": noGrpcClientObjectLiterals,
|
||||
},
|
||||
configs: {
|
||||
recommended: {
|
||||
plugins: ["local"],
|
||||
rules: {
|
||||
"local/no-grpc-client-object-literals": "error",
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
@@ -0,0 +1,216 @@
|
||||
const { ESLintUtils } = require("@typescript-eslint/utils")
|
||||
|
||||
const createRule = ESLintUtils.RuleCreator((name) => `https://cline.bot/eslint-rules/${name}`)
|
||||
|
||||
module.exports = createRule({
|
||||
name: "no-grpc-client-object-literals",
|
||||
meta: {
|
||||
type: "problem",
|
||||
docs: {
|
||||
description:
|
||||
"Enforce using .create() or .fromPartial() for gRPC service client parameters instead of object literals",
|
||||
recommended: "error",
|
||||
},
|
||||
messages: {
|
||||
useProtobufMethod:
|
||||
"Use the appropriate protobuf .create() or .fromPartial() method instead of " +
|
||||
"object literal for gRPC client parameters.\n" +
|
||||
"Found: {{code}}\n" +
|
||||
"gRPC client methods should always receive properly created protobuf objects.",
|
||||
},
|
||||
schema: [],
|
||||
},
|
||||
defaultOptions: [],
|
||||
|
||||
create(context) {
|
||||
// Check if a name matches the gRPC service client pattern using regex
|
||||
// Must start with an uppercase letter and end with ServiceClient
|
||||
const isGrpcServiceClient = (name) => {
|
||||
return typeof name === "string" && /^[A-Z].*ServiceClient$/.test(name)
|
||||
}
|
||||
|
||||
const safeObjectExpressions = new Map() // Track object expressions in create/fromPartial calls
|
||||
|
||||
return {
|
||||
// Skip object literals inside create() or fromPartial() method calls
|
||||
CallExpression(node) {
|
||||
if (
|
||||
node.callee &&
|
||||
node.callee.type === "MemberExpression" &&
|
||||
(node.callee.property.name === "create" || node.callee.property.name === "fromPartial") &&
|
||||
node.arguments.length > 0 &&
|
||||
node.arguments[0].type === "ObjectExpression"
|
||||
) {
|
||||
// Track this object expression as being used with create/fromPartial
|
||||
safeObjectExpressions.set(node.arguments[0], { isProblematic: false })
|
||||
}
|
||||
},
|
||||
|
||||
// Track create/fromPartial calls that contain nested object literals
|
||||
"CallExpression[callee.type='MemberExpression'][callee.property.name=/^(create|fromPartial)$/]"(node) {
|
||||
if (node.arguments.length > 0 && node.arguments[0].type === "ObjectExpression") {
|
||||
// Track problematic nested object literals
|
||||
const nestedObjectLiterals = new Map() // Map of object expressions to their containing property paths
|
||||
|
||||
// Search for nested object literals
|
||||
const queue = [
|
||||
...node.arguments[0].properties.map((prop) => ({
|
||||
property: prop,
|
||||
path: prop.key && prop.key.name ? prop.key.name : "unknown",
|
||||
})),
|
||||
]
|
||||
|
||||
while (queue.length > 0) {
|
||||
const { property, path } = queue.shift()
|
||||
|
||||
// Skip spread elements
|
||||
if (property.type !== "Property") continue
|
||||
|
||||
// If this is an object literal, mark it as problematic
|
||||
if (property.value.type === "ObjectExpression") {
|
||||
nestedObjectLiterals.set(property.value, path)
|
||||
|
||||
// Add nested properties to queue
|
||||
queue.push(
|
||||
...property.value.properties.map((prop) => ({
|
||||
property: prop,
|
||||
path: `${path}.${prop.key && prop.key.name ? prop.key.name : "unknown"}`,
|
||||
})),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// For each problematic nested object, track it with its path
|
||||
nestedObjectLiterals.forEach((path, objectExpr) => {
|
||||
safeObjectExpressions.set(objectExpr, {
|
||||
isProblematic: true,
|
||||
path: path,
|
||||
parentNode: node,
|
||||
})
|
||||
})
|
||||
}
|
||||
},
|
||||
|
||||
// Check calls to gRPC service clients
|
||||
"CallExpression[callee.type='MemberExpression']"(node) {
|
||||
// Get the object (left side) of the member expression
|
||||
const callee = node.callee
|
||||
if (callee.object && callee.object.type === "Identifier") {
|
||||
const objectName = callee.object.name
|
||||
|
||||
// Check if this is a call to one of our gRPC service clients
|
||||
if (isGrpcServiceClient(objectName)) {
|
||||
// Only check the first argument of gRPC service client calls
|
||||
if (node.arguments.length > 0) {
|
||||
const arg = node.arguments[0] // Only check the first parameter
|
||||
if (arg.type === "ObjectExpression" && !safeObjectExpressions.has(arg)) {
|
||||
// This is an object literal being passed directly to a gRPC client
|
||||
const sourceCode = context.getSourceCode()
|
||||
const callText = sourceCode.getText(node).trim()
|
||||
|
||||
context.report({
|
||||
node: arg,
|
||||
messageId: "useProtobufMethod",
|
||||
data: {
|
||||
code: callText,
|
||||
},
|
||||
})
|
||||
} else if (arg.type === "ObjectExpression") {
|
||||
// Search for nested object literals that aren't protected
|
||||
const queue = [...arg.properties]
|
||||
while (queue.length > 0) {
|
||||
const property = queue.shift()
|
||||
|
||||
// Skip spread elements
|
||||
if (property.type !== "Property") continue
|
||||
|
||||
// Check value
|
||||
if (
|
||||
property.value.type === "ObjectExpression" &&
|
||||
!safeObjectExpressions.has(property.value)
|
||||
) {
|
||||
// Found a nested object literal
|
||||
const sourceCode = context.getSourceCode()
|
||||
const propertyText = sourceCode.getText(property).trim()
|
||||
|
||||
context.report({
|
||||
node: property.value,
|
||||
messageId: "useProtobufMethod",
|
||||
data: {
|
||||
code: `${objectName}.${callee.property.name}(... ${propertyText} ...)`,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
// Add any nested properties to the queue
|
||||
if (property.value.type === "ObjectExpression") {
|
||||
queue.push(...property.value.properties)
|
||||
}
|
||||
}
|
||||
} else if (arg.type === "Identifier") {
|
||||
// This is a variable - check if it references a problematic protobuf object
|
||||
const varName = arg.name
|
||||
const sourceCode = context.getSourceCode()
|
||||
const scope = sourceCode.getScope(node)
|
||||
|
||||
// Find the variable declaration
|
||||
const variable = scope.variables.find((v) => v.name === varName)
|
||||
if (variable && variable.references && variable.references.length > 0) {
|
||||
// Look for definitions
|
||||
const def = variable.defs.find(
|
||||
(d) => d.node && d.node.type === "VariableDeclarator" && d.node.init,
|
||||
)
|
||||
|
||||
if (
|
||||
def &&
|
||||
def.node.init.type === "CallExpression" &&
|
||||
def.node.init.callee.type === "MemberExpression" &&
|
||||
(def.node.init.callee.property.name === "create" ||
|
||||
def.node.init.callee.property.name === "fromPartial")
|
||||
) {
|
||||
// Flag if we find problematic nested object literals in this create/fromPartial call
|
||||
const callText = sourceCode.getText(node).trim()
|
||||
const initCallText = sourceCode.getText(def.node.init).trim()
|
||||
|
||||
// Check for nested object literals in init node
|
||||
let foundNestedLiteral = false
|
||||
if (
|
||||
def.node.init.arguments.length > 0 &&
|
||||
def.node.init.arguments[0].type === "ObjectExpression"
|
||||
) {
|
||||
// Find any nested object literals
|
||||
const queue = [...def.node.init.arguments[0].properties]
|
||||
while (queue.length > 0 && !foundNestedLiteral) {
|
||||
const property = queue.shift()
|
||||
|
||||
// Skip spread elements
|
||||
if (property.type !== "Property") continue
|
||||
|
||||
if (property.value.type === "ObjectExpression") {
|
||||
foundNestedLiteral = true
|
||||
|
||||
context.report({
|
||||
node,
|
||||
messageId: "useProtobufMethod",
|
||||
data: {
|
||||
code: `${callText} - using request created with nested object literal at: ${property.key.name}`,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
// Add any nested properties to the queue
|
||||
if (property.value.type === "ObjectExpression") {
|
||||
queue.push(...property.value.properties)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
}
|
||||
},
|
||||
})
|
||||
Generated
+2479
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,31 @@
|
||||
{
|
||||
"name": "eslint-plugin-eslint-rules",
|
||||
"version": "1.0.0",
|
||||
"description": "Custom ESLint rules for Cline",
|
||||
"main": "index.js",
|
||||
"scripts": {
|
||||
"test": "mocha --no-config --require ts-node/register __tests__/**/*.test.ts"
|
||||
},
|
||||
"keywords": [
|
||||
"eslint",
|
||||
"eslintplugin"
|
||||
],
|
||||
"author": "Cline Bot Inc.",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"@typescript-eslint/utils": "^8.33.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/eslint": "^8.0.0",
|
||||
"@types/mocha": "^10.0.7",
|
||||
"@types/node": "^20.0.0",
|
||||
"@typescript-eslint/parser": "^7.14.1",
|
||||
"eslint": "^8.57.0",
|
||||
"mocha": "^10.0.0",
|
||||
"ts-node": "^10.9.2",
|
||||
"typescript": "^5.4.5"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"eslint": ">=8.0.0"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "es2020",
|
||||
"module": "commonjs",
|
||||
"moduleResolution": "node",
|
||||
"esModuleInterop": true,
|
||||
"strict": true,
|
||||
"skipLibCheck": true,
|
||||
"forceConsistentCasingInFileNames": true,
|
||||
"outDir": "dist",
|
||||
"resolveJsonModule": true,
|
||||
"declaration": true
|
||||
},
|
||||
"include": ["**/*.ts", "**/*.js", "**/*.tsx", "__tests__/**/*"],
|
||||
"exclude": ["node_modules", "dist"]
|
||||
}
|
||||
Generated
+1736
-49
File diff suppressed because it is too large
Load Diff
+10
-11
@@ -2,7 +2,7 @@
|
||||
"name": "claude-dev",
|
||||
"displayName": "Cline",
|
||||
"description": "Autonomous coding agent right in your IDE, capable of creating/editing files, running commands, using the browser, and more with your permission every step of the way.",
|
||||
"version": "3.17.5",
|
||||
"version": "3.17.8",
|
||||
"icon": "assets/icons/icon.png",
|
||||
"engines": {
|
||||
"vscode": "^1.84.0"
|
||||
@@ -58,13 +58,7 @@
|
||||
"id": "claude-dev-ActivityBar",
|
||||
"title": "Cline (Ctrl+')",
|
||||
"icon": "assets/icons/icon.svg",
|
||||
"when": "isWindows"
|
||||
},
|
||||
{
|
||||
"id": "claude-dev-ActivityBar",
|
||||
"title": "Cline (Ctrl+')",
|
||||
"icon": "assets/icons/icon.svg",
|
||||
"when": "isLinux || !isMac && !isWindows"
|
||||
"when": "!isMac"
|
||||
}
|
||||
]
|
||||
},
|
||||
@@ -283,9 +277,9 @@
|
||||
"postprotos": "prettier src/shared/proto src/core/controller webview-ui/src/services src/standalone/server-setup.ts --write --log-level silent",
|
||||
"compile-tests": "node ./scripts/build-tests.js",
|
||||
"watch-tests": "tsc -p . -w --outDir out",
|
||||
"pretest": "npm run compile-tests && npm run compile && npm run lint",
|
||||
"pretest": "npm run compile-tests && npm run compile && npm run compile-standalone && npm run lint",
|
||||
"check-types": "npm run protos && tsc --noEmit",
|
||||
"lint": "eslint src --ext ts && eslint webview-ui/src --ext ts",
|
||||
"lint": "eslint src --ext ts && eslint webview-ui/src --ext ts && cd webview-ui && npm run lint",
|
||||
"format": "prettier . --check",
|
||||
"format:fix": "prettier . --write",
|
||||
"test": "npm-run-all test:unit test:integration",
|
||||
@@ -322,13 +316,15 @@
|
||||
"@types/turndown": "^5.0.5",
|
||||
"@types/vscode": "^1.84.0",
|
||||
"@typescript-eslint/eslint-plugin": "^7.14.1",
|
||||
"@typescript-eslint/parser": "^7.11.0",
|
||||
"@typescript-eslint/parser": "^7.18.0",
|
||||
"@typescript-eslint/utils": "^8.33.0",
|
||||
"@vscode/test-cli": "^0.0.10",
|
||||
"@vscode/test-electron": "^2.4.1",
|
||||
"chai": "^4.3.10",
|
||||
"chalk": "^5.3.0",
|
||||
"esbuild": "^0.25.0",
|
||||
"eslint": "^8.57.0",
|
||||
"eslint-plugin-eslint-rules": "file:eslint-rules",
|
||||
"grpc-tools": "^1.13.0",
|
||||
"husky": "^9.1.7",
|
||||
"mintlify": "^4.0.515",
|
||||
@@ -349,6 +345,7 @@
|
||||
"@anthropic-ai/vertex-sdk": "^0.6.4",
|
||||
"@aws-sdk/client-bedrock-runtime": "^3.758.0",
|
||||
"@bufbuild/protobuf": "^2.2.5",
|
||||
"@cerebras/cerebras_cloud_sdk": "^1.35.0",
|
||||
"@google-cloud/vertexai": "^1.9.3",
|
||||
"@google/genai": "^0.13.0",
|
||||
"@grpc/grpc-js": "^1.9.15",
|
||||
@@ -362,6 +359,7 @@
|
||||
"@opentelemetry/sdk-trace-node": "^1.30.1",
|
||||
"@opentelemetry/semantic-conventions": "^1.30.0",
|
||||
"@sentry/browser": "^9.12.0",
|
||||
"@streamparser/json": "^0.0.22",
|
||||
"@vscode/codicons": "^0.0.36",
|
||||
"archiver": "^7.0.1",
|
||||
"axios": "^1.8.2",
|
||||
@@ -371,6 +369,7 @@
|
||||
"clone-deep": "^4.0.1",
|
||||
"default-shell": "^2.2.0",
|
||||
"diff": "^5.2.0",
|
||||
"exceljs": "^4.4.0",
|
||||
"execa": "^9.5.2",
|
||||
"fast-deep-equal": "^3.1.3",
|
||||
"firebase": "^11.2.0",
|
||||
|
||||
@@ -16,4 +16,7 @@ service AccountService {
|
||||
// Handles the user clicking the logout button in the UI.
|
||||
// Clears API keys and user state.
|
||||
rpc accountLogoutClicked(EmptyRequest) returns (Empty);
|
||||
|
||||
// Subscribe to auth callback events (when authentication tokens are received)
|
||||
rpc subscribeToAuthCallback(EmptyRequest) returns (stream String);
|
||||
}
|
||||
|
||||
@@ -6,11 +6,44 @@ import { fileURLToPath } from "url"
|
||||
import { execSync } from "child_process"
|
||||
import { globby } from "globby"
|
||||
import chalk from "chalk"
|
||||
import os from "os"
|
||||
|
||||
import { createRequire } from "module"
|
||||
const require = createRequire(import.meta.url)
|
||||
const protoc = path.join(require.resolve("grpc-tools"), "../bin/protoc")
|
||||
|
||||
// Check for Apple Silicon compatibility
|
||||
function checkAppleSiliconCompatibility() {
|
||||
// Only run check on macOS
|
||||
if (process.platform !== "darwin") {
|
||||
return
|
||||
}
|
||||
|
||||
// Check if running on Apple Silicon
|
||||
const cpuArchitecture = os.arch()
|
||||
if (cpuArchitecture === "arm64") {
|
||||
try {
|
||||
// Check if Rosetta is installed
|
||||
const rosettaCheck = execSync('/usr/bin/pgrep oahd || echo "NOT_INSTALLED"').toString().trim()
|
||||
|
||||
if (rosettaCheck === "NOT_INSTALLED") {
|
||||
console.log(chalk.yellow("Detected Apple Silicon (ARM64) architecture."))
|
||||
console.log(
|
||||
chalk.red("Rosetta 2 is NOT installed. The npm version of protoc is not compatible with Apple Silicon."),
|
||||
)
|
||||
console.log(chalk.cyan("Please install Rosetta 2 using the following command:"))
|
||||
console.log(chalk.cyan(" softwareupdate --install-rosetta --agree-to-license"))
|
||||
console.log(chalk.red("Aborting build process."))
|
||||
process.exit(1)
|
||||
} else {
|
||||
console.log(chalk.green("Rosetta 2 is installed. Continuing with build."))
|
||||
}
|
||||
} catch (error) {
|
||||
console.log(chalk.yellow("Could not determine Rosetta installation status. Proceeding anyway."))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const __filename = fileURLToPath(import.meta.url)
|
||||
const SCRIPT_DIR = path.dirname(__filename)
|
||||
const ROOT_DIR = path.resolve(SCRIPT_DIR, "..")
|
||||
@@ -42,6 +75,9 @@ const serviceDirs = Object.keys(serviceNameMap).map((serviceKey) => path.join(RO
|
||||
async function main() {
|
||||
console.log(chalk.bold.blue("Starting Protocol Buffer code generation..."))
|
||||
|
||||
// Check for Apple Silicon compatibility before proceeding
|
||||
checkAppleSiliconCompatibility()
|
||||
|
||||
// Define output directories
|
||||
const TS_OUT_DIR = path.join(ROOT_DIR, "src", "shared", "proto")
|
||||
|
||||
|
||||
@@ -58,3 +58,8 @@ message Boolean {
|
||||
message StringArray {
|
||||
repeated string values = 1;
|
||||
}
|
||||
|
||||
message StringArrays {
|
||||
repeated string values1 = 1;
|
||||
repeated string values2 = 2;
|
||||
}
|
||||
|
||||
@@ -31,6 +31,9 @@ service FileService {
|
||||
|
||||
// Select images from the file system and return as data URLs
|
||||
rpc selectImages(EmptyRequest) returns (StringArray);
|
||||
|
||||
// Select images and other files from the file system and returns as data URLs & paths respectively
|
||||
rpc selectFiles(BooleanRequest) returns (StringArrays);
|
||||
|
||||
// Convert URIs to workspace-relative paths
|
||||
rpc getRelativePaths(RelativePathsRequest) returns (RelativePaths);
|
||||
@@ -49,6 +52,9 @@ service FileService {
|
||||
|
||||
// Refreshes all rule toggles (Cline, External, and Workflows)
|
||||
rpc refreshRules(EmptyRequest) returns (RefreshedRules);
|
||||
|
||||
// Opens a task's conversation history file on disk
|
||||
rpc openTaskHistory(StringRequest) returns (Empty);
|
||||
}
|
||||
|
||||
// Response for refreshRules operation
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
syntax = "proto3";
|
||||
package cline;
|
||||
option java_package = "bot.cline.proto";
|
||||
option java_multiple_files = true;
|
||||
|
||||
import "common.proto";
|
||||
|
||||
@@ -37,6 +39,7 @@ message ChatSettings {
|
||||
message ChatContent {
|
||||
optional string message = 1;
|
||||
repeated string images = 2;
|
||||
repeated string files = 3;
|
||||
}
|
||||
|
||||
// Message for auto approval settings
|
||||
|
||||
@@ -40,6 +40,7 @@ message NewTaskRequest {
|
||||
Metadata metadata = 1;
|
||||
string text = 2;
|
||||
repeated string images = 3;
|
||||
repeated string files = 4;
|
||||
}
|
||||
|
||||
// Request message for toggling task favorite status
|
||||
@@ -104,4 +105,5 @@ message AskResponseRequest {
|
||||
string response_type = 2;
|
||||
string text = 3;
|
||||
repeated string images = 4;
|
||||
repeated string files = 5;
|
||||
}
|
||||
|
||||
@@ -13,4 +13,7 @@ service UiService {
|
||||
|
||||
// Marks the current announcement as shown and returns whether an announcement should still be shown
|
||||
rpc onDidShowAnnouncement(EmptyRequest) returns (Boolean);
|
||||
|
||||
// Subscribe to addToInput events (when user adds content via context menu)
|
||||
rpc subscribeToAddToInput(EmptyRequest) returns (stream String);
|
||||
}
|
||||
|
||||
@@ -24,6 +24,7 @@ import { FireworksHandler } from "./providers/fireworks"
|
||||
import { AskSageHandler } from "./providers/asksage"
|
||||
import { XAIHandler } from "./providers/xai"
|
||||
import { SambanovaHandler } from "./providers/sambanova"
|
||||
import { CerebrasHandler } from "./providers/cerebras"
|
||||
|
||||
export interface ApiHandler {
|
||||
createMessage(systemPrompt: string, messages: Anthropic.Messages.MessageParam[]): ApiStream
|
||||
@@ -84,6 +85,8 @@ export function buildApiHandler(configuration: ApiConfiguration): ApiHandler {
|
||||
return new XAIHandler(options)
|
||||
case "sambanova":
|
||||
return new SambanovaHandler(options)
|
||||
case "cerebras":
|
||||
return new CerebrasHandler(options)
|
||||
default:
|
||||
return new AnthropicHandler(options)
|
||||
}
|
||||
|
||||
@@ -133,7 +133,7 @@ export class AnthropicHandler implements ApiHandler {
|
||||
}
|
||||
|
||||
for await (const chunk of stream) {
|
||||
switch (chunk.type) {
|
||||
switch (chunk?.type) {
|
||||
case "message_start":
|
||||
// tells us cache reads/writes/input/output
|
||||
const usage = chunk.message.usage
|
||||
|
||||
@@ -120,7 +120,7 @@ export class AwsBedrockHandler implements ApiHandler {
|
||||
)
|
||||
|
||||
for await (const chunk of stream) {
|
||||
switch (chunk.type) {
|
||||
switch (chunk?.type) {
|
||||
case "message_start":
|
||||
const usage = chunk.message.usage
|
||||
yield {
|
||||
@@ -223,8 +223,19 @@ export class AwsBedrockHandler implements ApiHandler {
|
||||
secretAccessKey: string
|
||||
sessionToken?: string
|
||||
}> {
|
||||
// Configure provider options
|
||||
const providerOptions: any = {}
|
||||
if (this.options.awsUseProfile) {
|
||||
// For profile-based auth, always use ignoreCache to detect credential file changes
|
||||
// This solves the AWS Identity Manager issue where credential files change externally
|
||||
providerOptions.ignoreCache = true
|
||||
if (this.options.awsProfile) {
|
||||
providerOptions.profile = this.options.awsProfile
|
||||
}
|
||||
}
|
||||
|
||||
// Create AWS credentials by executing an AWS provider chain
|
||||
const providerChain = fromNodeProviderChain()
|
||||
const providerChain = fromNodeProviderChain(providerOptions)
|
||||
return await AwsBedrockHandler.withTempEnv(
|
||||
() => {
|
||||
AwsBedrockHandler.setEnv("AWS_REGION", this.options.awsRegion)
|
||||
|
||||
@@ -0,0 +1,169 @@
|
||||
import { Anthropic } from "@anthropic-ai/sdk"
|
||||
import Cerebras from "@cerebras/cerebras_cloud_sdk"
|
||||
import { withRetry } from "../retry"
|
||||
import { ApiHandlerOptions, ModelInfo, CerebrasModelId, cerebrasDefaultModelId, cerebrasModels } from "@shared/api"
|
||||
import { ApiHandler } from "../index"
|
||||
import { ApiStream } from "@api/transform/stream"
|
||||
|
||||
export class CerebrasHandler implements ApiHandler {
|
||||
private options: ApiHandlerOptions
|
||||
private client: Cerebras
|
||||
|
||||
constructor(options: ApiHandlerOptions) {
|
||||
this.options = options
|
||||
|
||||
// Clean and validate the API key
|
||||
const cleanApiKey = this.options.cerebrasApiKey?.trim()
|
||||
|
||||
if (!cleanApiKey) {
|
||||
throw new Error("Cerebras API key is required")
|
||||
}
|
||||
|
||||
this.client = new Cerebras({
|
||||
apiKey: cleanApiKey,
|
||||
timeout: 30000, // 30 second timeout
|
||||
})
|
||||
}
|
||||
|
||||
@withRetry()
|
||||
async *createMessage(systemPrompt: string, messages: Anthropic.Messages.MessageParam[]): ApiStream {
|
||||
// Convert Anthropic messages to Cerebras format
|
||||
const cerebrasMessages: Array<{
|
||||
role: "system" | "user" | "assistant"
|
||||
content: string
|
||||
}> = [{ role: "system", content: systemPrompt }]
|
||||
|
||||
// Convert Anthropic messages to Cerebras format
|
||||
for (const message of messages) {
|
||||
if (message.role === "user") {
|
||||
const content = Array.isArray(message.content)
|
||||
? message.content
|
||||
.map((block) => {
|
||||
if (block.type === "text") {
|
||||
return block.text
|
||||
} else if (block.type === "image") {
|
||||
return "[Image content not supported in Cerebras]"
|
||||
}
|
||||
return ""
|
||||
})
|
||||
.join("\n")
|
||||
: message.content
|
||||
cerebrasMessages.push({ role: "user", content })
|
||||
} else if (message.role === "assistant") {
|
||||
const content = Array.isArray(message.content)
|
||||
? message.content
|
||||
.map((block) => {
|
||||
if (block.type === "text") {
|
||||
return block.text
|
||||
}
|
||||
return ""
|
||||
})
|
||||
.join("\n")
|
||||
: message.content || ""
|
||||
cerebrasMessages.push({ role: "assistant", content })
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
const stream = await this.client.chat.completions.create({
|
||||
model: this.getModel().id,
|
||||
messages: cerebrasMessages,
|
||||
temperature: 0,
|
||||
stream: true,
|
||||
})
|
||||
|
||||
// Handle streaming response
|
||||
let reasoning: string | null = null // Track reasoning content for models that support thinking
|
||||
const modelId = this.getModel().id
|
||||
const isReasoningModel = modelId.includes("qwen") || modelId.includes("deepseek-r1-distill")
|
||||
|
||||
for await (const chunk of stream as any) {
|
||||
// Type assertion for the streaming chunk
|
||||
const streamChunk = chunk as any
|
||||
|
||||
if (streamChunk.choices?.[0]?.delta?.content) {
|
||||
const content = streamChunk.choices[0].delta.content
|
||||
|
||||
// Handle reasoning models (Qwen and DeepSeek R1 Distill) that use <think> tags
|
||||
if (isReasoningModel) {
|
||||
// Check if we're entering or continuing reasoning mode
|
||||
if (reasoning || content.includes("<think>")) {
|
||||
reasoning = (reasoning || "") + content
|
||||
|
||||
// Clean the content by removing think tags for display
|
||||
let cleanContent = content.replace(/<think>/g, "").replace(/<\/think>/g, "")
|
||||
|
||||
// Only yield reasoning content if there's actual content after cleaning
|
||||
if (cleanContent.trim()) {
|
||||
yield {
|
||||
type: "reasoning",
|
||||
reasoning: cleanContent,
|
||||
}
|
||||
}
|
||||
|
||||
// Check if reasoning is complete
|
||||
if (reasoning.includes("</think>")) {
|
||||
reasoning = null
|
||||
}
|
||||
} else {
|
||||
// Regular content outside of thinking tags
|
||||
yield {
|
||||
type: "text",
|
||||
text: content,
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// Non-reasoning models - just yield text content
|
||||
yield {
|
||||
type: "text",
|
||||
text: content,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Handle usage information from Cerebras API
|
||||
// Usage is typically only available in the final chunk
|
||||
if (streamChunk.usage) {
|
||||
const totalCost = this.calculateCost({
|
||||
inputTokens: streamChunk.usage.prompt_tokens || 0,
|
||||
outputTokens: streamChunk.usage.completion_tokens || 0,
|
||||
})
|
||||
|
||||
yield {
|
||||
type: "usage",
|
||||
inputTokens: streamChunk.usage.prompt_tokens || 0,
|
||||
outputTokens: streamChunk.usage.completion_tokens || 0,
|
||||
cacheReadTokens: 0,
|
||||
cacheWriteTokens: 0,
|
||||
totalCost,
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
getModel(): { id: string; info: ModelInfo } {
|
||||
const modelId = this.options.apiModelId
|
||||
if (modelId && modelId in cerebrasModels) {
|
||||
const id = modelId as CerebrasModelId
|
||||
return { id, info: cerebrasModels[id] }
|
||||
}
|
||||
return {
|
||||
id: cerebrasDefaultModelId,
|
||||
info: cerebrasModels[cerebrasDefaultModelId],
|
||||
}
|
||||
}
|
||||
|
||||
private calculateCost({ inputTokens, outputTokens }: { inputTokens: number; outputTokens: number }): number {
|
||||
const model = this.getModel()
|
||||
const inputPrice = model.info.inputPrice || 0
|
||||
const outputPrice = model.info.outputPrice || 0
|
||||
|
||||
const inputCost = (inputPrice / 1_000_000) * inputTokens
|
||||
const outputCost = (outputPrice / 1_000_000) * outputTokens
|
||||
|
||||
return inputCost + outputCost
|
||||
}
|
||||
}
|
||||
@@ -80,7 +80,9 @@ export class OllamaHandler implements ApiHandler {
|
||||
getModel(): { id: string; info: ModelInfo } {
|
||||
return {
|
||||
id: this.options.ollamaModelId || "",
|
||||
info: openAiModelInfoSaneDefaults,
|
||||
info: this.options.ollamaApiOptionsCtxNum
|
||||
? { ...openAiModelInfoSaneDefaults, contextWindow: Number(this.options.ollamaApiOptionsCtxNum) || 32768 }
|
||||
: openAiModelInfoSaneDefaults,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -98,6 +98,10 @@ export class OpenAiHandler implements ApiHandler {
|
||||
type: "usage",
|
||||
inputTokens: chunk.usage.prompt_tokens || 0,
|
||||
outputTokens: chunk.usage.completion_tokens || 0,
|
||||
// @ts-ignore-next-line
|
||||
cacheReadTokens: chunk.usage.prompt_tokens_details?.cached_tokens || 0,
|
||||
// @ts-ignore-next-line
|
||||
cacheWriteTokens: chunk.usage.prompt_cache_miss_tokens || 0,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -154,7 +154,7 @@ export class VertexHandler implements ApiHandler {
|
||||
}
|
||||
|
||||
for await (const chunk of stream) {
|
||||
switch (chunk.type) {
|
||||
switch (chunk?.type) {
|
||||
case "message_start":
|
||||
const usage = chunk.message.usage
|
||||
yield {
|
||||
|
||||
@@ -58,10 +58,10 @@ export class XAIHandler implements ApiHandler {
|
||||
if (chunk.usage) {
|
||||
yield {
|
||||
type: "usage",
|
||||
inputTokens: 0,
|
||||
inputTokens: chunk.usage.prompt_tokens || 0,
|
||||
outputTokens: chunk.usage.completion_tokens || 0,
|
||||
// @ts-ignore-next-line
|
||||
cacheReadTokens: chunk.usage.prompt_cache_hit_tokens || 0,
|
||||
cacheReadTokens: chunk.usage.prompt_tokens_details?.cached_tokens || 0,
|
||||
// @ts-ignore-next-line
|
||||
cacheWriteTokens: chunk.usage.prompt_cache_miss_tokens || 0,
|
||||
}
|
||||
|
||||
@@ -0,0 +1,135 @@
|
||||
import { JSONParser } from "@streamparser/json"
|
||||
|
||||
// Fallback type definition based on the error message: "Property 'value' is optional in type 'ParsedElementInfo'"
|
||||
type ParsedElementInfo = {
|
||||
value?: any
|
||||
key?: string | number
|
||||
parent?: any
|
||||
stack?: any[]
|
||||
}
|
||||
|
||||
export interface ReplacementItem {
|
||||
old_str: string
|
||||
new_str: string
|
||||
}
|
||||
|
||||
export interface ChangeLocation {
|
||||
startLine: number
|
||||
endLine: number
|
||||
startChar: number
|
||||
endChar: number
|
||||
}
|
||||
|
||||
export class StreamingJsonReplacer {
|
||||
private currentFileContent: string
|
||||
private parser: JSONParser
|
||||
private onContentUpdated: (newContent: string, isFinalItem: boolean, changeLocation?: ChangeLocation) => void
|
||||
private onErrorCallback: (error: Error) => void
|
||||
private itemsProcessed: number = 0
|
||||
private successfullyParsedItems: ReplacementItem[] = []
|
||||
|
||||
constructor(
|
||||
initialContent: string,
|
||||
onContentUpdatedCallback: (newContent: string, isFinalItem: boolean, changeLocation?: ChangeLocation) => void,
|
||||
onErrorCallback: (error: Error) => void,
|
||||
) {
|
||||
this.currentFileContent = initialContent
|
||||
this.onContentUpdated = onContentUpdatedCallback
|
||||
this.onErrorCallback = onErrorCallback
|
||||
|
||||
this.parser = new JSONParser({ paths: ["$.replacements.*"] })
|
||||
|
||||
this.parser.onValue = (parsedElementInfo: ParsedElementInfo) => {
|
||||
const { value } = parsedElementInfo // Destructure to get value, which might be undefined
|
||||
// This callback is triggered for each item matched by '$.replacements.*'
|
||||
if (value && typeof value === "object" && "old_str" in value && "new_str" in value) {
|
||||
const item = value as ReplacementItem // Value here is confirmed to be an object
|
||||
|
||||
if (typeof item.old_str === "string" && typeof item.new_str === "string") {
|
||||
this.successfullyParsedItems.push(item) // Store the structurally valid item
|
||||
|
||||
if (this.currentFileContent.includes(item.old_str)) {
|
||||
// Calculate the change location before making the replacement
|
||||
const changeLocation = this.calculateChangeLocation(item.old_str, item.new_str)
|
||||
|
||||
this.currentFileContent = this.currentFileContent.replace(item.old_str, item.new_str)
|
||||
this.itemsProcessed++
|
||||
// Notify that an item has been processed. The `isFinalItem` argument here is tricky
|
||||
// as we don't know from the parser alone if this is the *absolute* last item
|
||||
// until the stream ends. The caller (Task.ts) will manage the final update.
|
||||
// For now, we'll pass `false` and let Task.ts handle the final diff view update.
|
||||
this.onContentUpdated(this.currentFileContent, false, changeLocation)
|
||||
} else {
|
||||
const snippet = item.old_str.length > 50 ? item.old_str.substring(0, 47) + "..." : item.old_str
|
||||
const error = new Error(`Streaming Replacement failed: 'old_str' not found. Snippet: "${snippet}"`)
|
||||
this.onErrorCallback(error) // Call our own error callback
|
||||
}
|
||||
} else {
|
||||
const error = new Error(`Invalid item structure in replacements stream: ${JSON.stringify(item)}`)
|
||||
this.onErrorCallback(error) // Call our own error callback
|
||||
}
|
||||
} else if (value && (Array.isArray(value) || (typeof value === "object" && "replacements" in value))) {
|
||||
// This might be the 'replacements' array itself or the root object.
|
||||
// The `paths: ['$.replacements.*']` should mean we only get items.
|
||||
// If we get here, it's likely the root object if paths wasn't specific enough or if it's an empty replacements array.
|
||||
console.log("Streaming parser emitted container:", value)
|
||||
} else {
|
||||
// Value is not a ReplacementItem or a known container, could be an issue with the JSON structure or path.
|
||||
// If `paths` is correct, this path should ideally not be hit often for valid streams.
|
||||
console.warn("Streaming parser emitted unexpected value:", value)
|
||||
}
|
||||
}
|
||||
|
||||
this.parser.onError = (err: Error) => {
|
||||
// Propagate the error to the caller via the callback
|
||||
this.onErrorCallback(err)
|
||||
// Note: The @streamparser/json library might throw synchronously on write if onError is not set,
|
||||
// or if it re-throws. We'll ensure Task.ts wraps write/end in try-catch.
|
||||
}
|
||||
}
|
||||
|
||||
public write(jsonChunk: string): void {
|
||||
// Errors during write will be caught by the parser's onError or thrown.
|
||||
this.parser.write(jsonChunk)
|
||||
}
|
||||
|
||||
public getCurrentContent(): string {
|
||||
return this.currentFileContent
|
||||
}
|
||||
|
||||
public getSuccessfullyParsedItems(): ReplacementItem[] {
|
||||
return [...this.successfullyParsedItems] // Return a copy
|
||||
}
|
||||
|
||||
private calculateChangeLocation(oldStr: string, newStr: string): ChangeLocation {
|
||||
// Find the index where the old string starts
|
||||
const startIndex = this.currentFileContent.indexOf(oldStr)
|
||||
if (startIndex === -1) {
|
||||
// This shouldn't happen since we already checked includes(), but just in case
|
||||
return { startLine: 0, endLine: 0, startChar: 0, endChar: 0 }
|
||||
}
|
||||
|
||||
// Calculate line numbers by counting newlines before the start index
|
||||
const contentBeforeStart = this.currentFileContent.substring(0, startIndex)
|
||||
const startLine = (contentBeforeStart.match(/\n/g) || []).length
|
||||
|
||||
// Calculate the end index after replacement
|
||||
const endIndex = startIndex + oldStr.length
|
||||
const contentBeforeEnd = this.currentFileContent.substring(0, endIndex)
|
||||
const endLine = (contentBeforeEnd.match(/\n/g) || []).length
|
||||
|
||||
// Calculate character positions within their respective lines
|
||||
const lastNewlineBeforeStart = contentBeforeStart.lastIndexOf("\n")
|
||||
const startChar = lastNewlineBeforeStart === -1 ? startIndex : startIndex - lastNewlineBeforeStart - 1
|
||||
|
||||
const lastNewlineBeforeEnd = contentBeforeEnd.lastIndexOf("\n")
|
||||
const endChar = lastNewlineBeforeEnd === -1 ? endIndex : endIndex - lastNewlineBeforeEnd - 1
|
||||
|
||||
return {
|
||||
startLine,
|
||||
endLine,
|
||||
startChar,
|
||||
endChar,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -27,6 +27,7 @@ export const toolUseNames = [
|
||||
"condense",
|
||||
"report_bug",
|
||||
"new_rule",
|
||||
"web_fetch",
|
||||
] as const
|
||||
|
||||
// Converts array of tool call names into a union type ("execute_command" | "read_file" | ...)
|
||||
|
||||
@@ -473,3 +473,594 @@ export function parseAssistantMessageV2(assistantMessage: string): AssistantMess
|
||||
|
||||
return contentBlocks
|
||||
}
|
||||
|
||||
export function parseAssistantMessageV3(assistantMessage: string): AssistantMessageContent[] {
|
||||
const contentBlocks: AssistantMessageContent[] = []
|
||||
let currentTextContentStart = 0 // Index where the current text block started
|
||||
let currentTextContent: TextContent | undefined = undefined
|
||||
let currentToolUseStart = 0 // Index *after* the opening tag of the current tool use
|
||||
let currentToolUse: ToolUse | undefined = undefined
|
||||
let currentParamValueStart = 0 // Index *after* the opening tag of the current param
|
||||
let currentParamName: ToolParamName | undefined = undefined
|
||||
|
||||
// Precompute tags for faster lookups
|
||||
const toolUseOpenTags = new Map<string, ToolUseName>()
|
||||
const toolParamOpenTags = new Map<string, ToolParamName>()
|
||||
for (const name of toolUseNames) {
|
||||
toolUseOpenTags.set(`<${name}>`, name)
|
||||
}
|
||||
for (const name of toolParamNames) {
|
||||
toolParamOpenTags.set(`<${name}>`, name)
|
||||
}
|
||||
|
||||
// Function calls format detection
|
||||
const isFunctionCallsOpen = "<function_calls>"
|
||||
const isFunctionCallsClose = "</function_calls>"
|
||||
const isInvokeStart = '<invoke name="'
|
||||
const isInvokeEnd = '">'
|
||||
const isInvokeClose = "</invoke>"
|
||||
const isParameterStart = '<parameter name="'
|
||||
const isParameterNameEnd = '">'
|
||||
const isParameterClose = "</parameter>"
|
||||
|
||||
// Variables for function calls parsing
|
||||
let inFunctionCalls = false
|
||||
let currentInvokeName = ""
|
||||
let currentParameterName = ""
|
||||
|
||||
const len = assistantMessage.length
|
||||
for (let i = 0; i < len; i++) {
|
||||
const currentCharIndex = i
|
||||
|
||||
// --- State: Parsing Function Calls ---
|
||||
// Check for opening function_calls tag
|
||||
if (
|
||||
!inFunctionCalls &&
|
||||
currentCharIndex >= isFunctionCallsOpen.length - 1 &&
|
||||
assistantMessage.startsWith(isFunctionCallsOpen, currentCharIndex - isFunctionCallsOpen.length + 1)
|
||||
) {
|
||||
// End current text block if one was active
|
||||
if (currentTextContent) {
|
||||
currentTextContent.content = assistantMessage
|
||||
.slice(currentTextContentStart, currentCharIndex - isFunctionCallsOpen.length + 1)
|
||||
.trim()
|
||||
currentTextContent.partial = false
|
||||
if (currentTextContent.content.length > 0) {
|
||||
contentBlocks.push(currentTextContent)
|
||||
}
|
||||
currentTextContent = undefined
|
||||
}
|
||||
|
||||
inFunctionCalls = true
|
||||
continue
|
||||
}
|
||||
|
||||
// Check for invoke start within function_calls
|
||||
if (
|
||||
inFunctionCalls &&
|
||||
currentInvokeName === "" &&
|
||||
currentCharIndex >= isInvokeStart.length - 1 &&
|
||||
assistantMessage.startsWith(isInvokeStart, currentCharIndex - isInvokeStart.length + 1)
|
||||
) {
|
||||
// Find the end of the invoke name
|
||||
const nameEndPos = assistantMessage.indexOf(isInvokeEnd, currentCharIndex + 1)
|
||||
if (nameEndPos !== -1) {
|
||||
// Extract the invoke name
|
||||
currentInvokeName = assistantMessage.slice(currentCharIndex + 1, nameEndPos)
|
||||
i = nameEndPos + isInvokeEnd.length - 1 // Skip to after the '">
|
||||
|
||||
// If this is an LS invoke, create a list_files tool
|
||||
if (currentInvokeName === "LS") {
|
||||
currentToolUse = {
|
||||
type: "tool_use",
|
||||
name: "list_files",
|
||||
params: {},
|
||||
partial: true,
|
||||
}
|
||||
}
|
||||
|
||||
// If this is a Grep invoke, create a search_files tool
|
||||
if (currentInvokeName === "Grep") {
|
||||
currentToolUse = {
|
||||
type: "tool_use",
|
||||
name: "search_files",
|
||||
params: {},
|
||||
partial: true,
|
||||
}
|
||||
}
|
||||
|
||||
if (currentInvokeName === "Bash") {
|
||||
currentToolUse = {
|
||||
type: "tool_use",
|
||||
name: "execute_command",
|
||||
params: {},
|
||||
partial: true,
|
||||
}
|
||||
}
|
||||
|
||||
if (currentInvokeName === "Read") {
|
||||
currentToolUse = {
|
||||
type: "tool_use",
|
||||
name: "read_file",
|
||||
params: {},
|
||||
partial: true,
|
||||
}
|
||||
}
|
||||
|
||||
if (currentInvokeName === "Write") {
|
||||
currentToolUse = {
|
||||
type: "tool_use",
|
||||
name: "write_to_file",
|
||||
params: {},
|
||||
partial: true,
|
||||
}
|
||||
}
|
||||
|
||||
if (currentInvokeName === "WebFetch") {
|
||||
currentToolUse = {
|
||||
type: "tool_use",
|
||||
name: "web_fetch",
|
||||
params: {},
|
||||
partial: true,
|
||||
}
|
||||
}
|
||||
|
||||
if (currentInvokeName === "AskQuestion") {
|
||||
currentToolUse = {
|
||||
type: "tool_use",
|
||||
name: "ask_followup_question",
|
||||
params: {},
|
||||
partial: true,
|
||||
}
|
||||
}
|
||||
|
||||
if (currentInvokeName === "UseMCPTool") {
|
||||
currentToolUse = {
|
||||
type: "tool_use",
|
||||
name: "use_mcp_tool",
|
||||
params: {},
|
||||
partial: true,
|
||||
}
|
||||
}
|
||||
|
||||
if (currentInvokeName === "AccessMCPResource") {
|
||||
currentToolUse = {
|
||||
type: "tool_use",
|
||||
name: "access_mcp_resource",
|
||||
params: {},
|
||||
partial: true,
|
||||
}
|
||||
}
|
||||
|
||||
if (currentInvokeName === "ListCodeDefinitionNames") {
|
||||
currentToolUse = {
|
||||
type: "tool_use",
|
||||
name: "list_code_definition_names",
|
||||
params: {},
|
||||
partial: true,
|
||||
}
|
||||
}
|
||||
|
||||
if (currentInvokeName === "PlanModeRespond") {
|
||||
currentToolUse = {
|
||||
type: "tool_use",
|
||||
name: "plan_mode_respond",
|
||||
params: {},
|
||||
partial: true,
|
||||
}
|
||||
}
|
||||
|
||||
if (currentInvokeName === "LoadMcpDocumentation") {
|
||||
currentToolUse = {
|
||||
type: "tool_use",
|
||||
name: "load_mcp_documentation",
|
||||
params: {},
|
||||
partial: true,
|
||||
}
|
||||
}
|
||||
|
||||
if (currentInvokeName === "AttemptCompletion") {
|
||||
currentToolUse = {
|
||||
type: "tool_use",
|
||||
name: "attempt_completion",
|
||||
params: {},
|
||||
partial: true,
|
||||
}
|
||||
}
|
||||
|
||||
if (currentInvokeName === "BrowserAction") {
|
||||
currentToolUse = {
|
||||
type: "tool_use",
|
||||
name: "browser_action",
|
||||
params: {},
|
||||
partial: true,
|
||||
}
|
||||
}
|
||||
|
||||
if (currentInvokeName === "NewTask") {
|
||||
currentToolUse = {
|
||||
type: "tool_use",
|
||||
name: "new_task",
|
||||
params: {},
|
||||
partial: true,
|
||||
}
|
||||
}
|
||||
|
||||
continue
|
||||
}
|
||||
}
|
||||
|
||||
// Check for parameter start within invoke
|
||||
if (
|
||||
inFunctionCalls &&
|
||||
currentInvokeName !== "" &&
|
||||
currentParameterName === "" &&
|
||||
currentCharIndex >= isParameterStart.length - 1 &&
|
||||
assistantMessage.startsWith(isParameterStart, currentCharIndex - isParameterStart.length + 1)
|
||||
) {
|
||||
// Find the end of the parameter name
|
||||
const nameEndPos = assistantMessage.indexOf(isParameterNameEnd, currentCharIndex + 1)
|
||||
if (nameEndPos !== -1) {
|
||||
// Extract the parameter name
|
||||
currentParameterName = assistantMessage.slice(currentCharIndex + 1, nameEndPos)
|
||||
currentParamValueStart = nameEndPos + isParameterNameEnd.length
|
||||
i = nameEndPos + isParameterNameEnd.length - 1 // Skip to after the '">'
|
||||
continue
|
||||
}
|
||||
}
|
||||
|
||||
// Check for parameter end
|
||||
if (
|
||||
inFunctionCalls &&
|
||||
currentInvokeName !== "" &&
|
||||
currentParameterName !== "" &&
|
||||
currentCharIndex >= isParameterClose.length - 1 &&
|
||||
assistantMessage.startsWith(isParameterClose, currentCharIndex - isParameterClose.length + 1)
|
||||
) {
|
||||
// Extract parameter value
|
||||
const value = assistantMessage.slice(currentParamValueStart, currentCharIndex - isParameterClose.length + 1).trim()
|
||||
|
||||
// Map parameter to tool params
|
||||
if (currentToolUse && currentInvokeName === "LS" && currentParameterName === "path") {
|
||||
currentToolUse.params["path"] = value
|
||||
// Default recursive to false - only show top level
|
||||
currentToolUse.params["recursive"] = "false"
|
||||
}
|
||||
|
||||
if (currentToolUse && currentInvokeName === "Read" && currentParameterName === "file_path") {
|
||||
currentToolUse.params["path"] = value
|
||||
}
|
||||
|
||||
if (currentToolUse && currentInvokeName === "PlanModeRespond" && currentParameterName === "response") {
|
||||
currentToolUse.params["response"] = value
|
||||
}
|
||||
|
||||
if (currentToolUse && currentInvokeName === "WebFetch" && currentParameterName === "url") {
|
||||
currentToolUse.params["url"] = value
|
||||
}
|
||||
|
||||
if (currentToolUse && currentInvokeName === "ListCodeDefinitionNames" && currentParameterName === "path") {
|
||||
currentToolUse.params["path"] = value
|
||||
}
|
||||
|
||||
if (currentToolUse && currentInvokeName === "NewTask" && currentParameterName === "context") {
|
||||
currentToolUse.params["context"] = value
|
||||
}
|
||||
|
||||
// Map parameter to tool params for Grep
|
||||
if (currentToolUse && currentInvokeName === "Grep") {
|
||||
if (currentParameterName === "pattern") {
|
||||
currentToolUse.params["regex"] = value
|
||||
} else if (currentParameterName === "path") {
|
||||
currentToolUse.params["path"] = value
|
||||
} else if (currentParameterName === "include") {
|
||||
currentToolUse.params["file_pattern"] = value
|
||||
}
|
||||
}
|
||||
|
||||
if (currentToolUse && currentInvokeName === "Bash") {
|
||||
if (currentParameterName === "command") {
|
||||
currentToolUse.params["command"] = value
|
||||
} else if (currentParameterName === "requires_approval") {
|
||||
currentToolUse.params["requires_approval"] = value === "true" ? "true" : "false"
|
||||
}
|
||||
}
|
||||
|
||||
if (currentToolUse && currentInvokeName === "Write") {
|
||||
if (currentParameterName === "file_path") {
|
||||
currentToolUse.params["path"] = value
|
||||
} else if (currentParameterName === "content") {
|
||||
currentToolUse.params["content"] = value
|
||||
}
|
||||
}
|
||||
|
||||
if (currentToolUse && currentInvokeName === "AskQuestion") {
|
||||
if (currentParameterName === "question") {
|
||||
currentToolUse.params["question"] = value
|
||||
} else if (currentParameterName === "options") {
|
||||
currentToolUse.params["options"] = value
|
||||
}
|
||||
}
|
||||
|
||||
if (currentToolUse && currentInvokeName === "UseMCPTool") {
|
||||
if (currentParameterName === "server_name") {
|
||||
currentToolUse.params["server_name"] = value
|
||||
} else if (currentParameterName === "tool_name") {
|
||||
currentToolUse.params["tool_name"] = value
|
||||
} else if (currentParameterName === "arguments") {
|
||||
currentToolUse.params["arguments"] = value
|
||||
}
|
||||
}
|
||||
|
||||
if (currentToolUse && currentInvokeName === "AccessMCPResource") {
|
||||
if (currentParameterName === "server_name") {
|
||||
currentToolUse.params["server_name"] = value
|
||||
} else if (currentParameterName === "uri") {
|
||||
currentToolUse.params["uri"] = value
|
||||
}
|
||||
}
|
||||
|
||||
if (currentToolUse && currentInvokeName === "AttemptCompletion") {
|
||||
if (currentParameterName === "result") {
|
||||
currentToolUse.params["result"] = value
|
||||
}
|
||||
if (currentParameterName === "command") {
|
||||
currentToolUse.params["command"] = value
|
||||
}
|
||||
}
|
||||
|
||||
if (currentToolUse && currentInvokeName === "BrowserAction") {
|
||||
if (currentParameterName === "action") {
|
||||
currentToolUse.params["action"] = value
|
||||
} else if (currentParameterName === "url") {
|
||||
currentToolUse.params["url"] = value
|
||||
} else if (currentParameterName === "coordinate") {
|
||||
currentToolUse.params["coordinate"] = value
|
||||
} else if (currentParameterName === "text") {
|
||||
currentToolUse.params["text"] = value
|
||||
}
|
||||
}
|
||||
|
||||
currentParameterName = ""
|
||||
continue
|
||||
}
|
||||
|
||||
// Check for invoke end
|
||||
if (
|
||||
inFunctionCalls &&
|
||||
currentInvokeName !== "" &&
|
||||
currentCharIndex >= isInvokeClose.length - 1 &&
|
||||
assistantMessage.startsWith(isInvokeClose, currentCharIndex - isInvokeClose.length + 1)
|
||||
) {
|
||||
// If we have a tool use from this invoke, finalize it
|
||||
if (
|
||||
currentToolUse &&
|
||||
(currentInvokeName === "LS" ||
|
||||
currentInvokeName === "Grep" ||
|
||||
currentInvokeName === "Bash" ||
|
||||
currentInvokeName === "Read" ||
|
||||
currentInvokeName === "Write" ||
|
||||
currentInvokeName === "WebFetch" ||
|
||||
currentInvokeName === "AskQuestion" ||
|
||||
currentInvokeName === "UseMCPTool" ||
|
||||
currentInvokeName === "AccessMCPResource" ||
|
||||
currentInvokeName === "ListCodeDefinitionNames" ||
|
||||
currentInvokeName === "PlanModeRespond" ||
|
||||
currentInvokeName === "LoadMcpDocumentation" ||
|
||||
currentInvokeName === "AttemptCompletion" ||
|
||||
currentInvokeName === "BrowserAction" ||
|
||||
currentInvokeName === "NewTask")
|
||||
) {
|
||||
currentToolUse.partial = false
|
||||
contentBlocks.push(currentToolUse)
|
||||
currentToolUse = undefined
|
||||
}
|
||||
|
||||
currentInvokeName = ""
|
||||
continue
|
||||
}
|
||||
|
||||
// Check for function_calls end
|
||||
if (
|
||||
inFunctionCalls &&
|
||||
currentCharIndex >= isFunctionCallsClose.length - 1 &&
|
||||
assistantMessage.startsWith(isFunctionCallsClose, currentCharIndex - isFunctionCallsClose.length + 1)
|
||||
) {
|
||||
inFunctionCalls = false
|
||||
currentTextContentStart = currentCharIndex + 1
|
||||
continue
|
||||
}
|
||||
|
||||
// Skip normal parsing when inside function_calls
|
||||
if (inFunctionCalls) {
|
||||
continue
|
||||
}
|
||||
|
||||
// --- State: Parsing a Tool Parameter ---
|
||||
if (currentToolUse && currentParamName) {
|
||||
const closeTag = `</${currentParamName}>`
|
||||
// Check if the string *ending* at index `i` matches the closing tag
|
||||
if (
|
||||
currentCharIndex >= closeTag.length - 1 &&
|
||||
assistantMessage.startsWith(
|
||||
closeTag,
|
||||
currentCharIndex - closeTag.length + 1, // Start checking from potential start of tag
|
||||
)
|
||||
) {
|
||||
// Found the closing tag for the parameter
|
||||
const value = assistantMessage
|
||||
.slice(
|
||||
currentParamValueStart, // Start after the opening tag
|
||||
currentCharIndex - closeTag.length + 1, // End before the closing tag
|
||||
)
|
||||
.trim()
|
||||
currentToolUse.params[currentParamName] = value
|
||||
currentParamName = undefined // Go back to parsing tool content
|
||||
// We don't continue loop here, need to check for tool close or other params at index i
|
||||
} else {
|
||||
continue // Still inside param value, move to next char
|
||||
}
|
||||
}
|
||||
|
||||
// --- State: Parsing a Tool Use (but not a specific parameter) ---
|
||||
if (currentToolUse && !currentParamName) {
|
||||
// Ensure we are not inside a parameter already
|
||||
// Check if starting a new parameter
|
||||
let startedNewParam = false
|
||||
for (const [tag, paramName] of toolParamOpenTags.entries()) {
|
||||
if (currentCharIndex >= tag.length - 1 && assistantMessage.startsWith(tag, currentCharIndex - tag.length + 1)) {
|
||||
currentParamName = paramName
|
||||
currentParamValueStart = currentCharIndex + 1 // Value starts after the tag
|
||||
startedNewParam = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if (startedNewParam) {
|
||||
continue // Handled start of param, move to next char
|
||||
}
|
||||
|
||||
// Check if closing the current tool use
|
||||
const toolCloseTag = `</${currentToolUse.name}>`
|
||||
if (
|
||||
currentCharIndex >= toolCloseTag.length - 1 &&
|
||||
assistantMessage.startsWith(toolCloseTag, currentCharIndex - toolCloseTag.length + 1)
|
||||
) {
|
||||
// End of the tool use found
|
||||
// Special handling for content params *before* finalizing the tool
|
||||
const toolContentSlice = assistantMessage.slice(
|
||||
currentToolUseStart, // From after the tool opening tag
|
||||
currentCharIndex - toolCloseTag.length + 1, // To before the tool closing tag
|
||||
)
|
||||
|
||||
// Check if content parameter needs special handling (write_to_file/new_rule)
|
||||
// This check is important if the closing </content> tag was missed by the parameter parsing logic
|
||||
// (e.g., if content is empty or parsing logic prioritizes tool close)
|
||||
const contentParamName: ToolParamName = "content"
|
||||
if (
|
||||
currentToolUse.name === "write_to_file" /* || currentToolUse.name === "new_rule" */ &&
|
||||
toolContentSlice.includes(`<${contentParamName}>`)
|
||||
) {
|
||||
const contentStartTag = `<${contentParamName}>`
|
||||
const contentEndTag = `</${contentParamName}>`
|
||||
const contentStart = toolContentSlice.indexOf(contentStartTag)
|
||||
// Use lastIndexOf for robustness against nested tags
|
||||
const contentEnd = toolContentSlice.lastIndexOf(contentEndTag)
|
||||
|
||||
if (contentStart !== -1 && contentEnd !== -1 && contentEnd > contentStart) {
|
||||
const contentValue = toolContentSlice.slice(contentStart + contentStartTag.length, contentEnd).trim()
|
||||
currentToolUse.params[contentParamName] = contentValue
|
||||
}
|
||||
}
|
||||
|
||||
currentToolUse.partial = false // Mark as complete
|
||||
contentBlocks.push(currentToolUse)
|
||||
currentToolUse = undefined // Reset state
|
||||
currentTextContentStart = currentCharIndex + 1 // Potential text starts after this tag
|
||||
continue // Move to next char
|
||||
}
|
||||
// If not starting a param and not closing the tool, continue accumulating tool content implicitly
|
||||
continue
|
||||
}
|
||||
|
||||
// --- State: Parsing Text / Looking for Tool Start ---
|
||||
if (!currentToolUse) {
|
||||
// Check if starting a new tool use
|
||||
let startedNewTool = false
|
||||
for (const [tag, toolName] of toolUseOpenTags.entries()) {
|
||||
if (currentCharIndex >= tag.length - 1 && assistantMessage.startsWith(tag, currentCharIndex - tag.length + 1)) {
|
||||
// End current text block if one was active
|
||||
if (currentTextContent) {
|
||||
currentTextContent.content = assistantMessage
|
||||
.slice(
|
||||
currentTextContentStart, // From where text started
|
||||
currentCharIndex - tag.length + 1, // To before the tool tag starts
|
||||
)
|
||||
.trim()
|
||||
currentTextContent.partial = false // Ended because tool started
|
||||
if (currentTextContent.content.length > 0) {
|
||||
contentBlocks.push(currentTextContent)
|
||||
}
|
||||
currentTextContent = undefined
|
||||
} else {
|
||||
// Check for any text between the last block and this tag
|
||||
const potentialText = assistantMessage
|
||||
.slice(
|
||||
currentTextContentStart, // From where text *might* have started
|
||||
currentCharIndex - tag.length + 1, // To before the tool tag starts
|
||||
)
|
||||
.trim()
|
||||
if (potentialText.length > 0) {
|
||||
contentBlocks.push({
|
||||
type: "text",
|
||||
content: potentialText,
|
||||
partial: false,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Start the new tool use
|
||||
currentToolUse = {
|
||||
type: "tool_use",
|
||||
name: toolName,
|
||||
params: {},
|
||||
partial: true, // Assume partial until closing tag is found
|
||||
}
|
||||
currentToolUseStart = currentCharIndex + 1 // Tool content starts after the opening tag
|
||||
startedNewTool = true
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
if (startedNewTool) {
|
||||
continue // Handled start of tool, move to next char
|
||||
}
|
||||
|
||||
// If not starting a tool, it must be text content
|
||||
if (!currentTextContent) {
|
||||
// Start a new text block if we aren't already in one
|
||||
currentTextContentStart = currentCharIndex // Text starts at the current character
|
||||
// Check if the current char is the start of potential text *immediately* after a tag
|
||||
// This needs the previous state - simpler to let slicing handle it later.
|
||||
// Resetting start index accurately is key.
|
||||
// It should be the index *after* the last processed tag.
|
||||
// The logic managing currentTextContentStart after closing tags handles this.
|
||||
|
||||
currentTextContent = {
|
||||
type: "text",
|
||||
content: "", // Will be determined by slicing at the end or when a tool starts
|
||||
partial: true,
|
||||
}
|
||||
}
|
||||
// Continue accumulating text implicitly; content is extracted later.
|
||||
}
|
||||
} // End of loop
|
||||
|
||||
// --- Finalization after loop ---
|
||||
|
||||
// Finalize any open parameter within an open tool use
|
||||
if (currentToolUse && currentParamName) {
|
||||
currentToolUse.params[currentParamName] = assistantMessage
|
||||
.slice(currentParamValueStart) // From param start to end of string
|
||||
.trim()
|
||||
// Tool use remains partial
|
||||
}
|
||||
|
||||
// Finalize any open tool use (which might contain the finalized partial param)
|
||||
if (currentToolUse) {
|
||||
// Tool use is partial because the loop finished before its closing tag
|
||||
contentBlocks.push(currentToolUse)
|
||||
}
|
||||
// Finalize any trailing text content
|
||||
// Only possible if a tool use wasn't open at the very end
|
||||
else if (currentTextContent) {
|
||||
currentTextContent.content = assistantMessage
|
||||
.slice(currentTextContentStart) // From text start to end of string
|
||||
.trim()
|
||||
// Text is partial because the loop finished
|
||||
if (currentTextContent.content.length > 0) {
|
||||
contentBlocks.push(currentTextContent)
|
||||
}
|
||||
}
|
||||
|
||||
return contentBlocks
|
||||
}
|
||||
|
||||
@@ -12,7 +12,7 @@ import { EmptyRequest, String } from "../../../shared/proto/common"
|
||||
* @param controller The controller instance.
|
||||
* @returns The login URL as a string.
|
||||
*/
|
||||
export async function accountLoginClicked(controller: Controller, unused: EmptyRequest): Promise<String> {
|
||||
export async function accountLoginClicked(controller: Controller, _: EmptyRequest): Promise<String> {
|
||||
// Generate nonce for state validation
|
||||
const nonce = crypto.randomBytes(32).toString("hex")
|
||||
await storeSecret(controller.context, "authNonce", nonce)
|
||||
@@ -27,7 +27,7 @@ export async function accountLoginClicked(controller: Controller, unused: EmptyR
|
||||
`https://app.cline.bot/auth?state=${encodeURIComponent(nonce)}&callback_url=${encodeURIComponent(`${uriScheme || "vscode"}://saoudrizwan.claude-dev/auth`)}`,
|
||||
)
|
||||
await vscode.env.openExternal(authUrl)
|
||||
return {
|
||||
return String.create({
|
||||
value: authUrl.toString(),
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { Empty } from "../../../shared/proto/common"
|
||||
import { Empty } from "../../../shared/proto/common"
|
||||
import type { EmptyRequest } from "../../../shared/proto/common"
|
||||
import type { Controller } from "../index"
|
||||
|
||||
@@ -10,5 +10,5 @@ import type { Controller } from "../index"
|
||||
*/
|
||||
export async function accountLogoutClicked(controller: Controller, _request: EmptyRequest): Promise<Empty> {
|
||||
await controller.handleSignOut()
|
||||
return {}
|
||||
return Empty.create({})
|
||||
}
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
import { Controller } from "../index"
|
||||
import { EmptyRequest } from "../../../shared/proto/common"
|
||||
import { String as ProtoString } from "../../../shared/proto/common"
|
||||
import { StreamingResponseHandler, getRequestRegistry } from "../grpc-handler"
|
||||
|
||||
// Keep track of active authCallback subscriptions
|
||||
const activeAuthCallbackSubscriptions = new Set<StreamingResponseHandler>()
|
||||
|
||||
/**
|
||||
* Subscribe to authCallback events
|
||||
* @param controller The controller instance
|
||||
* @param request The empty request
|
||||
* @param responseStream The streaming response handler
|
||||
* @param requestId The ID of the request (passed by the gRPC handler)
|
||||
*/
|
||||
export async function subscribeToAuthCallback(
|
||||
controller: Controller,
|
||||
request: EmptyRequest,
|
||||
responseStream: StreamingResponseHandler,
|
||||
requestId?: string,
|
||||
): Promise<void> {
|
||||
// Add this subscription to the active subscriptions
|
||||
activeAuthCallbackSubscriptions.add(responseStream)
|
||||
|
||||
// Register cleanup when the connection is closed
|
||||
const cleanup = () => {
|
||||
activeAuthCallbackSubscriptions.delete(responseStream)
|
||||
}
|
||||
|
||||
// Register the cleanup function with the request registry if we have a requestId
|
||||
if (requestId) {
|
||||
getRequestRegistry().registerRequest(requestId, cleanup, { type: "authCallback_subscription" }, responseStream)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Send an authCallback event to all active subscribers
|
||||
* @param customToken The custom token for authentication
|
||||
*/
|
||||
export async function sendAuthCallbackEvent(customToken: string): Promise<void> {
|
||||
// Send the event to all active subscribers
|
||||
const promises = Array.from(activeAuthCallbackSubscriptions).map(async (responseStream) => {
|
||||
try {
|
||||
const event: ProtoString = {
|
||||
value: customToken,
|
||||
}
|
||||
await responseStream(
|
||||
event,
|
||||
false, // Not the last message
|
||||
)
|
||||
} catch (error) {
|
||||
console.error("Error sending authCallback event:", error)
|
||||
// Remove the subscription if there was an error
|
||||
activeAuthCallbackSubscriptions.delete(responseStream)
|
||||
}
|
||||
})
|
||||
|
||||
await Promise.all(promises)
|
||||
}
|
||||
@@ -24,24 +24,24 @@ export async function discoverBrowser(controller: Controller, request: EmptyRequ
|
||||
const browserSession = new BrowserSession(controller.context, browserSettings)
|
||||
const result = await browserSession.testConnection(discoveredHost)
|
||||
|
||||
return {
|
||||
return BrowserConnection.create({
|
||||
success: true,
|
||||
message: `Successfully discovered and connected to Chrome at ${discoveredHost}`,
|
||||
endpoint: result.endpoint || "",
|
||||
}
|
||||
})
|
||||
} else {
|
||||
return {
|
||||
return BrowserConnection.create({
|
||||
success: false,
|
||||
message:
|
||||
"No Chrome instances found. Make sure Chrome is running with remote debugging enabled (--remote-debugging-port=9222).",
|
||||
endpoint: "",
|
||||
}
|
||||
})
|
||||
}
|
||||
} catch (error) {
|
||||
return {
|
||||
return BrowserConnection.create({
|
||||
success: false,
|
||||
message: `Error discovering browser: ${error instanceof Error ? error.message : String(error)}`,
|
||||
endpoint: "",
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,7 +9,7 @@ import { getAllExtensionState } from "@core/storage/state"
|
||||
* @param request The request message
|
||||
* @returns The browser connection info
|
||||
*/
|
||||
export async function getBrowserConnectionInfo(controller: Controller, request: EmptyRequest): Promise<BrowserConnectionInfo> {
|
||||
export async function getBrowserConnectionInfo(controller: Controller, _: EmptyRequest): Promise<BrowserConnectionInfo> {
|
||||
try {
|
||||
// Get browser settings from extension state
|
||||
const { browserSettings } = await getAllExtensionState(controller.context)
|
||||
@@ -23,25 +23,25 @@ export async function getBrowserConnectionInfo(controller: Controller, request:
|
||||
const connectionInfo = browserSession.getConnectionInfo()
|
||||
|
||||
// Convert from BrowserSession.BrowserConnectionInfo to proto.BrowserConnectionInfo
|
||||
return {
|
||||
return BrowserConnectionInfo.create({
|
||||
isConnected: connectionInfo.isConnected,
|
||||
isRemote: connectionInfo.isRemote,
|
||||
host: connectionInfo.host || "", // Ensure host is never undefined
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// Fallback to browser settings if no active browser session
|
||||
return {
|
||||
return BrowserConnectionInfo.create({
|
||||
isConnected: false,
|
||||
isRemote: !!browserSettings.remoteBrowserEnabled,
|
||||
host: browserSettings.remoteBrowserHost || "",
|
||||
}
|
||||
})
|
||||
} catch (error: unknown) {
|
||||
console.error("Error getting browser connection info:", error)
|
||||
return {
|
||||
return BrowserConnectionInfo.create({
|
||||
isConnected: false,
|
||||
isRemote: false,
|
||||
host: "",
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -10,21 +10,21 @@ import { BrowserSession } from "../../../services/browser/BrowserSession"
|
||||
* @param request The empty request message
|
||||
* @returns The detected Chrome path and whether it's bundled
|
||||
*/
|
||||
export async function getDetectedChromePath(controller: Controller, request: EmptyRequest): Promise<ChromePath> {
|
||||
export async function getDetectedChromePath(controller: Controller, _: EmptyRequest): Promise<ChromePath> {
|
||||
try {
|
||||
const { browserSettings } = await getAllExtensionState(controller.context)
|
||||
const browserSession = new BrowserSession(controller.context, browserSettings)
|
||||
const result = await browserSession.getDetectedChromePath()
|
||||
|
||||
return {
|
||||
return ChromePath.create({
|
||||
path: result.path,
|
||||
isBundled: result.isBundled,
|
||||
}
|
||||
})
|
||||
} catch (error) {
|
||||
console.error("Error getting detected Chrome path:", error)
|
||||
return {
|
||||
return ChromePath.create({
|
||||
path: "",
|
||||
isBundled: false,
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,7 +8,7 @@ import { BrowserSession } from "../../../services/browser/BrowserSession"
|
||||
* @param request The empty request message
|
||||
* @returns The browser relaunch result as a string message
|
||||
*/
|
||||
export async function relaunchChromeDebugMode(controller: Controller, request: EmptyRequest): Promise<StringMessage> {
|
||||
export async function relaunchChromeDebugMode(controller: Controller, _: EmptyRequest): Promise<StringMessage> {
|
||||
try {
|
||||
const { browserSettings } = await controller.getStateToPostToWebview()
|
||||
const browserSession = new BrowserSession(controller.context, browserSettings)
|
||||
@@ -18,9 +18,9 @@ export async function relaunchChromeDebugMode(controller: Controller, request: E
|
||||
|
||||
// The actual result will be sent via postMessageToWebview in the BrowserSession.relaunchChromeDebugMode method
|
||||
// Here we just return a message as a placeholder
|
||||
return {
|
||||
return StringMessage.create({
|
||||
value: "Chrome relaunch initiated",
|
||||
}
|
||||
})
|
||||
} catch (error) {
|
||||
throw new Error(`Error relaunching Chrome: ${error instanceof Error ? error.message : globalThis.String(error)}`)
|
||||
}
|
||||
|
||||
@@ -24,40 +24,40 @@ export async function testBrowserConnection(controller: Controller, request: Str
|
||||
if (discoveredHost) {
|
||||
// Test the connection to the discovered host
|
||||
const result = await browserSession.testConnection(discoveredHost)
|
||||
return {
|
||||
return BrowserConnection.create({
|
||||
success: result.success,
|
||||
message: `Auto-discovered and tested connection to Chrome at ${discoveredHost}: ${result.message}`,
|
||||
endpoint: result.endpoint || "",
|
||||
}
|
||||
})
|
||||
} else {
|
||||
return {
|
||||
return BrowserConnection.create({
|
||||
success: false,
|
||||
message:
|
||||
"No Chrome instances found on the network. Make sure Chrome is running with remote debugging enabled (--remote-debugging-port=9222).",
|
||||
endpoint: "",
|
||||
}
|
||||
})
|
||||
}
|
||||
} catch (error) {
|
||||
return {
|
||||
return BrowserConnection.create({
|
||||
success: false,
|
||||
message: `Error during auto-discovery: ${error instanceof Error ? error.message : String(error)}`,
|
||||
endpoint: "",
|
||||
}
|
||||
})
|
||||
}
|
||||
} else {
|
||||
// Test the provided URL
|
||||
const result = await browserSession.testConnection(text)
|
||||
return {
|
||||
return BrowserConnection.create({
|
||||
success: result.success,
|
||||
message: result.message,
|
||||
endpoint: result.endpoint || "",
|
||||
}
|
||||
})
|
||||
}
|
||||
} catch (error) {
|
||||
return {
|
||||
return BrowserConnection.create({
|
||||
success: false,
|
||||
message: `Error testing connection: ${error instanceof Error ? error.message : String(error)}`,
|
||||
endpoint: "",
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -50,13 +50,13 @@ export async function updateBrowserSettings(controller: Controller, request: Upd
|
||||
// Post updated state to webview
|
||||
await controller.postStateToWebview()
|
||||
|
||||
return {
|
||||
return Boolean.create({
|
||||
value: true,
|
||||
}
|
||||
})
|
||||
} catch (error) {
|
||||
console.error("Error updating browser settings:", error)
|
||||
return {
|
||||
return Boolean.create({
|
||||
value: false,
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -18,5 +18,5 @@ export async function checkpointRestore(controller: Controller, request: Checkpo
|
||||
// NOTE: cancelTask awaits abortTask, which awaits diffViewProvider.revertChanges, which reverts any edited files, allowing us to reset to a checkpoint rather than running into a state where the revertChanges function is called alongside or after the checkpoint reset
|
||||
await controller.task?.restoreCheckpoint(request.number, request.restoreType as ClineCheckpointRestore, request.offset)
|
||||
}
|
||||
return {}
|
||||
return Empty.create({})
|
||||
}
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
import { Controller } from ".."
|
||||
import { Empty, StringRequest } from "@shared/proto/common"
|
||||
import { openFile as openFileIntegration } from "@integrations/misc/open-file"
|
||||
import { FileMethodHandler } from "./index"
|
||||
import path from "path"
|
||||
/**
|
||||
* Opens a file in the editor
|
||||
* @param controller The controller instance
|
||||
* @param request The request message containing the file path in the 'value' field
|
||||
* @returns Empty response
|
||||
*/
|
||||
export const openTaskHistory: FileMethodHandler = async (controller: Controller, request: StringRequest): Promise<Empty> => {
|
||||
const globalStoragePath = controller.context.globalStorageUri.fsPath
|
||||
const taskHistoryPath = path.join(globalStoragePath, "tasks", request.value, "api_conversation_history.json")
|
||||
if (request.value) {
|
||||
openFileIntegration(taskHistoryPath)
|
||||
}
|
||||
return Empty.create()
|
||||
}
|
||||
@@ -18,14 +18,14 @@ export async function refreshRules(controller: Controller, _request: EmptyReques
|
||||
const { cursorLocalToggles, windsurfLocalToggles } = await refreshExternalRulesToggles(controller.context, cwd)
|
||||
const { localWorkflowToggles, globalWorkflowToggles } = await refreshWorkflowToggles(controller.context, cwd)
|
||||
|
||||
return {
|
||||
return RefreshedRules.create({
|
||||
globalClineRulesToggles: { toggles: globalToggles },
|
||||
localClineRulesToggles: { toggles: localToggles },
|
||||
localCursorRulesToggles: { toggles: cursorLocalToggles },
|
||||
localWindsurfRulesToggles: { toggles: windsurfLocalToggles },
|
||||
localWorkflowToggles: { toggles: localWorkflowToggles },
|
||||
globalWorkflowToggles: { toggles: globalWorkflowToggles },
|
||||
}
|
||||
})
|
||||
} catch (error) {
|
||||
console.error("Failed to refresh rules:", error)
|
||||
throw error
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
import { Controller } from ".."
|
||||
import { BooleanRequest, StringArrays } from "@shared/proto/common"
|
||||
import { selectFiles as selectFilesIntegration } from "@integrations/misc/process-files"
|
||||
import { FileMethodHandler } from "./index"
|
||||
|
||||
/**
|
||||
* Prompts the user to select images from the file system and returns them as data URLs
|
||||
* @param controller The controller instance
|
||||
* @param request Boolean request, with the value defining whether this model supports images
|
||||
* @returns Two arrays of image data URLs and other file paths
|
||||
*/
|
||||
export const selectFiles: FileMethodHandler = async (controller: Controller, request: BooleanRequest): Promise<StringArrays> => {
|
||||
try {
|
||||
const { images, files } = await selectFilesIntegration(request.value)
|
||||
return StringArrays.create({ values1: images, values2: files })
|
||||
} catch (error) {
|
||||
console.error("Error selecting images & files:", error)
|
||||
// Return empty array on error
|
||||
return StringArrays.create({ values1: [], values2: [] })
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
import type { ToggleClineRuleRequest, ClineRulesToggles, ToggleClineRules } from "../../../shared/proto/file"
|
||||
import { ToggleClineRules } from "../../../shared/proto/file"
|
||||
import type { ToggleClineRuleRequest } from "../../../shared/proto/file"
|
||||
import type { Controller } from "../index"
|
||||
import { getGlobalState, getWorkspaceState, updateGlobalState, updateWorkspaceState } from "../../../core/storage/state"
|
||||
import { ClineRulesToggles as AppClineRulesToggles } from "@shared/cline-rules"
|
||||
@@ -36,8 +37,8 @@ export async function toggleClineRule(controller: Controller, request: ToggleCli
|
||||
const globalToggles = ((await getGlobalState(controller.context, "globalClineRulesToggles")) as AppClineRulesToggles) || {}
|
||||
const localToggles = ((await getWorkspaceState(controller.context, "localClineRulesToggles")) as AppClineRulesToggles) || {}
|
||||
|
||||
return {
|
||||
return ToggleClineRules.create({
|
||||
globalClineRulesToggles: { toggles: globalToggles },
|
||||
localClineRulesToggles: { toggles: localToggles },
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import type { ToggleCursorRuleRequest, ClineRulesToggles } from "../../../shared/proto/file"
|
||||
import type { ToggleCursorRuleRequest } from "../../../shared/proto/file"
|
||||
import { ClineRulesToggles } from "../../../shared/proto/file"
|
||||
import type { Controller } from "../index"
|
||||
import { getWorkspaceState, updateWorkspaceState } from "../../../core/storage/state"
|
||||
import { ClineRulesToggles as AppClineRulesToggles } from "@shared/cline-rules"
|
||||
@@ -28,7 +29,7 @@ export async function toggleCursorRule(controller: Controller, request: ToggleCu
|
||||
// Get the current state to return in the response
|
||||
const cursorToggles = ((await getWorkspaceState(controller.context, "localCursorRulesToggles")) as AppClineRulesToggles) || {}
|
||||
|
||||
return {
|
||||
return ClineRulesToggles.create({
|
||||
toggles: cursorToggles,
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import type { ToggleWindsurfRuleRequest, ClineRulesToggles } from "../../../shared/proto/file"
|
||||
import type { ToggleWindsurfRuleRequest } from "../../../shared/proto/file"
|
||||
import { ClineRulesToggles } from "../../../shared/proto/file"
|
||||
import type { Controller } from "../index"
|
||||
import { getWorkspaceState, updateWorkspaceState } from "../../../core/storage/state"
|
||||
import { ClineRulesToggles as AppClineRulesToggles } from "@shared/cline-rules"
|
||||
@@ -26,5 +27,5 @@ export async function toggleWindsurfRule(controller: Controller, request: Toggle
|
||||
await updateWorkspaceState(controller.context, "localWindsurfRulesToggles", toggles)
|
||||
|
||||
// Return the toggles directly
|
||||
return { toggles: toggles }
|
||||
return ClineRulesToggles.create({ toggles: toggles })
|
||||
}
|
||||
|
||||
@@ -23,7 +23,7 @@ import { telemetryService } from "@/services/posthog/telemetry/TelemetryService"
|
||||
import { ApiProvider, ModelInfo } from "@shared/api"
|
||||
import { ChatContent } from "@shared/ChatContent"
|
||||
import { ChatSettings } from "@shared/ChatSettings"
|
||||
import { ExtensionMessage, ExtensionState, Invoke, Platform } from "@shared/ExtensionMessage"
|
||||
import { ExtensionMessage, ExtensionState, Platform } from "@shared/ExtensionMessage"
|
||||
import { HistoryItem } from "@shared/HistoryItem"
|
||||
import { McpDownloadResponse, McpMarketplaceCatalog, McpServer } from "@shared/mcp"
|
||||
import { TelemetrySetting } from "@shared/TelemetrySetting"
|
||||
@@ -52,6 +52,8 @@ import {
|
||||
import { Task, cwd } from "../task"
|
||||
import { ClineRulesToggles } from "@shared/cline-rules"
|
||||
import { sendStateUpdate } from "./state/subscribeToState"
|
||||
import { sendAddToInputEvent } from "./ui/subscribeToAddToInput"
|
||||
import { sendAuthCallbackEvent } from "./account/subscribeToAuthCallback"
|
||||
import { refreshClineRulesToggles } from "@core/context/instructions/user-instructions/cline-rules"
|
||||
import { refreshExternalRulesToggles } from "@core/context/instructions/user-instructions/external-rules"
|
||||
import { refreshWorkflowToggles } from "@core/context/instructions/user-instructions/workflows"
|
||||
@@ -107,9 +109,7 @@ export class Controller {
|
||||
- https://github.com/microsoft/vscode-extension-samples/blob/main/webview-sample/src/extension.ts
|
||||
*/
|
||||
async dispose() {
|
||||
this.outputChannel.appendLine("Disposing ClineProvider...")
|
||||
await this.clearTask()
|
||||
this.outputChannel.appendLine("Cleared task")
|
||||
while (this.disposables.length) {
|
||||
const x = this.disposables.pop()
|
||||
if (x) {
|
||||
@@ -118,7 +118,6 @@ export class Controller {
|
||||
}
|
||||
this.workspaceTracker.dispose()
|
||||
this.mcpHub.dispose()
|
||||
this.outputChannel.appendLine("Disposed all disposables")
|
||||
|
||||
console.error("Controller disposed")
|
||||
}
|
||||
@@ -140,7 +139,7 @@ export class Controller {
|
||||
await updateGlobalState(this.context, "userInfo", info)
|
||||
}
|
||||
|
||||
async initTask(task?: string, images?: string[], historyItem?: HistoryItem) {
|
||||
async initTask(task?: string, images?: string[], files?: string[], historyItem?: HistoryItem) {
|
||||
await this.clearTask() // ensures that an existing task doesn't exist before starting a new one, although this shouldn't be possible since user must clear task before starting a new one
|
||||
const {
|
||||
apiConfiguration,
|
||||
@@ -187,6 +186,7 @@ export class Controller {
|
||||
customInstructions,
|
||||
task,
|
||||
images,
|
||||
files,
|
||||
historyItem,
|
||||
)
|
||||
}
|
||||
@@ -194,7 +194,7 @@ export class Controller {
|
||||
async reinitExistingTaskFromId(taskId: string) {
|
||||
const history = await this.getTaskWithId(taskId)
|
||||
if (history) {
|
||||
await this.initTask(undefined, undefined, history.historyItem)
|
||||
await this.initTask(undefined, undefined, undefined, history.historyItem)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -262,13 +262,6 @@ export class Controller {
|
||||
}
|
||||
})
|
||||
break
|
||||
case "showChatView": {
|
||||
this.postMessageToWebview({
|
||||
type: "action",
|
||||
action: "chatButtonClicked",
|
||||
})
|
||||
break
|
||||
}
|
||||
case "newTask":
|
||||
// Code that should run in response to the hello message command
|
||||
//vscode.window.showInformationMessage(message.text!)
|
||||
@@ -278,7 +271,7 @@ export class Controller {
|
||||
// Could also do this in extension .ts
|
||||
//this.postMessageToWebview({ type: "text", text: `Extension: ${Date.now()}` })
|
||||
// initializing new instance of Cline will make sure that any agentically running promises in old instance don't affect our new task. this essentially creates a fresh slate for the new task
|
||||
await this.initTask(message.text, message.images)
|
||||
await this.initTask(message.text, message.images, message.files)
|
||||
break
|
||||
case "apiConfiguration":
|
||||
if (message.apiConfiguration) {
|
||||
@@ -289,13 +282,6 @@ export class Controller {
|
||||
}
|
||||
await this.postStateToWebview()
|
||||
break
|
||||
case "optionsResponse":
|
||||
await this.postMessageToWebview({
|
||||
type: "invoke",
|
||||
invoke: "sendMessage",
|
||||
text: message.text,
|
||||
})
|
||||
break
|
||||
case "fetchUserCreditsData": {
|
||||
await this.fetchUserCreditsData()
|
||||
break
|
||||
@@ -361,15 +347,6 @@ export class Controller {
|
||||
this.mcpHub?.sendLatestMcpServers()
|
||||
break
|
||||
}
|
||||
case "invoke": {
|
||||
if (message.text) {
|
||||
await this.postMessageToWebview({
|
||||
type: "invoke",
|
||||
invoke: message.text as Invoke,
|
||||
})
|
||||
}
|
||||
break
|
||||
}
|
||||
// telemetry
|
||||
case "telemetrySetting": {
|
||||
if (message.telemetrySetting) {
|
||||
@@ -451,6 +428,13 @@ export class Controller {
|
||||
}
|
||||
break
|
||||
}
|
||||
case "executeQuickWin":
|
||||
if (message.payload) {
|
||||
const { command, title } = message.payload
|
||||
this.outputChannel.appendLine(`Received executeQuickWin: command='${command}', title='${title}'`)
|
||||
await this.initTask(title)
|
||||
}
|
||||
break
|
||||
|
||||
// Add more switch case statements here as more webview message commands
|
||||
// are created within the webview context (i.e. inside media/main.js)
|
||||
@@ -617,12 +601,12 @@ export class Controller {
|
||||
if (this.task.isAwaitingPlanResponse && didSwitchToActMode) {
|
||||
this.task.didRespondToPlanAskBySwitchingMode = true
|
||||
// Use chatContent if provided, otherwise use default message
|
||||
await this.postMessageToWebview({
|
||||
type: "invoke",
|
||||
invoke: "sendMessage",
|
||||
text: chatContent?.message || "PLAN_MODE_TOGGLE_RESPONSE",
|
||||
images: chatContent?.images,
|
||||
})
|
||||
await this.task.handleWebviewAskResponse(
|
||||
"messageResponse",
|
||||
chatContent?.message || "PLAN_MODE_TOGGLE_RESPONSE",
|
||||
chatContent?.images || [],
|
||||
chatContent?.files || [],
|
||||
)
|
||||
} else {
|
||||
this.cancelTask()
|
||||
}
|
||||
@@ -653,7 +637,7 @@ export class Controller {
|
||||
// 'abandoned' will prevent this cline instance from affecting future cline instance gui. this may happen if its hanging on a streaming request
|
||||
this.task.abandoned = true
|
||||
}
|
||||
await this.initTask(undefined, undefined, historyItem) // clears task again, so we need to abortTask manually above
|
||||
await this.initTask(undefined, undefined, undefined, historyItem) // clears task again, so we need to abortTask manually above
|
||||
// await this.postStateToWebview() // new Cline instance will post state when it's ready. having this here sent an empty messages array to webview leading to virtuoso having to reload the entire list
|
||||
}
|
||||
}
|
||||
@@ -697,10 +681,7 @@ export class Controller {
|
||||
await storeSecret(this.context, "clineApiKey", apiKey)
|
||||
|
||||
// Send custom token to webview for Firebase auth
|
||||
await this.postMessageToWebview({
|
||||
type: "authCallback",
|
||||
customToken,
|
||||
})
|
||||
await sendAuthCallbackEvent(customToken)
|
||||
|
||||
const clineProvider: ApiProvider = "cline"
|
||||
await updateGlobalState(this.context, "apiProvider", clineProvider)
|
||||
@@ -934,10 +915,7 @@ export class Controller {
|
||||
input += `\nProblems:\n${problemsString}`
|
||||
}
|
||||
|
||||
await this.postMessageToWebview({
|
||||
type: "addToInput",
|
||||
text: input,
|
||||
})
|
||||
await sendAddToInputEvent(input)
|
||||
|
||||
console.log("addSelectedCodeToChat", code, filePath, languageId)
|
||||
}
|
||||
@@ -955,10 +933,7 @@ export class Controller {
|
||||
// terminalName
|
||||
// })
|
||||
|
||||
await this.postMessageToWebview({
|
||||
type: "addToInput",
|
||||
text: `Terminal output:\n\`\`\`\n${output}\n\`\`\``,
|
||||
})
|
||||
await sendAddToInputEvent(`Terminal output:\n\`\`\`\n${output}\n\`\`\``)
|
||||
|
||||
console.log("addSelectedTerminalOutputToChat", output, terminalName)
|
||||
}
|
||||
@@ -1047,7 +1022,7 @@ export class Controller {
|
||||
if (id !== this.task?.taskId) {
|
||||
// non-current task
|
||||
const { historyItem } = await this.getTaskWithId(id)
|
||||
await this.initTask(undefined, undefined, historyItem) // clears existing task
|
||||
await this.initTask(undefined, undefined, undefined, historyItem) // clears existing task
|
||||
}
|
||||
await this.postMessageToWebview({
|
||||
type: "action",
|
||||
@@ -1178,10 +1153,7 @@ export class Controller {
|
||||
|
||||
async postStateToWebview() {
|
||||
const state = await this.getStateToPostToWebview()
|
||||
// For testing: Bypass gRPC stream and send state directly
|
||||
console.log("[Controller Test Revert] Posting full state via direct 'state' message.")
|
||||
await this.postMessageToWebview({ type: "state", state: state })
|
||||
// await sendStateUpdate(state) // Original line for the GrPC stream
|
||||
await sendStateUpdate(state)
|
||||
}
|
||||
|
||||
async getStateToPostToWebview(): Promise<ExtensionState> {
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { convertMcpServersToProtoMcpServers } from "@/shared/proto-conversions/mcp/mcp-server-conversion"
|
||||
import type { AddRemoteMcpServerRequest, McpServers } from "../../../shared/proto/mcp"
|
||||
import type { AddRemoteMcpServerRequest } from "../../../shared/proto/mcp"
|
||||
import { McpServers } from "../../../shared/proto/mcp"
|
||||
import type { Controller } from "../index"
|
||||
|
||||
/**
|
||||
@@ -23,7 +24,7 @@ export async function addRemoteMcpServer(controller: Controller, request: AddRem
|
||||
|
||||
const protoServers = convertMcpServersToProtoMcpServers(servers)
|
||||
|
||||
return { mcpServers: protoServers }
|
||||
return McpServers.create({ mcpServers: protoServers })
|
||||
} catch (error) {
|
||||
console.error(`Failed to add remote MCP server ${request.serverName}:`, error)
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import type { Controller } from "../index"
|
||||
import type { McpServers } from "../../../shared/proto/mcp"
|
||||
import { McpServers } from "../../../shared/proto/mcp"
|
||||
import { convertMcpServersToProtoMcpServers } from "../../../shared/proto-conversions/mcp/mcp-server-conversion"
|
||||
import { StringRequest } from "@/shared/proto/common"
|
||||
|
||||
@@ -17,7 +17,7 @@ export async function deleteMcpServer(controller: Controller, request: StringReq
|
||||
// Convert application types to protobuf types
|
||||
const protoServers = convertMcpServersToProtoMcpServers(mcpServers)
|
||||
|
||||
return { mcpServers: protoServers }
|
||||
return McpServers.create({ mcpServers: protoServers })
|
||||
} catch (error) {
|
||||
console.error(`Failed to delete MCP server: ${error}`)
|
||||
throw error
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import type { EmptyRequest } from "../../../shared/proto/common"
|
||||
import type { McpMarketplaceCatalog } from "../../../shared/proto/mcp"
|
||||
import { McpMarketplaceCatalog } from "../../../shared/proto/mcp"
|
||||
import type { Controller } from "../index"
|
||||
|
||||
/**
|
||||
@@ -19,9 +19,9 @@ export async function refreshMcpMarketplace(controller: Controller, _request: Em
|
||||
}
|
||||
|
||||
// Return empty catalog if nothing was fetched
|
||||
return { items: [] }
|
||||
return McpMarketplaceCatalog.create({ items: [] })
|
||||
} catch (error) {
|
||||
console.error("Failed to refresh MCP marketplace:", error)
|
||||
return { items: [] }
|
||||
return McpMarketplaceCatalog.create({ items: [] })
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { McpServers } from "@shared/proto/mcp"
|
||||
import { McpServers } from "@shared/proto/mcp"
|
||||
import type { Controller } from "../index"
|
||||
import { convertMcpServersToProtoMcpServers } from "@shared/proto-conversions/mcp/mcp-server-conversion"
|
||||
import { StringRequest } from "@/shared/proto/common"
|
||||
@@ -16,7 +16,7 @@ export async function restartMcpServer(controller: Controller, request: StringRe
|
||||
// Convert from McpServer[] to ProtoMcpServer[] ensuring all required fields are set
|
||||
const protoServers = convertMcpServersToProtoMcpServers(mcpServers)
|
||||
|
||||
return { mcpServers: protoServers }
|
||||
return McpServers.create({ mcpServers: protoServers })
|
||||
} catch (error) {
|
||||
console.error(`Failed to restart MCP server ${request.value}:`, error)
|
||||
throw error
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import type { ToggleMcpServerRequest, McpServers } from "../../../shared/proto/mcp"
|
||||
import type { ToggleMcpServerRequest } from "../../../shared/proto/mcp"
|
||||
import { McpServers } from "../../../shared/proto/mcp"
|
||||
import type { Controller } from "../index"
|
||||
import { convertMcpServersToProtoMcpServers } from "../../../shared/proto-conversions/mcp/mcp-server-conversion"
|
||||
|
||||
@@ -15,7 +16,7 @@ export async function toggleMcpServer(controller: Controller, request: ToggleMcp
|
||||
// Convert from McpServer[] to ProtoMcpServer[] ensuring all required fields are set
|
||||
const protoServers = convertMcpServersToProtoMcpServers(mcpServers)
|
||||
|
||||
return { mcpServers: protoServers }
|
||||
return McpServers.create({ mcpServers: protoServers })
|
||||
} catch (error) {
|
||||
console.error(`Failed to toggle MCP server ${request.serverName}:`, error)
|
||||
throw error
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import type { ToggleToolAutoApproveRequest, McpServers } from "@shared/proto/mcp"
|
||||
import type { ToggleToolAutoApproveRequest } from "@shared/proto/mcp"
|
||||
import { McpServers } from "@shared/proto/mcp"
|
||||
import type { Controller } from "../index"
|
||||
import { convertMcpServersToProtoMcpServers } from "@shared/proto-conversions/mcp/mcp-server-conversion"
|
||||
|
||||
@@ -15,7 +16,7 @@ export async function toggleToolAutoApprove(controller: Controller, request: Tog
|
||||
(await controller.mcpHub?.toggleToolAutoApproveRPC(request.serverName, request.toolNames, request.autoApprove)) || []
|
||||
|
||||
// Convert application types to proto types
|
||||
return { mcpServers: convertMcpServersToProtoMcpServers(mcpServers) }
|
||||
return McpServers.create({ mcpServers: convertMcpServersToProtoMcpServers(mcpServers) })
|
||||
} catch (error) {
|
||||
console.error(`Failed to toggle tool auto-approve for ${request.serverName}:`, error)
|
||||
throw error
|
||||
|
||||
@@ -15,7 +15,7 @@ export async function updateMcpTimeout(controller: Controller, request: UpdateMc
|
||||
console.log("mcpServers", mcpServers)
|
||||
const convertedMcpServers = convertMcpServersToProtoMcpServers(mcpServers)
|
||||
console.log("convertedMcpServers", convertedMcpServers)
|
||||
return { mcpServers: convertedMcpServers }
|
||||
return McpServers.create({ mcpServers: convertedMcpServers })
|
||||
} else {
|
||||
console.error("Server name and timeout are required")
|
||||
throw new Error("Server name and timeout are required")
|
||||
|
||||
@@ -10,10 +10,7 @@ import { getSecret } from "@core/storage/state"
|
||||
* @param request Empty request object
|
||||
* @returns Response containing the Requesty models
|
||||
*/
|
||||
export async function refreshRequestyModels(
|
||||
controller: Controller,
|
||||
request: EmptyRequest,
|
||||
): Promise<OpenRouterCompatibleModelInfo> {
|
||||
export async function refreshRequestyModels(controller: Controller, _: EmptyRequest): Promise<OpenRouterCompatibleModelInfo> {
|
||||
const parsePrice = (price: any) => {
|
||||
if (price) {
|
||||
return parseFloat(price) * 1_000_000
|
||||
@@ -30,7 +27,7 @@ export async function refreshRequestyModels(
|
||||
const response = await axios.get("https://router.requesty.ai/v1/models", { headers })
|
||||
if (response.data?.data) {
|
||||
for (const model of response.data.data) {
|
||||
const modelInfo: OpenRouterModelInfo = {
|
||||
const modelInfo: OpenRouterModelInfo = OpenRouterModelInfo.create({
|
||||
maxTokens: model.max_output_tokens || undefined,
|
||||
contextWindow: model.context_window,
|
||||
supportsImages: model.supports_vision || undefined,
|
||||
@@ -40,7 +37,7 @@ export async function refreshRequestyModels(
|
||||
cacheWritesPrice: parsePrice(model.caching_price) || 0,
|
||||
cacheReadsPrice: parsePrice(model.cached_price) || 0,
|
||||
description: model.description,
|
||||
}
|
||||
})
|
||||
models[model.id] = modelInfo
|
||||
}
|
||||
console.log("Requesty models fetched", models)
|
||||
|
||||
@@ -2,7 +2,6 @@ import * as vscode from "vscode"
|
||||
import { Controller } from "../index"
|
||||
import { EmptyRequest } from "../../../shared/proto/common"
|
||||
import { State } from "../../../shared/proto/state"
|
||||
import { ExtensionState } from "../../../shared/ExtensionMessage"
|
||||
|
||||
/**
|
||||
* Get the latest extension state
|
||||
@@ -10,7 +9,7 @@ import { ExtensionState } from "../../../shared/ExtensionMessage"
|
||||
* @param request The empty request
|
||||
* @returns The current extension state
|
||||
*/
|
||||
export async function getLatestState(controller: Controller, request: EmptyRequest): Promise<State> {
|
||||
export async function getLatestState(controller: Controller, _: EmptyRequest): Promise<State> {
|
||||
// Get the state using the existing method
|
||||
const state = await controller.getStateToPostToWebview()
|
||||
|
||||
@@ -18,7 +17,7 @@ export async function getLatestState(controller: Controller, request: EmptyReque
|
||||
const stateJson = JSON.stringify(state)
|
||||
|
||||
// Return the state as a JSON string
|
||||
return {
|
||||
return State.create({
|
||||
stateJson,
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
@@ -15,7 +15,7 @@ export async function updateTerminalConnectionTimeout(controller: Controller, re
|
||||
if (typeof timeout === "number" && !isNaN(timeout) && timeout > 0) {
|
||||
// Update the global state directly
|
||||
await updateGlobalState(controller.context, "shellIntegrationTimeout", timeout)
|
||||
return { value: timeout }
|
||||
return Int64.create({ value: timeout })
|
||||
} else {
|
||||
console.warn(`Invalid shell integration timeout value received: ${timeout}. Expected a positive number.`)
|
||||
throw new Error("Invalid timeout value. Expected a positive number.")
|
||||
|
||||
@@ -35,7 +35,7 @@ export async function askResponse(controller: Controller, request: AskResponseRe
|
||||
}
|
||||
|
||||
// Call the task's handler for webview responses
|
||||
await controller.task.handleWebviewAskResponse(responseType, request.text, request.images)
|
||||
await controller.task.handleWebviewAskResponse(responseType, request.text, request.images, request.files)
|
||||
|
||||
return Empty.create()
|
||||
} catch (error) {
|
||||
|
||||
@@ -47,10 +47,10 @@ export async function deleteNonFavoritedTasks(
|
||||
console.error("Error posting to webview:", webviewErr)
|
||||
}
|
||||
|
||||
return {
|
||||
return DeleteNonFavoritedTasksResults.create({
|
||||
tasksPreserved: favoritedTasks.length,
|
||||
tasksDeleted: deletedCount,
|
||||
}
|
||||
})
|
||||
} catch (error) {
|
||||
console.error("Error in deleteNonFavoritedTasks:", error)
|
||||
throw error
|
||||
|
||||
@@ -106,10 +106,10 @@ export async function getTaskHistory(controller: Controller, request: GetTaskHis
|
||||
cacheReads: item.cacheReads || 0,
|
||||
}))
|
||||
|
||||
return {
|
||||
return TaskHistoryArray.create({
|
||||
tasks,
|
||||
totalCount,
|
||||
}
|
||||
})
|
||||
} catch (error) {
|
||||
console.error("Error in getTaskHistory:", error)
|
||||
throw error
|
||||
|
||||
@@ -9,6 +9,6 @@ import { NewTaskRequest } from "../../../shared/proto/task"
|
||||
* @returns Empty response
|
||||
*/
|
||||
export async function newTask(controller: Controller, request: NewTaskRequest): Promise<Empty> {
|
||||
await controller.initTask(request.text, request.images)
|
||||
await controller.initTask(request.text, request.images, request.files)
|
||||
return Empty.create()
|
||||
}
|
||||
|
||||
@@ -19,7 +19,7 @@ export async function showTaskWithId(controller: Controller, request: StringRequ
|
||||
// We need to initialize the task before returning data
|
||||
if (historyItem) {
|
||||
// Always initialize the task with the history item
|
||||
await controller.initTask(undefined, undefined, historyItem)
|
||||
await controller.initTask(undefined, undefined, undefined, historyItem)
|
||||
|
||||
// Send UI update to show the chat view
|
||||
await controller.postMessageToWebview({
|
||||
@@ -28,7 +28,7 @@ export async function showTaskWithId(controller: Controller, request: StringRequ
|
||||
})
|
||||
|
||||
// Return task data for gRPC response
|
||||
return {
|
||||
return TaskResponse.create({
|
||||
id: historyItem.id,
|
||||
task: historyItem.task || "",
|
||||
ts: historyItem.ts || 0,
|
||||
@@ -39,14 +39,14 @@ export async function showTaskWithId(controller: Controller, request: StringRequ
|
||||
tokensOut: historyItem.tokensOut || 0,
|
||||
cacheWrites: historyItem.cacheWrites || 0,
|
||||
cacheReads: historyItem.cacheReads || 0,
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// If not in global state, fetch from storage
|
||||
const { historyItem: fetchedItem } = await controller.getTaskWithId(id)
|
||||
|
||||
// Initialize the task with the fetched item
|
||||
await controller.initTask(undefined, undefined, fetchedItem)
|
||||
await controller.initTask(undefined, undefined, undefined, fetchedItem)
|
||||
|
||||
// Send UI update to show the chat view
|
||||
await controller.postMessageToWebview({
|
||||
@@ -54,7 +54,7 @@ export async function showTaskWithId(controller: Controller, request: StringRequ
|
||||
action: "chatButtonClicked",
|
||||
})
|
||||
|
||||
return {
|
||||
return TaskResponse.create({
|
||||
id: fetchedItem.id,
|
||||
task: fetchedItem.task || "",
|
||||
ts: fetchedItem.ts || 0,
|
||||
@@ -65,7 +65,7 @@ export async function showTaskWithId(controller: Controller, request: StringRequ
|
||||
tokensOut: fetchedItem.tokensOut || 0,
|
||||
cacheWrites: fetchedItem.cacheWrites || 0,
|
||||
cacheReads: fetchedItem.cacheReads || 0,
|
||||
}
|
||||
})
|
||||
} catch (error) {
|
||||
console.error("Error in showTaskWithId:", error)
|
||||
throw error
|
||||
|
||||
@@ -6,7 +6,7 @@ export async function toggleTaskFavorite(controller: Controller, request: TaskFa
|
||||
if (!request.taskId || request.isFavorited === undefined) {
|
||||
const errorMsg = `[toggleTaskFavorite] Invalid request: taskId or isFavorited missing`
|
||||
console.error(errorMsg)
|
||||
return {}
|
||||
return Empty.create({})
|
||||
}
|
||||
|
||||
try {
|
||||
@@ -47,5 +47,5 @@ export async function toggleTaskFavorite(controller: Controller, request: TaskFa
|
||||
console.error("Error in toggleTaskFavorite:", error)
|
||||
}
|
||||
|
||||
return {}
|
||||
return Empty.create({})
|
||||
}
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import type { EmptyRequest, Boolean } from "../../../shared/proto/common"
|
||||
import type { EmptyRequest } from "../../../shared/proto/common"
|
||||
import { Boolean } from "../../../shared/proto/common"
|
||||
import type { Controller } from "../index"
|
||||
import { getGlobalState, updateGlobalState } from "../../storage/state"
|
||||
|
||||
@@ -21,9 +22,9 @@ export async function onDidShowAnnouncement(controller: Controller, _request: Em
|
||||
// This replicates the same logic used in getStateToPostToWebview()
|
||||
const shouldShowAnnouncement = lastShownAnnouncementId !== controller.latestAnnouncementId
|
||||
|
||||
return { value: shouldShowAnnouncement }
|
||||
return Boolean.create({ value: shouldShowAnnouncement })
|
||||
} catch (error) {
|
||||
console.error("Failed to acknowledge announcement:", error)
|
||||
return { value: false }
|
||||
return Boolean.create({ value: false })
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
import * as vscode from "vscode"
|
||||
import { Controller } from "../index"
|
||||
import { EmptyRequest } from "../../../shared/proto/common"
|
||||
import { String as ProtoString } from "../../../shared/proto/common"
|
||||
import { StreamingResponseHandler, getRequestRegistry } from "../grpc-handler"
|
||||
|
||||
// Keep track of active addToInput subscriptions
|
||||
const activeAddToInputSubscriptions = new Set<StreamingResponseHandler>()
|
||||
|
||||
/**
|
||||
* Subscribe to addToInput events
|
||||
* @param controller The controller instance
|
||||
* @param request The empty request
|
||||
* @param responseStream The streaming response handler
|
||||
* @param requestId The ID of the request (passed by the gRPC handler)
|
||||
*/
|
||||
export async function subscribeToAddToInput(
|
||||
controller: Controller,
|
||||
request: EmptyRequest,
|
||||
responseStream: StreamingResponseHandler,
|
||||
requestId?: string,
|
||||
): Promise<void> {
|
||||
console.log("[DEBUG] set up addToInput subscription")
|
||||
|
||||
// Add this subscription to the active subscriptions
|
||||
activeAddToInputSubscriptions.add(responseStream)
|
||||
|
||||
// Register cleanup when the connection is closed
|
||||
const cleanup = () => {
|
||||
activeAddToInputSubscriptions.delete(responseStream)
|
||||
console.log("[DEBUG] Cleaned up addToInput subscription")
|
||||
}
|
||||
|
||||
// Register the cleanup function with the request registry if we have a requestId
|
||||
if (requestId) {
|
||||
getRequestRegistry().registerRequest(requestId, cleanup, { type: "addToInput_subscription" }, responseStream)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Send an addToInput event to all active subscribers
|
||||
* @param text The text to add to the input
|
||||
*/
|
||||
export async function sendAddToInputEvent(text: string): Promise<void> {
|
||||
// Send the event to all active subscribers
|
||||
const promises = Array.from(activeAddToInputSubscriptions).map(async (responseStream) => {
|
||||
try {
|
||||
const event: ProtoString = {
|
||||
value: text,
|
||||
}
|
||||
await responseStream(
|
||||
event,
|
||||
false, // Not the last message
|
||||
)
|
||||
console.log("[DEBUG] sending addToInput event", text.length, "chars")
|
||||
} catch (error) {
|
||||
console.error("Error sending addToInput event:", error)
|
||||
// Remove the subscription if there was an error
|
||||
activeAddToInputSubscriptions.delete(responseStream)
|
||||
}
|
||||
})
|
||||
|
||||
await Promise.all(promises)
|
||||
}
|
||||
@@ -9,21 +9,21 @@ import { detectImageUrl } from "@integrations/misc/link-preview"
|
||||
* @param request The request containing the URL to check
|
||||
* @returns A result indicating if the URL is an image and the URL that was checked
|
||||
*/
|
||||
export async function checkIsImageUrl(controller: Controller, request: StringRequest): Promise<IsImageUrl> {
|
||||
export async function checkIsImageUrl(_: Controller, request: StringRequest): Promise<IsImageUrl> {
|
||||
try {
|
||||
const url = request.value || ""
|
||||
// Check if the URL is an image
|
||||
const isImage = await detectImageUrl(url)
|
||||
|
||||
return {
|
||||
return IsImageUrl.create({
|
||||
isImage,
|
||||
url,
|
||||
}
|
||||
})
|
||||
} catch (error) {
|
||||
console.error(`Error checking if URL is an image: ${request.value}`, error)
|
||||
return {
|
||||
return IsImageUrl.create({
|
||||
isImage: false,
|
||||
url: request.value || "",
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,381 @@
|
||||
import { getShell } from "@utils/shell"
|
||||
import os from "os"
|
||||
import osName from "os-name"
|
||||
import { McpHub } from "@services/mcp/McpHub"
|
||||
import { BrowserSettings } from "@shared/BrowserSettings"
|
||||
|
||||
import { createAntmlToolPrompt, createSimpleXmlToolPrompt, toolDefinitionToSimpleXml } from "@core/prompts/model_prompts/jsonToolToXml"
|
||||
import { bashToolDefinition } from "@core/tools/bashTool"
|
||||
import { readToolDefinition } from "@core/tools/readTool"
|
||||
import { writeToolDefinition } from "@core/tools/writeTool"
|
||||
import {lsToolDefinition} from "@core/tools/lsTool"
|
||||
import { grepToolDefinition } from "@core/tools/grepTool"
|
||||
import {webFetchToolDefinition} from "@core/tools/webFetchTool"
|
||||
import { askQuestionToolDefinition } from "@core/tools/askQuestionTool"
|
||||
import { useMCPToolDefinition } from "@core/tools/useMcpTool"
|
||||
import {listCodeDefinitionNamesToolDefinition} from "@core/tools/listCodeDefinitionNamesTool"
|
||||
import {accessMcpResourceToolDefinition} from "@core/tools/accessMcpResourceTool"
|
||||
import {planModeRespondToolDefinition} from "@core/tools/planModeRespondTool"
|
||||
import {loadMcpDocumentationToolDefinition} from "@core/tools/loadMcpDocumentationTool"
|
||||
import { attemptCompletionToolDefinition } from "@core/tools/attemptCompletionTool"
|
||||
import {browserActionToolDefinition} from "@core/tools/browserActionTool"
|
||||
import {newTaskToolDefinition} from "@core/tools/newTaskTool"
|
||||
|
||||
export const SYSTEM_PROMPT_CLAUDE4 = async (
|
||||
cwd: string,
|
||||
supportsBrowserUse: boolean,
|
||||
mcpHub: McpHub,
|
||||
browserSettings: BrowserSettings,
|
||||
) => {
|
||||
const bashTool = bashToolDefinition(cwd);
|
||||
const readTool = readToolDefinition(cwd);
|
||||
const writeTool = writeToolDefinition(cwd);
|
||||
const listCodeDefinitionNamesTool = listCodeDefinitionNamesToolDefinition(cwd);
|
||||
const loadMcpDocumentationTool = loadMcpDocumentationToolDefinition(useMCPToolDefinition.name, accessMcpResourceToolDefinition.name);
|
||||
const browserActionTool = browserActionToolDefinition(browserSettings);
|
||||
|
||||
const systemPrompt = `You are Cline, a highly skilled software engineer with extensive knowledge in many programming languages, frameworks, design patterns, and best practices.
|
||||
|
||||
====
|
||||
|
||||
TOOL USE
|
||||
|
||||
You have access to a set of tools that are executed upon the user's approval. You can use one tool per message, and will receive the result of that tool use in the user's response. You use tools step-by-step to accomplish a given task, with each tool use informed by the result of the previous tool use.
|
||||
|
||||
# Tool Use Formatting
|
||||
|
||||
Tool use is formatted using XML-style tags. The tool name is enclosed in opening and closing tags, and each parameter is similarly enclosed within its own set of tags. Here's the structure:
|
||||
|
||||
<tool_name>
|
||||
<parameter1_name>value1</parameter1_name>
|
||||
<parameter2_name>value2</parameter2_name>
|
||||
...
|
||||
</tool_name>
|
||||
|
||||
Always adhere to this format for the tool use to ensure proper parsing and execution.
|
||||
|
||||
# Tools
|
||||
|
||||
## replace_in_file
|
||||
|
||||
"Description: Return your edits as a JSON object with a "replacements" array. Each replacement should have "old_str" and "new_str" fields. The old_str must match exactly what's in the file (including whitespace, indentation and new lines). You can edit multiple lines, but please keep the replacements as simple as possible.
|
||||
Both old_str and new_str can be multiline strings, but they must be valid JSON strings.
|
||||
|
||||
Usage:
|
||||
<replace_in_file>
|
||||
<path>File path here</path>
|
||||
<diff>
|
||||
{{
|
||||
"replacements": [
|
||||
{{
|
||||
"old_str": "exact string from file",
|
||||
"new_str": "replacement string"
|
||||
}}
|
||||
]
|
||||
}}
|
||||
</diff>
|
||||
</replace_in_file>
|
||||
|
||||
Important: Make sure each old_str matches the exact text in the file, character for character.
|
||||
Parameters:
|
||||
- path: (required) The path of the file to modify (relative to the current working directory ${cwd.toPosix()})
|
||||
- replacements_json: (required) A JSON string containing an object with a "replacements" array. Each object in the array must have "old_str" (the exact string to find in the file) and "new_str" (the string to replace it with). Refer to the example format in the main description.
|
||||
Usage:
|
||||
<replace_in_file>
|
||||
<path>File path here</path>
|
||||
<diff>
|
||||
{{
|
||||
"replacements": [
|
||||
{{
|
||||
"old_str": "exact string from file",
|
||||
"new_str": "replacement string"
|
||||
}}
|
||||
]
|
||||
}}
|
||||
</diff>
|
||||
</replace_in_file>
|
||||
|
||||
## Example 2: Requesting to make targeted edits to a file
|
||||
|
||||
<replace_in_file>
|
||||
|
||||
<path>src/baseApp.py</path>
|
||||
<diff>
|
||||
{
|
||||
"replacements": [
|
||||
{
|
||||
"old_str": "def try_dotdotdots(whole, part, replace):",
|
||||
"new_str": "# Handles search/replace blocks that use ellipsis (...) to represent omitted code sections\n# Validates that ellipsis usage is consistent between search and replace blocks\ndef try_dotdotdots(whole, part, replace):"
|
||||
},
|
||||
{
|
||||
"old_str": "def strip_filename(filename, fence):",
|
||||
"new_str": "# Extracts and cleans filename from various markdown formatting styles\n# Handles filenames with different prefixes, suffixes, and decorations\ndef strip_filename(filename, fence):"
|
||||
},
|
||||
{
|
||||
"old_str": "def main():",
|
||||
"new_str": "# Main entry point for command-line usage\n# Processes chat history and displays diffs for all found edit blocks\ndef main():"
|
||||
}
|
||||
]
|
||||
}
|
||||
</diff>
|
||||
</replace_in_file>
|
||||
|
||||
# Tool Use Guidelines
|
||||
|
||||
1. In <thinking> tags, assess what information you already have and what information you need to proceed with the task.
|
||||
2. Choose the most appropriate tool based on the task and the tool descriptions provided. Assess if you need additional information to proceed, and which of the available tools would be most effective for gathering this information. It's critical that you think about each available tool and use the one that best fits the current step in the task.
|
||||
3. If multiple actions are needed, use one tool at a time per message to accomplish the task iteratively, with each tool use being informed by the result of the previous tool use. Do not assume the outcome of any tool use. Each step must be informed by the previous step's result.
|
||||
4. Formulate your tool use using the XML format specified for each tool.
|
||||
5. After each tool use, the user will respond with the result of that tool use. This result will provide you with the necessary information to continue your task or make further decisions. This response may include:
|
||||
- Information about whether the tool succeeded or failed, along with any reasons for failure.
|
||||
- Linter errors that may have arisen due to the changes you made, which you'll need to address.
|
||||
- New terminal output in reaction to the changes, which you may need to consider or act upon.
|
||||
- Any other relevant feedback or information related to the tool use.
|
||||
6. ALWAYS wait for user confirmation after each tool use before proceeding. Never assume the success of a tool use without explicit confirmation of the result from the user.
|
||||
|
||||
It is crucial to proceed step-by-step, waiting for the user's message after each tool use before moving forward with the task. This approach allows you to:
|
||||
1. Confirm the success of each step before proceeding.
|
||||
2. Address any issues or errors that arise immediately.
|
||||
3. Adapt your approach based on new information or unexpected results.
|
||||
4. Ensure that each action builds correctly on the previous ones.
|
||||
|
||||
By waiting for and carefully considering the user's response after each tool use, you can react accordingly and make informed decisions about how to proceed with the task. This iterative process helps ensure the overall success and accuracy of your work.
|
||||
|
||||
====
|
||||
|
||||
MCP SERVERS
|
||||
|
||||
The Model Context Protocol (MCP) enables communication between the system and locally running MCP servers that provide additional tools and resources to extend your capabilities.
|
||||
|
||||
# Connected MCP Servers
|
||||
|
||||
When a server is connected, you can use the server's tools via the \`${useMCPToolDefinition.name}\` tool, and access the server's resources via the \`${accessMcpResourceToolDefinition.name}\` tool.
|
||||
|
||||
${
|
||||
mcpHub.getServers().length > 0
|
||||
? `${mcpHub
|
||||
.getServers()
|
||||
.filter((server) => server.status === "connected")
|
||||
.map((server) => {
|
||||
const tools = server.tools
|
||||
?.map((tool) => {
|
||||
const schemaStr = tool.inputSchema
|
||||
? ` Input Schema:
|
||||
${JSON.stringify(tool.inputSchema, null, 2).split("\n").join("\n ")}`
|
||||
: ""
|
||||
|
||||
return `- ${tool.name}: ${tool.description}\n${schemaStr}`
|
||||
})
|
||||
.join("\n\n")
|
||||
|
||||
const templates = server.resourceTemplates
|
||||
?.map((template) => `- ${template.uriTemplate} (${template.name}): ${template.description}`)
|
||||
.join("\n")
|
||||
|
||||
const resources = server.resources
|
||||
?.map((resource) => `- ${resource.uri} (${resource.name}): ${resource.description}`)
|
||||
.join("\n")
|
||||
|
||||
const config = JSON.parse(server.config)
|
||||
|
||||
return (
|
||||
`## ${server.name} (\`${config.command}${config.args && Array.isArray(config.args) ? ` ${config.args.join(" ")}` : ""}\`)` +
|
||||
(tools ? `\n\n### Available Tools\n${tools}` : "") +
|
||||
(templates ? `\n\n### Resource Templates\n${templates}` : "") +
|
||||
(resources ? `\n\n### Direct Resources\n${resources}` : "")
|
||||
)
|
||||
})
|
||||
.join("\n\n")}`
|
||||
: "(No MCP servers currently connected)"
|
||||
}
|
||||
|
||||
====
|
||||
|
||||
EDITING FILES
|
||||
|
||||
You have access to two tools for working with files: **${writeTool.name}** and **replace_in_file**. Understanding their roles and selecting the right one for the job will help ensure efficient and accurate modifications.
|
||||
|
||||
# ${writeTool.name}
|
||||
|
||||
## Purpose
|
||||
|
||||
- Create a new file, or overwrite the entire contents of an existing file.
|
||||
|
||||
## When to Use
|
||||
|
||||
- Initial file creation, such as when scaffolding a new project.
|
||||
- Overwriting large boilerplate files where you want to replace the entire content at once.
|
||||
- When the complexity or number of changes would make replace_in_file unwieldy or error-prone.
|
||||
- When you need to completely restructure a file's content or change its fundamental organization.
|
||||
|
||||
## Important Considerations
|
||||
|
||||
- Using ${writeTool.name} requires providing the file's complete final content.
|
||||
- If you only need to make small changes to an existing file, consider using replace_in_file instead to avoid unnecessarily rewriting the entire file.
|
||||
- While ${writeTool.name} should not be your default choice, don't hesitate to use it when the situation truly calls for it.
|
||||
|
||||
# replace_in_file
|
||||
|
||||
## Purpose
|
||||
|
||||
- Make targeted edits to specific parts of an existing file without overwriting the entire file.
|
||||
|
||||
## When to Use
|
||||
|
||||
- Small, localized changes like updating a few lines, function implementations, changing variable names, modifying a section of text, etc.
|
||||
- Targeted improvements where only specific portions of the file's content needs to be altered.
|
||||
- Especially useful for long files where much of the file will remain unchanged.
|
||||
|
||||
## Advantages
|
||||
|
||||
- More efficient for minor edits, since you don't need to supply the entire file content.
|
||||
- Reduces the chance of errors that can occur when overwriting large files.
|
||||
|
||||
# Choosing the Appropriate Tool
|
||||
|
||||
- **Default to replace_in_file** for most changes. It's the safer, more precise option that minimizes potential issues.
|
||||
- **Use ${writeTool.name}** when:
|
||||
- Creating new files
|
||||
- The changes are so extensive that using replace_in_file would be more complex or risky
|
||||
- You need to completely reorganize or restructure a file
|
||||
- The file is relatively small and the changes affect most of its content
|
||||
- You're generating boilerplate or template files
|
||||
|
||||
# Auto-formatting Considerations
|
||||
|
||||
- After using either ${writeTool.name} or replace_in_file, the user's editor may automatically format the file
|
||||
- This auto-formatting may modify the file contents, for example:
|
||||
- Breaking single lines into multiple lines
|
||||
- Adjusting indentation to match project style (e.g. 2 spaces vs 4 spaces vs tabs)
|
||||
- Converting single quotes to double quotes (or vice versa based on project preferences)
|
||||
- Organizing imports (e.g. sorting, grouping by type)
|
||||
- Adding/removing trailing commas in objects and arrays
|
||||
- Enforcing consistent brace style (e.g. same-line vs new-line)
|
||||
- Standardizing semicolon usage (adding or removing based on style)
|
||||
- The ${writeTool.name} and replace_in_file tool responses will include the final state of the file after any auto-formatting
|
||||
- Use this final state as your reference point for any subsequent edits. This is ESPECIALLY important when crafting SEARCH blocks for replace_in_file which require the content to match what's in the file exactly.
|
||||
|
||||
# Workflow Tips
|
||||
|
||||
1. Before editing, assess the scope of your changes and decide which tool to use.
|
||||
2. For major overhauls or initial file creation, rely on ${writeTool.name}.
|
||||
3. Once the file has been edited with either ${writeTool.name} or replace_in_file, the system will provide you with the final state of the modified file. Use this updated content as the reference point for any subsequent SEARCH/REPLACE operations, since it reflects any auto-formatting or user-applied changes.
|
||||
4. All edits are applied in sequence, in the order they are provided
|
||||
5. All edits must be valid for the operation to succeed - if any edit fails, none will be applied
|
||||
6. Do not make more than 4 replacements in a single replace_in_file call, as this can lead to errors and make it difficult to track changes. If you need to make more than 4 changes, consider breaking them into multiple replace_in_file calls.
|
||||
7. Make sure a single old_str in a replace_in_file call is no more than 4 lines, as too many lines can lead to errors. If you need to replace a larger section, break it into smaller blocks.
|
||||
|
||||
By thoughtfully selecting between ${writeTool.name} and replace_in_file, you can make your file editing process smoother, safer, and more efficient.
|
||||
|
||||
====
|
||||
|
||||
ACT MODE V.S. PLAN MODE
|
||||
|
||||
In each user message, the environment_details will specify the current mode. There are two modes:
|
||||
|
||||
- ACT MODE: In this mode, you have access to all tools EXCEPT the ${planModeRespondToolDefinition.name} tool.
|
||||
- In ACT MODE, you use tools to accomplish the user's task. Once you've completed the user's task, you use the ${attemptCompletionToolDefinition.name} tool to present the result of the task to the user.
|
||||
- PLAN MODE: In this special mode, you have access to the ${planModeRespondToolDefinition.name} tool.
|
||||
- In PLAN MODE, the goal is to gather information and get context to create a detailed plan for accomplishing the task, which the user will review and approve before they switch you to ACT MODE to implement the solution.
|
||||
- In PLAN MODE, when you need to converse with the user or present a plan, you should use the ${planModeRespondToolDefinition.name} tool to deliver your response directly, rather than using <thinking> tags to analyze when to respond. Do not talk about using ${planModeRespondToolDefinition.name} - just use it directly to share your thoughts and provide helpful answers.
|
||||
|
||||
## What is PLAN MODE?
|
||||
|
||||
- While you are usually in ACT MODE, the user may switch to PLAN MODE in order to have a back and forth with you to plan how to best accomplish the task.
|
||||
- When starting in PLAN MODE, depending on the user's request, you may need to do some information gathering e.g. using ${readTool.name} or ${grepToolDefinition.name} to get more context about the task. You may also ask the user clarifying questions to get a better understanding of the task. You may return mermaid diagrams to visually display your understanding.
|
||||
- Once you've gained more context about the user's request, you should architect a detailed plan for how you will accomplish the task. Returning mermaid diagrams may be helpful here as well.
|
||||
- Then you might ask the user if they are pleased with this plan, or if they would like to make any changes. Think of this as a brainstorming session where you can discuss the task and plan the best way to accomplish it.
|
||||
- If at any point a mermaid diagram would make your plan clearer to help the user quickly see the structure, you are encouraged to include a Mermaid code block in the response. (Note: if you use colors in your mermaid diagrams, be sure to use high contrast colors so the text is readable.)
|
||||
- Finally once it seems like you've reached a good plan, ask the user to switch you back to ACT MODE to implement the solution.
|
||||
|
||||
====
|
||||
|
||||
CAPABILITIES
|
||||
|
||||
- You have access to tools that let you execute CLI commands on the user's computer, list files, view source code definitions, regex search${
|
||||
supportsBrowserUse ? ", use the browser" : ""
|
||||
}, read and edit files, and ask follow-up questions. These tools help you effectively accomplish a wide range of tasks, such as writing code, making edits or improvements to existing files, understanding the current state of a project, performing system operations, and much more.
|
||||
- When the user initially gives you a task, a recursive list of all filepaths in the current working directory ('${cwd.toPosix()}') will be included in environment_details. This provides an overview of the project's file structure, offering key insights into the project from directory/file names (how developers conceptualize and organize their code) and file extensions (the language used). This can also guide decision-making on which files to explore further. If you pass 'true' for the recursive parameter, it will list files recursively. Otherwise, it will list files at the top level, which is better suited for generic directories where you don't necessarily need the nested structure, like the Desktop.
|
||||
- You can use ${grepToolDefinition.name} to perform regex searches across files in a specified directory, outputting context-rich results that include surrounding lines. This is particularly useful for understanding code patterns, finding specific implementations, or identifying areas that need refactoring.
|
||||
- You can use the ${listCodeDefinitionNamesTool.name} tool to get an overview of source code definitions for all files at the top level of a specified directory. This can be particularly useful when you need to understand the broader context and relationships between certain parts of the code. You may need to call this tool multiple times to understand various parts of the codebase related to the task.
|
||||
- For example, when asked to make edits or improvements you might analyze the file structure in the initial environment_details to get an overview of the project, then use ${listCodeDefinitionNamesTool.name} to get further insight using source code definitions for files located in relevant directories, then ${readTool.name} to examine the contents of relevant files, analyze the code and suggest improvements or make necessary edits, then use the replace_in_file tool to implement changes. If you refactored code that could affect other parts of the codebase, you could use ${grepToolDefinition.name} to ensure you update other files as needed.
|
||||
- You can use the ${bashTool.name} tool to run commands on the user's computer whenever you feel it can help accomplish the user's task. When you need to execute a CLI command, you must provide a clear explanation of what the command does. Prefer to execute complex CLI commands over creating executable scripts, since they are more flexible and easier to run. Interactive and long-running commands are allowed, since the commands are run in the user's VSCode terminal. The user may keep commands running in the background and you will be kept updated on their status along the way. Each command you execute is run in a new terminal instance.${
|
||||
supportsBrowserUse
|
||||
? `\n- You can use the ${browserActionTool.name} tool to interact with websites (including html files and locally running development servers) through a Puppeteer-controlled browser when you feel it is necessary in accomplishing the user's task. This tool is particularly useful for web development tasks as it allows you to launch a browser, navigate to pages, interact with elements through clicks and keyboard input, and capture the results through screenshots and console logs. This tool may be useful at key stages of web development tasks-such as after implementing new features, making substantial changes, when troubleshooting issues, or to verify the result of your work. You can analyze the provided screenshots to ensure correct rendering or identify errors, and review console logs for runtime issues.\n - For example, if asked to add a component to a react website, you might create the necessary files, use the ${bashTool.name} tool to run the site locally, then use ${browserActionTool.name} to launch the browser, navigate to the local server, and verify the component renders & functions correctly before closing the browser.`
|
||||
: ""
|
||||
}
|
||||
- You have access to MCP servers that may provide additional tools and resources. Each server may provide different capabilities that you can use to accomplish tasks more effectively.
|
||||
- You can use LaTeX syntax in your responses to render mathematical expressions
|
||||
|
||||
====
|
||||
|
||||
RULES
|
||||
|
||||
- Your current working directory is: ${cwd.toPosix()}
|
||||
- You cannot \`cd\` into a different directory to complete a task. You are stuck operating from '${cwd.toPosix()}', so be sure to pass in the correct 'path' parameter when using tools that require a path.
|
||||
- Do not use the ~ character or $HOME to refer to the home directory.
|
||||
- Before using the ${bashTool.name} tool, you must first think about the SYSTEM INFORMATION context provided to understand the user's environment and tailor your commands to ensure they are compatible with their system. You must also consider if the command you need to run should be executed in a specific directory outside of the current working directory '${cwd.toPosix()}', and if so prepend with \`cd\`'ing into that directory && then executing the command (as one command since you are stuck operating from '${cwd.toPosix()}'). For example, if you needed to run \`npm install\` in a project outside of '${cwd.toPosix()}', you would need to prepend with a \`cd\` i.e. pseudocode for this would be \`cd (path to project) && (command, in this case npm install)\`.
|
||||
- When using the ${grepToolDefinition.name} tool, craft your regex patterns carefully to balance specificity and flexibility. Based on the user's task you may use it to find code patterns, TODO comments, function definitions, or any text-based information across the project. The results include context, so analyze the surrounding code to better understand the matches. Leverage the ${grepToolDefinition.name} tool in combination with other tools for more comprehensive analysis. For example, use it to find specific code patterns, then use ${readTool.name} to examine the full context of interesting matches before using replace_in_file to make informed changes.
|
||||
- When creating a new project (such as an app, website, or any software project), organize all new files within a dedicated project directory unless the user specifies otherwise. Use appropriate file paths when creating files, as the ${writeTool.name} tool will automatically create any necessary directories. Structure the project logically, adhering to best practices for the specific type of project being created. Unless otherwise specified, new projects should be easily run without additional setup, for example most projects can be built in HTML, CSS, and JavaScript - which you can open in a browser.
|
||||
- Be sure to consider the type of project (e.g. Python, JavaScript, web application) when determining the appropriate structure and files to include. Also consider what files may be most relevant to accomplishing the task, for example looking at a project's manifest file would help you understand the project's dependencies, which you could incorporate into any code you write.
|
||||
- When making changes to code, always consider the context in which the code is being used. Ensure that your changes are compatible with the existing codebase and that they follow the project's coding standards and best practices.
|
||||
- When you want to modify a file, use the replace_in_file or ${writeTool.name} tool directly with the desired changes. You do not need to display the changes before using the tool.
|
||||
- Do not ask for more information than necessary. Use the tools provided to accomplish the user's request efficiently and effectively. When you've completed your task, you must use the ${attemptCompletionToolDefinition.name} tool to present the result to the user. The user may provide feedback, which you can use to make improvements and try again.
|
||||
- You are only allowed to ask the user questions using the ${askQuestionToolDefinition.name} tool. Use this tool only when you need additional details to complete a task, and be sure to use a clear and concise question that will help you move forward with the task. However if you can use the available tools to avoid having to ask the user questions, you should do so. For example, if the user mentions a file that may be in an outside directory like the Desktop, you should use the ${lsToolDefinition.name} tool to list the files in the Desktop and check if the file they are talking about is there, rather than asking the user to provide the file path themselves.
|
||||
- When executing commands, if you don't see the expected output, assume the terminal executed the command successfully and proceed with the task. The user's terminal may be unable to stream the output back properly. If you absolutely need to see the actual terminal output, use the ${askQuestionToolDefinition.name} tool to request the user to copy and paste it back to you.
|
||||
- The user may provide a file's contents directly in their message, in which case you shouldn't use the ${readTool.name} tool to get the file contents again since you already have it.
|
||||
- Your goal is to try to accomplish the user's task, NOT engage in a back and forth conversation.${
|
||||
supportsBrowserUse
|
||||
? `\n- The user may ask generic non-development tasks, such as "what\'s the latest news" or "look up the weather in San Diego", in which case you might use the ${browserActionTool.name} tool to complete the task if it makes sense to do so, rather than trying to create a website or using curl to answer the question. However, if an available MCP server tool or resource can be used instead, you should prefer to use it over ${browserActionTool.name}.`
|
||||
: ""
|
||||
}
|
||||
- NEVER end ${attemptCompletionToolDefinition.name} result with a question or request to engage in further conversation! Formulate the end of your result in a way that is final and does not require further input from the user.
|
||||
- You are STRICTLY FORBIDDEN from starting your messages with "Great", "Certainly", "Okay", "Sure". You should NOT be conversational in your responses, but rather direct and to the point. For example you should NOT say "Great, I've updated the CSS" but instead something like "I've updated the CSS". It is important you be clear and technical in your messages.
|
||||
- When presented with images, utilize your vision capabilities to thoroughly examine them and extract meaningful information. Incorporate these insights into your thought process as you accomplish the user's task.
|
||||
- At the end of each user message, you will automatically receive environment_details. This information is not written by the user themselves, but is auto-generated to provide potentially relevant context about the project structure and environment. While this information can be valuable for understanding the project context, do not treat it as a direct part of the user's request or response. Use it to inform your actions and decisions, but don't assume the user is explicitly asking about or referring to this information unless they clearly do so in their message. When using environment_details, explain your actions clearly to ensure the user understands, as they may not be aware of these details.
|
||||
- Before executing commands, check the "Actively Running Terminals" section in environment_details. If present, consider how these active processes might impact your task. For example, if a local development server is already running, you wouldn't need to start it again. If no active terminals are listed, proceed with command execution as normal.
|
||||
- When using the replace_in_file tool, you must include complete lines
|
||||
- It is critical you wait for the user's response after each tool use, in order to confirm the success of the tool use. For example, if asked to make a todo app, you would create a file, wait for the user's response it was created successfully, then create another file if needed, wait for the user's response it was created successfully, etc.${
|
||||
supportsBrowserUse
|
||||
? ` Then if you want to test your work, you might use ${browserActionTool.name} to launch the site, wait for the user's response confirming the site was launched along with a screenshot, then perhaps e.g., click a button to test functionality if needed, wait for the user's response confirming the button was clicked along with a screenshot of the new state, before finally closing the browser.`
|
||||
: ""
|
||||
}
|
||||
- MCP operations should be used one at a time, similar to other tool usage. Wait for confirmation of success before proceeding with additional operations.
|
||||
|
||||
====
|
||||
|
||||
SYSTEM INFORMATION
|
||||
|
||||
Operating System: ${osName()}
|
||||
Default Shell: ${getShell()}
|
||||
Home Directory: ${os.homedir().toPosix()}
|
||||
Current Working Directory: ${cwd.toPosix()}
|
||||
|
||||
====
|
||||
|
||||
If the user asks for help or wants to give feedback inform them of the following:
|
||||
- To give feedback, users should report the issue using the /reportbug slash command in the chat.
|
||||
|
||||
When the user directly asks about Cline (eg 'can Cline do...', 'does Cline have...') or asks in second person (eg 'are you able...', 'can you do...'), first use the ${webFetchToolDefinition.name} tool to gather information to answer the question from Cline docs at https://docs.cline.bot.
|
||||
- The available sub-pages are \`getting-started\` (Intro for new coders, installing Cline and dev essentials), \`model-selection\` (Model Selection Guide, Custom Model Configs, Bedrock, Vertex, Codestral, LM Studio, Ollama), \`features\` (Auto approve, Checkpoints, Cline rules, Drag & Drop, Plan & Act, Workflows, etc), \`task-management\` (Task and Context Management in Cline), \`prompt-engineering\` (Improving your prompting skills, Prompt Engineering Guide), \`cline-tools\` (Cline Tools Reference Guide, New Task Tool, Remote Browser Support, Slash Commands), \`mcp\` (MCP Overview, Adding/Configuring Servers, Transport Mechanisms, MCP Dev Protocol), \`enterprise\` (Cloud provider integration, Security concerns, Custom instructions), \`more-info\` (Telemetry and other reference content)
|
||||
- Example: https://docs.cline.bot/features/auto-approve
|
||||
|
||||
====
|
||||
|
||||
OBJECTIVE
|
||||
|
||||
You accomplish a given task iteratively, breaking it down into clear steps and working through them methodically.
|
||||
|
||||
1. Analyze the user's task and set clear, achievable goals to accomplish it. Prioritize these goals in a logical order.
|
||||
2. Work through these goals sequentially, utilizing available tools one at a time as necessary. Each goal should correspond to a distinct step in your problem-solving process. You will be informed on the work completed and what's remaining as you go.
|
||||
3. Remember, you have extensive capabilities with access to a wide range of tools that can be used in powerful and clever ways as necessary to accomplish each goal. Before calling a tool, do some analysis within <thinking></thinking> tags. First, analyze the file structure provided in environment_details to gain context and insights for proceeding effectively. Then, think about which of the provided tools is the most relevant tool to accomplish the user's task. Next, go through each of the required parameters of the relevant tool and determine if the user has directly provided or given enough information to infer a value. When deciding if the parameter can be inferred, carefully consider all the context to see if it supports a specific value. If all of the required parameters are present or can be reasonably inferred, close the thinking tag and proceed with the tool use. BUT, if one of the values for a required parameter is missing, DO NOT invoke the tool (not even with fillers for the missing params) and instead, ask the user to provide the missing parameters using the ${askQuestionToolDefinition.name} tool. DO NOT ask for more information on optional parameters if it is not provided.
|
||||
4. Once you've completed the user's task, you must use the ${attemptCompletionToolDefinition.name} tool to present the result of the task to the user. You may also provide a CLI command to showcase the result of your task; this can be particularly useful for web development tasks, where you can run e.g. \`open index.html\` to show the website you've built.
|
||||
5. The user may provide feedback, which you can use to make improvements and try again. But DO NOT continue in pointless back and forth conversations, i.e. don't end your responses with questions or offers for further assistance.`
|
||||
|
||||
const tools = [readTool, writeTool, askQuestionToolDefinition, planModeRespondToolDefinition, bashTool, lsToolDefinition, grepToolDefinition, webFetchToolDefinition, listCodeDefinitionNamesTool, useMCPToolDefinition, accessMcpResourceToolDefinition, loadMcpDocumentationTool, newTaskToolDefinition];
|
||||
if (supportsBrowserUse) {
|
||||
tools.push(browserActionTool);
|
||||
}
|
||||
|
||||
return createAntmlToolPrompt(tools, true, systemPrompt);
|
||||
}
|
||||
@@ -0,0 +1,283 @@
|
||||
function escapeXml(text: string): string {
|
||||
// Anything that could be interpreted as markup has to be entity-encoded
|
||||
return text.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">")
|
||||
}
|
||||
|
||||
export interface ToolDefinition {
|
||||
name: string
|
||||
description?: string
|
||||
descriptionForAgent?: string
|
||||
inputSchema: {
|
||||
type: string
|
||||
properties: Record<string, any>
|
||||
required?: string[]
|
||||
[key: string]: any
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts a single tool definition (JSON schema) to the <function> tag format.
|
||||
* This is for *defining* the tool, not calling it.
|
||||
* @param toolDef The tool definition object
|
||||
* @returns The tool definition as a JSON string wrapped in <function> tags
|
||||
*/
|
||||
export function toolDefinitionToAntmlDefinition(toolDef: ToolDefinition): string {
|
||||
// Restructure the parameters object to match the expected order
|
||||
const { type, properties, required, ...rest } = toolDef.inputSchema
|
||||
const parameters = {
|
||||
properties,
|
||||
required,
|
||||
type,
|
||||
...rest,
|
||||
}
|
||||
|
||||
const functionDef = {
|
||||
description: toolDef.descriptionForAgent || toolDef.description || "",
|
||||
name: toolDef.name,
|
||||
parameters,
|
||||
}
|
||||
|
||||
// 1. Create a custom JSON string with the exact format we want
|
||||
let rawJson = `{"description": "${functionDef.description}", "name": "${functionDef.name}", "parameters": {`
|
||||
|
||||
// Add properties
|
||||
rawJson += `"properties": {`
|
||||
const propEntries = Object.entries(parameters.properties)
|
||||
propEntries.forEach(([propName, propDef], index) => {
|
||||
rawJson += `"${propName}": {`
|
||||
rawJson += `"description": "${(propDef as any).description || ""}", `
|
||||
rawJson += `"type": "${(propDef as any).type || "string"}"`
|
||||
rawJson += `}`
|
||||
if (index < propEntries.length - 1) {
|
||||
rawJson += ", "
|
||||
}
|
||||
})
|
||||
rawJson += `}, `
|
||||
|
||||
// Add required
|
||||
rawJson += `"required": ${JSON.stringify(parameters.required || [])}, `
|
||||
|
||||
// Add type
|
||||
rawJson += `"type": "object"`
|
||||
|
||||
// Close parameters and the whole object
|
||||
rawJson += `}}`
|
||||
|
||||
// 2. Escape <, > and & so the JSON can sit INSIDE the XML tag safely.
|
||||
// (Quotes don’t need escaping - they’re not markup.)
|
||||
const safeJson = escapeXml(rawJson)
|
||||
|
||||
// 3. Return wrapped in <function> tags
|
||||
return `<function>${safeJson}</function>`
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts multiple tool definitions to the complete <functions> block.
|
||||
* This is for *defining* the tools.
|
||||
* @param toolDefs Array of tool definition objects
|
||||
* @returns Complete <functions> block with all tool definitions
|
||||
*/
|
||||
export function toolDefinitionsToAntmlDefinitions(toolDefs: ToolDefinition[]): string {
|
||||
const functionTags = toolDefs.map(toolDefinitionToAntmlDefinition)
|
||||
return `Here are the functions available in JSONSchema format:
|
||||
<functions>
|
||||
${functionTags.join("\n")}
|
||||
</functions>`
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates an example of an ANTML tool call for a given tool definition.
|
||||
* This is for *calling* a tool.
|
||||
* @param toolDef The tool definition object
|
||||
* @param exampleValues Optional example values for parameters
|
||||
* @returns Example ANTML function call string
|
||||
*/
|
||||
export function toolDefinitionToAntmlCallExample(toolDef: ToolDefinition, exampleValues: Record<string, any> = {}): string {
|
||||
const props = toolDef.inputSchema.properties ?? {}
|
||||
|
||||
const paramLines = Object.keys(props).length
|
||||
? Object.entries(props)
|
||||
.map(([name]) => {
|
||||
const value = exampleValues[name] ?? `$${name.toUpperCase()}` // placeholder
|
||||
// Don't escape XML here - the example should show raw format
|
||||
return `<parameter name="${name}">${value}</parameter>`
|
||||
})
|
||||
.join("\n")
|
||||
: ""
|
||||
|
||||
// Only include one invoke block
|
||||
return ["<function_calls>", `<invoke name="${toolDef.name}">`, paramLines, "</invoke>", "</function_calls>"]
|
||||
.filter(Boolean)
|
||||
.join("\n")
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a complete system prompt section for tools in ANTML format,
|
||||
* including instructions and tool definitions.
|
||||
* @param toolDefs Array of tool definition objects
|
||||
* @param includeInstructions Whether to include the standard tool calling instructions
|
||||
* @returns Complete system prompt section for ANTML tools
|
||||
*/
|
||||
export function createAntmlToolPrompt(toolDefs: ToolDefinition[], includeInstructions = true, systemPrompt = ""): string {
|
||||
if (toolDefs.length === 0) {
|
||||
if (!includeInstructions) {
|
||||
return ""
|
||||
}
|
||||
|
||||
const noToolsMessage = [
|
||||
"In this environment you have access to a set of tools you can use to answer the user's question.",
|
||||
'You can invoke functions by writing a "<function_calls>" block like the following as part of your reply to the user:',
|
||||
"<function_calls>",
|
||||
'<invoke name="$FUNCTION_NAME">',
|
||||
'<parameter name="$PARAMETER_NAME">$PARAMETER_VALUE</parameter>',
|
||||
"...",
|
||||
"</invoke>",
|
||||
"</function_calls>",
|
||||
"",
|
||||
"String and scalar parameters should be specified as is, while lists and objects should use JSON format.",
|
||||
"",
|
||||
"However, no tools are currently available.",
|
||||
].join("\n")
|
||||
|
||||
return noToolsMessage
|
||||
}
|
||||
|
||||
let prompt = ""
|
||||
|
||||
if (includeInstructions) {
|
||||
const instructionLines = [
|
||||
"In this environment you have access to a set of tools you can use to answer the user's question.",
|
||||
'You can invoke functions by writing a "<function_calls>" block like the following as part of your reply to the user:',
|
||||
"<function_calls>",
|
||||
'<invoke name="$FUNCTION_NAME">',
|
||||
'<parameter name="$PARAMETER_NAME">$PARAMETER_VALUE</parameter>',
|
||||
"...",
|
||||
"</invoke>",
|
||||
"</function_calls>",
|
||||
"",
|
||||
"String and scalar parameters should be specified as is, while lists and objects should use JSON format.",
|
||||
"",
|
||||
]
|
||||
prompt += instructionLines.join("\n")
|
||||
}
|
||||
|
||||
prompt += toolDefinitionsToAntmlDefinitions(toolDefs)
|
||||
|
||||
if (includeInstructions) {
|
||||
const closingInstructions = [
|
||||
"",
|
||||
"",
|
||||
systemPrompt,
|
||||
"",
|
||||
"",
|
||||
"Answer the user's request using the relevant tool(s), if they are available. Check that all the required parameters for each tool call are provided or can reasonably be inferred from context. IF there are no relevant tools or there are missing values for required parameters, ask the user to supply these values; otherwise proceed with the tool calls. If the user provides a specific value for a parameter (for example provided in quotes), make sure to use that value EXACTLY. DO NOT make up values for or ask about optional parameters. Carefully analyze descriptive terms in the request as they may indicate required parameter values that should be included even if not explicitly quoted.",
|
||||
]
|
||||
prompt += closingInstructions.join("\n")
|
||||
}
|
||||
|
||||
return prompt // Don't trim - preserve exact formatting
|
||||
}
|
||||
|
||||
// --- SimpleXML Functions (Cline's internal format) ---
|
||||
|
||||
/**
|
||||
* Converts a single tool definition to the SimpleXML format
|
||||
* as used by Cline's current system prompts for non-ANTML models.
|
||||
* @param toolDef The tool definition object
|
||||
* @returns The tool definition formatted for SimpleXML usage
|
||||
*/
|
||||
export function toolDefinitionToSimpleXml(toolDef: ToolDefinition): string {
|
||||
const description = toolDef.descriptionForAgent || toolDef.description || ""
|
||||
const properties = toolDef.inputSchema.properties || {}
|
||||
const required = toolDef.inputSchema.required || []
|
||||
|
||||
let parameterDocs = ""
|
||||
if (Object.keys(properties).length > 0) {
|
||||
parameterDocs = "Parameters:\n"
|
||||
for (const [paramName, paramDef] of Object.entries(properties)) {
|
||||
const isRequired = required.includes(paramName)
|
||||
const requiredText = isRequired ? "(required)" : "(optional)"
|
||||
const paramDescription = (paramDef as any).description || "No description."
|
||||
parameterDocs += `- ${paramName}: ${requiredText} ${paramDescription}\n`
|
||||
}
|
||||
}
|
||||
|
||||
const exampleParams = Object.keys(properties)
|
||||
.map((paramName) => `<${paramName}>${paramName} value here</${paramName}>`)
|
||||
.join("\n")
|
||||
|
||||
const usageExample = `Usage:
|
||||
<${toolDef.name}>
|
||||
${exampleParams.length > 0 ? exampleParams + "\n" : ""}</${toolDef.name}>`
|
||||
|
||||
return `## ${toolDef.name}
|
||||
Description: ${description}
|
||||
${parameterDocs.trim()}
|
||||
${usageExample}`
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts multiple tool definitions to the complete SimpleXML format.
|
||||
* @param toolDefs Array of tool definition objects
|
||||
* @returns Complete tools documentation in SimpleXML format
|
||||
*/
|
||||
export function toolDefinitionsToSimpleXml(toolDefs: ToolDefinition[]): string {
|
||||
const toolDocs = toolDefs.map((toolDef) => toolDefinitionToSimpleXml(toolDef))
|
||||
return `# Tools
|
||||
|
||||
${toolDocs.join("\n\n")}`
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a complete system prompt section for tools in SimpleXML format.
|
||||
* @param toolDefs Array of tool definition objects
|
||||
* @param includeInstructions Whether to include the standard tool calling instructions
|
||||
* @returns Complete system prompt section for SimpleXML tools
|
||||
*/
|
||||
export function createSimpleXmlToolPrompt(toolDefs: ToolDefinition[], includeInstructions: boolean = true): string {
|
||||
if (toolDefs.length === 0) {
|
||||
return ""
|
||||
}
|
||||
|
||||
let prompt = ""
|
||||
|
||||
if (includeInstructions) {
|
||||
prompt += `TOOL USE
|
||||
|
||||
You have access to a set of tools that are executed upon the user's approval. You can use one tool per message, and will receive the result of that tool use in the user's response. You use tools step-by-step to accomplish a given task, with each tool use informed by the result of the previous tool use.
|
||||
|
||||
# Tool Use Formatting
|
||||
|
||||
Tool use is formatted using XML-style tags. The tool name is enclosed in opening and closing tags, and each parameter is similarly enclosed within its own set of tags. Here's the structure:
|
||||
|
||||
<tool_name>
|
||||
<parameter1_name>value1</parameter1_name>
|
||||
<parameter2_name>value2</parameter2_name>
|
||||
...
|
||||
</tool_name>
|
||||
|
||||
For example:
|
||||
|
||||
<read_file>
|
||||
<path>src/main.js</path>
|
||||
</read_file>
|
||||
|
||||
Always adhere to this format for the tool use to ensure proper parsing and execution.
|
||||
`
|
||||
}
|
||||
|
||||
prompt += toolDefinitionsToSimpleXml(toolDefs)
|
||||
|
||||
if (includeInstructions) {
|
||||
prompt += `
|
||||
|
||||
# Tool Use Guidelines
|
||||
|
||||
1. Choose the most appropriate tool based on the task and the tool descriptions provided.
|
||||
2. If multiple actions are needed, use one tool at a time per message to accomplish the task iteratively.
|
||||
3. Formulate your tool use using the XML format specified for each tool.
|
||||
4. After each tool use, the user will respond with the result of that tool use.
|
||||
5. ALWAYS wait for user confirmation after each tool use before proceeding.`
|
||||
}
|
||||
return prompt.trimEnd()
|
||||
}
|
||||
@@ -41,15 +41,31 @@ Otherwise, if you have not completed the task and do not need additional informa
|
||||
invalidMcpToolArgumentError: (serverName: string, toolName: string) =>
|
||||
`Invalid JSON argument used with ${serverName} for ${toolName}. Please retry with a properly formatted JSON argument.`,
|
||||
|
||||
toolResult: (text: string, images?: string[]): string | Array<Anthropic.TextBlockParam | Anthropic.ImageBlockParam> => {
|
||||
if (images && images.length > 0) {
|
||||
const textBlock: Anthropic.TextBlockParam = { type: "text", text }
|
||||
const imageBlocks: Anthropic.ImageBlockParam[] = formatImagesIntoBlocks(images)
|
||||
// Placing images after text leads to better results
|
||||
return [textBlock, ...imageBlocks]
|
||||
} else {
|
||||
toolResult: (
|
||||
text: string,
|
||||
images?: string[],
|
||||
fileString?: string,
|
||||
): string | Array<Anthropic.TextBlockParam | Anthropic.ImageBlockParam> => {
|
||||
let toolResultOutput = []
|
||||
|
||||
if (!(images && images.length > 0) && !fileString) {
|
||||
return text
|
||||
}
|
||||
|
||||
const textBlock: Anthropic.TextBlockParam = { type: "text", text }
|
||||
toolResultOutput.push(textBlock)
|
||||
|
||||
if (images && images.length > 0) {
|
||||
const imageBlocks: Anthropic.ImageBlockParam[] = formatImagesIntoBlocks(images)
|
||||
toolResultOutput.push(...imageBlocks)
|
||||
}
|
||||
|
||||
if (fileString) {
|
||||
const fileBlock: Anthropic.TextBlockParam = { type: "text", text: fileString }
|
||||
toolResultOutput.push(fileBlock)
|
||||
}
|
||||
|
||||
return toolResultOutput
|
||||
},
|
||||
|
||||
imageBlocks: (images?: string[]): Anthropic.ImageBlockParam[] => {
|
||||
|
||||
@@ -3,13 +3,19 @@ import os from "os"
|
||||
import osName from "os-name"
|
||||
import { McpHub } from "@services/mcp/McpHub"
|
||||
import { BrowserSettings } from "@shared/BrowserSettings"
|
||||
import { SYSTEM_PROMPT_CLAUDE4 } from "./model_prompts/claude4"
|
||||
|
||||
export const SYSTEM_PROMPT = async (
|
||||
cwd: string,
|
||||
supportsBrowserUse: boolean,
|
||||
mcpHub: McpHub,
|
||||
browserSettings: BrowserSettings,
|
||||
) => `You are Cline, a highly skilled software engineer with extensive knowledge in many programming languages, frameworks, design patterns, and best practices.
|
||||
isClaude4ModelFamily: boolean = false,
|
||||
) => {
|
||||
if (isClaude4ModelFamily) {
|
||||
return SYSTEM_PROMPT_CLAUDE4(cwd, supportsBrowserUse, mcpHub, browserSettings)
|
||||
} else {
|
||||
return `You are Cline, a highly skilled software engineer with extensive knowledge in many programming languages, frameworks, design patterns, and best practices.
|
||||
|
||||
====
|
||||
|
||||
@@ -103,9 +109,10 @@ Usage:
|
||||
<path>File path here</path>
|
||||
<diff>
|
||||
Search and replace blocks here
|
||||
</diff>
|
||||
</diff>
|
||||
</replace_in_file>
|
||||
|
||||
|
||||
## search_files
|
||||
Description: Request to perform a regex search across files in a specified directory, providing context-rich results. This tool searches for patterns or specific content across multiple files, displaying each match with encapsulating context.
|
||||
Parameters:
|
||||
@@ -361,6 +368,7 @@ return (
|
||||
</diff>
|
||||
</replace_in_file>
|
||||
|
||||
|
||||
## Example 5: Requesting to use an MCP tool
|
||||
|
||||
<use_mcp_tool>
|
||||
@@ -532,7 +540,6 @@ You have access to two tools for working with files: **write_to_file** and **rep
|
||||
2. For targeted edits, apply replace_in_file with carefully crafted SEARCH/REPLACE blocks. If you need multiple changes, you can stack multiple SEARCH/REPLACE blocks within a single replace_in_file call.
|
||||
3. For major overhauls or initial file creation, rely on write_to_file.
|
||||
4. Once the file has been edited with either write_to_file or replace_in_file, the system will provide you with the final state of the modified file. Use this updated content as the reference point for any subsequent SEARCH/REPLACE operations, since it reflects any auto-formatting or user-applied changes.
|
||||
|
||||
By thoughtfully selecting between write_to_file and replace_in_file, you can make your file editing process smoother, safer, and more efficient.
|
||||
|
||||
====
|
||||
@@ -632,6 +639,8 @@ You accomplish a given task iteratively, breaking it down into clear steps and w
|
||||
3. Remember, you have extensive capabilities with access to a wide range of tools that can be used in powerful and clever ways as necessary to accomplish each goal. Before calling a tool, do some analysis within <thinking></thinking> tags. First, analyze the file structure provided in environment_details to gain context and insights for proceeding effectively. Then, think about which of the provided tools is the most relevant tool to accomplish the user's task. Next, go through each of the required parameters of the relevant tool and determine if the user has directly provided or given enough information to infer a value. When deciding if the parameter can be inferred, carefully consider all the context to see if it supports a specific value. If all of the required parameters are present or can be reasonably inferred, close the thinking tag and proceed with the tool use. BUT, if one of the values for a required parameter is missing, DO NOT invoke the tool (not even with fillers for the missing params) and instead, ask the user to provide the missing parameters using the ask_followup_question tool. DO NOT ask for more information on optional parameters if it is not provided.
|
||||
4. Once you've completed the user's task, you must use the attempt_completion tool to present the result of the task to the user. You may also provide a CLI command to showcase the result of your task; this can be particularly useful for web development tasks, where you can run e.g. \`open index.html\` to show the website you've built.
|
||||
5. The user may provide feedback, which you can use to make improvements and try again. But DO NOT continue in pointless back and forth conversations, i.e. don't end your responses with questions or offers for further assistance.`
|
||||
}
|
||||
}
|
||||
|
||||
export function addUserInstructions(
|
||||
settingsCustomInstructions?: string,
|
||||
|
||||
@@ -21,6 +21,7 @@ export type SecretKey =
|
||||
| "xaiApiKey"
|
||||
| "nebiusApiKey"
|
||||
| "sambanovaApiKey"
|
||||
| "cerebrasApiKey"
|
||||
|
||||
export type GlobalStateKey =
|
||||
| "apiProvider"
|
||||
|
||||
@@ -155,6 +155,7 @@ export async function getAllExtensionState(context: vscode.ExtensionContext) {
|
||||
thinkingBudgetTokens,
|
||||
reasoningEffort,
|
||||
sambanovaApiKey,
|
||||
cerebrasApiKey,
|
||||
nebiusApiKey,
|
||||
planActSeparateModelsSettingRaw,
|
||||
favoritedModelIds,
|
||||
@@ -244,6 +245,7 @@ export async function getAllExtensionState(context: vscode.ExtensionContext) {
|
||||
getGlobalState(context, "thinkingBudgetTokens") as Promise<number | undefined>,
|
||||
getGlobalState(context, "reasoningEffort") as Promise<string | undefined>,
|
||||
getSecret(context, "sambanovaApiKey") as Promise<string | undefined>,
|
||||
getSecret(context, "cerebrasApiKey") as Promise<string | undefined>,
|
||||
getSecret(context, "nebiusApiKey") as Promise<string | undefined>,
|
||||
getGlobalState(context, "planActSeparateModelsSetting") as Promise<boolean | undefined>,
|
||||
getGlobalState(context, "favoritedModelIds") as Promise<string[] | undefined>,
|
||||
@@ -357,6 +359,7 @@ export async function getAllExtensionState(context: vscode.ExtensionContext) {
|
||||
asksageApiUrl,
|
||||
xaiApiKey,
|
||||
sambanovaApiKey,
|
||||
cerebrasApiKey,
|
||||
nebiusApiKey,
|
||||
favoritedModelIds,
|
||||
requestTimeoutMs,
|
||||
@@ -451,6 +454,7 @@ export async function updateApiConfiguration(context: vscode.ExtensionContext, a
|
||||
reasoningEffort,
|
||||
clineApiKey,
|
||||
sambanovaApiKey,
|
||||
cerebrasApiKey,
|
||||
nebiusApiKey,
|
||||
favoritedModelIds,
|
||||
} = apiConfiguration
|
||||
@@ -512,6 +516,7 @@ export async function updateApiConfiguration(context: vscode.ExtensionContext, a
|
||||
await updateGlobalState(context, "reasoningEffort", reasoningEffort)
|
||||
await storeSecret(context, "clineApiKey", clineApiKey)
|
||||
await storeSecret(context, "sambanovaApiKey", sambanovaApiKey)
|
||||
await storeSecret(context, "cerebrasApiKey", cerebrasApiKey)
|
||||
await storeSecret(context, "nebiusApiKey", nebiusApiKey)
|
||||
await updateGlobalState(context, "favoritedModelIds", favoritedModelIds)
|
||||
await updateGlobalState(context, "requestTimeoutMs", apiConfiguration.requestTimeoutMs)
|
||||
@@ -542,6 +547,7 @@ export async function resetExtensionState(context: vscode.ExtensionContext) {
|
||||
"asksageApiKey",
|
||||
"xaiApiKey",
|
||||
"sambanovaApiKey",
|
||||
"cerebrasApiKey",
|
||||
"nebiusApiKey",
|
||||
]
|
||||
for (const key of secretKeys) {
|
||||
|
||||
+544
-141
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,20 @@
|
||||
const descriptionForAgent = `Request to access a resource provided by a connected MCP server. Resources represent data sources that can be used as context, such as files, API responses, or system information.`
|
||||
|
||||
export const accessMcpResourceToolDefinition = {
|
||||
name: "AccessMCPResource",
|
||||
descriptionForAgent,
|
||||
inputSchema: {
|
||||
type: "object",
|
||||
properties: {
|
||||
server_name: {
|
||||
type: "string",
|
||||
description: "The name of the MCP server providing the resource",
|
||||
},
|
||||
uri: {
|
||||
type: "string",
|
||||
description: "The URI identifying the specific resource to access",
|
||||
},
|
||||
},
|
||||
required: ["server_name", "uri"],
|
||||
},
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user