Compare commits

..
Author SHA1 Message Date
pashpashpash 9ba54aaee4 Update writing-documentation.md 2025-06-30 20:55:33 -07:00
pashpashpash 80ba1cf173 Update writing-documentation.md 2025-06-30 20:49:59 -07:00
pashpashpash 8cd0561911 Update writing-documentation.md 2025-06-30 20:39:01 -07:00
pashpashpash e1e523a35d Update writing-documentation.md 2025-06-30 20:32:10 -07:00
pashpashpash dd45d2aed5 Update writing-documentation.md 2025-06-30 20:29:41 -07:00
pashpashpash fe4cc95ae9 Update writing-documentation.md 2025-06-30 20:28:06 -07:00
pashpashpash 9fbf94e469 Update writing-documentation.md 2025-06-30 20:25:13 -07:00
pashpashpash af3d05d590 Update writing-documentation.md 2025-06-30 20:17:06 -07:00
pashpashpash 6fdf5c88ac Update writing-documentation.md 2025-06-30 20:16:02 -07:00
pashpashpash ec7311f8d5 Update writing-documentation.md 2025-06-30 20:15:15 -07:00
pashpashpash 61a4e79450 Update writing-documentation.md 2025-06-30 20:14:04 -07:00
pashpashpash 243c94b535 Update writing-documentation.md 2025-06-30 20:13:26 -07:00
pashpashpash ca87b6099b Update writing-documentation.md 2025-06-30 19:24:53 -07:00
pashpashpash de0ddcfb72 Update writing-documentation.md 2025-06-30 19:23:50 -07:00
Cline Evaluation 4d8676e5ec language 2025-06-30 18:53:08 -07:00
Cline Evaluation 3e3590a937 good example 2025-06-30 18:52:49 -07:00
Cline Evaluation 373bfa61f2 good example 2025-06-30 18:51:52 -07:00
pashpashpashandCopilot d52fcc1383 Update .clinerules/workflows/writing-documentation.md
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
2025-06-30 18:35:32 -07:00
Cline Evaluation 86993af2c7 adding documentation workflow 2025-06-30 18:34:15 -07:00
158 changed files with 3510 additions and 3130 deletions
-5
View File
@@ -1,5 +0,0 @@
---
"claude-dev": minor
---
Add support for Gemini 2.5 Pro and Flash to SAP AI Core Provider
+5
View File
@@ -0,0 +1,5 @@
---
"claude-dev": patch
---
Refactor chat view into multiple modular files
+5
View File
@@ -0,0 +1,5 @@
---
"claude-dev": minor
---
Add Claude Sonnet 4 and Opus 4 model in SAP AI Core provider.
-5
View File
@@ -1,5 +0,0 @@
---
"claude-dev": patch
---
Fix logging in with cline not getting past welcome screen
@@ -0,0 +1,392 @@
# General writing guide
# How I want you to write
I'm gonna write something technical.
It's often less about the nitty-gritty details of the tech stuff and more about learning something new or getting a solution handed to me on a silver platter.
Look, when I read, I want something out of it. So when I write, I gotta remember that my readers want something too. This whole piece? It's about cluing in anyone who writes for me, or wants me to write for them, on how I see this whole writing product thing.
I'm gonna lay out a checklist of stuff I'd like to have. It'll make the whole writing gig a bit smoother, you know?
## Crafting Compelling Titles
I often come across titles like "How to do X with Y,Z technology." These don't excite me because X or Y are usually unfamiliar unless they're already well-known. Its rarely the dream to use X unless X is the dream.
My dream isnt to use instructor, its to do something valueble with the data it extracts
An effective title should:
- Evoke an emotional response
- Highlight someone's goal
- Offer a dream or aspiration
- Challenge or comment on a belief
- Address someone's problems
I believe it's more impactful to write about specific problems. If this approach works, you can replicate it across various scenarios rather than staying too general.
- Time management for everyone can be a 15$ ebook
- Time management for executives is a 2000$ workshop
Aim for titles that answer questions you think everyone is asking, or address thoughts people have but can't quite articulate.
Instead of "How I do something" or "How to do something," frame it from the reader's perspective with "How you can do something." This makes the title more engaging. Just make sure the difference is advisory if the content is subjective. “How I made a million dollars” might be more reasonable than “How to make a million dollars” since you are the subject and the goal might be to share your story in hopes of helping others.
This approach ultimately trains the reader to have a stronger emotional connection to your content.
- "How I do X"
- "How You Can do X"
Between these two titles, it's obvious which one resonates more emotionally.
You can take it further by adding specific conditions. For instance, you could target a particular audience or set a timeframe:
- How to set up Braintrust
- How to set up Braintrust in 5 minutes
## NO adjectiives
I want you to almost always avoid adjectives and try to use evidence instead. Instead of saying "production ready," you can write something like "scaling this to 100 servers or 1 million documents per second." Numbers like that will tell you exactly what the specificity of your product is. If you have to use adjectives rather than evidence, you are probably making something up.
There's no reason to say something like "blazingly fast" unless those things are already known phrases.
Instead, say "200 times faster" or "30% faster." A 30% improvement in recommendation system speed is insane.
There's a 200 times performance improvement because we went from one programming language to another. It's just something that's a little bit more expected and understandable.
Another test that I really like using recently is tracking whether or not the statements you make can be:
- Visualized
- Proven false
- Said only by you
If you can nail all three, the claim you make will be more likely to resonate with an audience because only you can say it.
Earlier this year, I had an example where I embedded all of Wikipedia in 17 minutes with 20 bucks, and it got half a million views. All we posted was a video of me kicking off the job, and then you can see all the log lines go through. You see the number of containers go from 1 out of 50 to 50 out of 50.
It was easy to visualize and could have been proven false by being unreproducible. Lastly, Modal is the only company that could do that in such an effortless way, which made it unique.
## Keep It Digestible
- Aim for 5-minute reads
- Write at a Grade 10 reading level
- Break up long paragraphs
- Use headers and bullet points
## Make It Scannable
- Bold key points
- Use subheadings every 3-4 paragraphs
- Include plenty of white space
- Add relevant examples
This structure works whether you're writing a tweet thread or a full blog post. The key is making complex ideas accessible.
# Guide to Writing Cline Documentation
## Some general principles for explaining features
If you're talking about a feature, it's helpful to start with a human-readable explanations that cover what the feature is in simple terms. Skip jargon and explain it like you're talking to someone who's never seen it before. This sets the foundation for everything that follows.
Combine location and usage into one flowing section. Tell users exactly where to find the feature and how to use it, but weave the instructions into natural prose with a good balance of bullet points, numbered lists, code examples (if applicable), mintlify components, and headers/subheaders. Users shouldn't have to jump between separate "where is it" and "how do I use it" sections.
Show the feature in action with real examples like actual files, workflows, or code. Users need to see concrete implementations, not just abstract descriptions. This is where understanding turns into practical knowledge.
When talking about a feature, include an inspiration section that sparks imagination. This section pushes people from understanding to action by showing them what becomes possible when they use this feature creatively. It's what separates good documentation from great documentation.
## Writing Principles That Actually Work
### Write for Action, Not Just Understanding
Documentation should motivate users to try things. Instead of just explaining how something works, focus on what users can accomplish with it. The inspiration section is crucial - it's what transforms passive readers into active users.
### Create a Natural Story Flow
It should feel like a conversation that naturally progresses from "what is this?" to "how do I use it?" to "here's a real example" to "imagine what you could do with this."
### Show Real Examples, Not Toy Demos
Provide actual workflow files, real code snippets, and concrete implementations that users can copy and adapt. Abstract examples don't help anyone - users want to see exactly what they'll be working with.
### Keep It Scannable But Not Fragmented
Write in prose that flows naturally when read completely, but structure it so users can quickly find specific information when they're troubleshooting. Avoid dense walls of text, but also avoid over-formatting with excessive bullet points and bold headers. There should be a nice visual heirarchy of balance between all elements, so you can quickly scan the page and find what you're looking for.
## Language and Tone Guidelines
Write clearly without dumbing things down. Use simple language when possible, but don't avoid technical terms that users need to know. Explain concepts in terms of what users can achieve rather than how the software works internally.
Make your writing conversational and encouraging. Phrases like "you can also try" or "when that works" feel more natural than rigid instructional language. Help users feel confident about trying new things.
Keep content concise and purposeful. Every sentence should either help users understand something or help them do something. If it doesn't serve one of those purposes, cut it.
Build in context and reasoning. Users want to understand why they're doing something, not just what to do. This builds confidence and helps them troubleshoot when things don't work exactly as expected.
## Practical Implementation
Structure each feature page consistently with the four-section approach, but let the content flow naturally within that structure. Use visual assets like videos and screenshots to complement the written content - they often communicate more effectively than paragraphs of description.
Link generously to related resources, examples, and deeper documentation. Users should never feel stuck or wonder where to go next. Maintain a repository of real examples that users can reference and adapt to their own needs.
The goal is documentation that feels more like helpful guidance from an experienced colleague than a technical manual. Users should finish reading feeling excited about what they can accomplish, not just informed about what the feature does.
## Balance Structure with Flexibility
While they discuss having consistent documentation structure, there's also mention of making content feel less rigid and more natural. The writing should follow guidelines while still feeling conversational and engaging.
## Bad examples
I personally hate this pattern of bullet point **Bold Text** colon and then more text:
<bad_example_of_writing>
#### macOS
1. **Switch to bash**: Go to Cline Settings → Terminal → Default Terminal Profile → Select "bash"
2. **Disable Oh-My-Zsh temporarily**: If using zsh, try `mv ~/.zshrc ~/.zshrc.backup` and restart VSCode
3. **Set environment**: Add to your shell config: `export TERM=xterm-256color`
#### Windows
1. **Use PowerShell 7**: Install from Microsoft Store, then select it in Cline settings
2. **Disable Windows ConPTY**: VSCode Settings → Terminal Integrated: Windows Enable Conpty → Uncheck
3. **Try Command Prompt**: Sometimes simpler is better - switch to cmd.exe
#### Linux
1. **Use bash**: Most reliable option - select in Cline settings
2. **Check permissions**: Ensure VSCode has terminal access permissions
3. **Disable custom prompts**: Comment out prompt customizations in `.bashrc`
</bad_example_of_writing>
We should instead strive to write beautiful docs that read well. We can use bullet points and numbered lists but it should read naturally and be delightful to look at hierachally when scanning through the doc. There should be a good balance between blocks of text, code snippets, paragraphs, numbered lists, and bullet points. When scanning the documentation visually, you should feel like you're adminiring a tasteful art piece.
<good_example_of_writing>
#### macOS
The most common fix is switching to bash. Navigate to Cline Settings → Terminal → Default Terminal Profile and select "bash" from the dropdown.
If you're still having issues, Oh-My-Zsh might be interfering with terminal integration. Try temporarily disabling it:
- Run `mv ~/.zshrc ~/.zshrc.backup`
- Restart VSCode
You can also add `export TERM=xterm-256color` to your shell configuration file to improve compatibility.
#### Windows
PowerShell 7 provides the most reliable experience. Install it from the Microsoft Store, then select it in your Cline settings.
Still seeing problems? Try these solutions:
- Disable Windows ConPTY: VSCode Settings → Terminal Integrated: Windows Enable Conpty → uncheck
- Switch to Command Prompt (cmd.exe) - sometimes simpler shells work better
#### Linux
Bash is your most dependable option. Select it in Cline settings if you haven't already.
Check these common issues:
- Ensure VSCode has terminal access permissions
- Temporarily comment out custom prompt configurations in your `.bashrc`
</good_example_of_writing>
This is much more natural to read. Writing this way creates a conversational flow, and bullet points are used idiomatically.
# Using Mintlify Components Idiomatically
Mintlify's custom components can transform basic documentation into engaging, scannable content that users actually want to read. Here's how to use them effectively.
## Visual Content with Frames
Videos and images should be wrapped in `<Frame>` components rather than using raw HTML or markdown. This creates consistent styling and proper responsive behavior.
For videos, embed them directly rather than linking externally. Users are much more likely to watch a 30-second demonstration than click through to another platform:
```jsx
<Frame>
<iframe
style={{ width: "100%", aspectRatio: "16/9" }}
src="https://www.youtube.com/embed/your-video-id"
title="Feature demonstration"
frameBorder="0"
allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share"
allowFullScreen
/>
</Frame>
```
Screenshots work similarly - the frame provides visual polish and consistency:
```jsx
<Frame>
<img src="/path/to/screenshot.png" alt="Descriptive alt text" />
</Frame>
```
## Cards for Navigation and Overview
Cards excel at creating scannable overviews that link to detailed documentation. They're perfect for feature listings, getting started guides, or any section where users need to choose their path.
Use the two-column layout for related features:
```jsx
<Columns cols={2}>
<Card title="Feature Name" icon="relevant-icon" href="/link/to/docs">
Brief description that explains what this feature does and why someone would use it.
</Card>
<Card title="Related Feature" icon="another-icon" href="/another/link">
Another concise explanation that helps users understand the value proposition.
</Card>
</Columns>
```
The key is writing card descriptions that are informative enough to help users decide whether to click through, but concise enough to scan quickly. Each card should answer "what does this do?" and "why would I need this?"
## Tips and Notes for Context
Use `<Tip>` components for helpful information that enhances the main content without cluttering it:
```jsx
<Tip>
Pro tip: You can combine multiple @ mentions in a single message to give Cline
comprehensive context about your issue.
</Tip>
```
`<Note>` components work well for important caveats or technical limitations:
```jsx
<Note>
Due to VS Code limitations, some features require specific settings to work properly.
</Note>
```
`<Info>` is also cool:
<Info>
**Quick Fix**: If you're experiencing terminal issues, try switching to a simpler shell like `bash` in the Cline settings.
This resolves 90% of terminal integration problems.
</Info>
**Never** fall into that awful **Bold Text** - description pattern that we specifically identified as bad writing. The content should flow naturally as connected thoughts rather than feeling like a templated AI response with forced formatting.
## When to Use Bullet Points and Numbered Lists Strategically
Bullet points serve functional purposes - use them for:
**Sequential actions or troubleshooting steps** where users need to follow a specific order:
1. Install the extension
2. Restart VSCode
3. Check the settings panel
**Lists of related options** where users need to choose one approach:
- Try PowerShell 7 for the most reliable experience
- Switch to Command Prompt if you're still having issues
- Use WSL Bash for Linux compatibility
**Quick reference items** that users might need to scan quickly when problem-solving.
**Improving Visual Hierarchy** when there's a wall of text - that's a good time to introduce bullet points or numbered lists.
Each bulleted item or numbered list should be a discrete action or piece of information that benefits from being visually separated. This is a key weapon you can employ when going for that artwork experience I mentioned earlier.
<good_example_of_bullet_points>
## Finding and Configuring Terminal Settings
You can access Cline's terminal settings by clicking the settings icon in the Cline sidebar, then navigating to the Terminal section. These settings control how Cline interacts with your system's terminal.
- The **Default Terminal Profile** setting determines which shell Cline uses for executing commands. If you're experiencing issues, this is usually the first thing to change. I personally keep this set to `bash` on all my systems because it's the most reliable option, even though I use `zsh` for my regular terminal work.
- **Shell Integration Timeout** controls how long Cline waits for the terminal to become ready. The default is 4 seconds, but if you have a heavy shell configuration (lots of plugins, slow startup scripts), you might need to increase this to 10 or even 15 seconds. I've found that WSL environments and SSH connections often need longer timeouts.
- The **Enable Aggressive Terminal Reuse** setting determines whether Cline tries to reuse existing terminals even when they're not in the correct directory. When this causes problems (commands running in the wrong directory, virtual environment issues), disabling it creates more terminal instances but ensures each command runs in a clean state.
- **Terminal Output Line Limit** sets how many lines of output Cline will read from commands. The default of 500 lines works for most cases, but you might need to adjust it. For verbose build outputs, increase it. For commands with progress bars that spam thousands of lines, decrease it to around 100 to avoid consuming too many tokens.
</good_example_of_bullet_points>
## Write Like a Human, Not an AI
Keep it short and direct. If you can say something in fewer words, do it. Long explanations often confuse more than they help.
Use normal sentence lengths. Mix short and long sentences naturally, like you would when talking to someone. Avoid those meandering compound sentences that go on forever.
Cut the corporate speak. Instead of "utilize," say "use." Instead of "in order to," just say "to." Write like you're explaining something to a colleague, not drafting a press release.
Don't over-explain obvious things. If users are reading documentation, they probably understand basic concepts. Respect their intelligence.
## Never use em dashes or emojis
That's pretty much it. Never use them. Only AI writes with em dashes or emojis.
# Anthropomorphizing Cline
When referring to Cline, always call him a "him" not an "it".
Bad example:
- When Cline cant execute commands or read their output, you lose access to one of its most powerful capabilities.
Good Example:
- When Cline cant execute commands or read their output, you lose access to one of his most powerful capabilities.
# Using "I" when sharing your workflow
Adding a personal touch goes a long way. There are great examples in the docs currently where I use "I" to share how I personally use cline, from dev to dev. It's a great technique.
# Crosslinking relevant documentation pages
Make sure you crosslink when you're done writing the docs. If there are relevant docs, just link to them.
# Brevity is the soul of wit
Don't ramble if you don't need to. Use bullet points and numbered lists. Keep things easy to read.
<bad_example>
When Cline can't execute commands or read their output, you lose access to one of his most powerful capabilities. Terminal integration problems are frustrating, but they're usually fixable with a few simple changes.
## The Most Common Problem: Shell Integration Issues
If you're seeing "Shell integration unavailable" or Cline isn't getting command output, the issue is almost always your shell configuration. Complex shell setups with custom prompts, plugins, and fancy configurations can interfere with VSCode's terminal integration.
**Switch to bash first.** This fixes the problem 90% of the time. Navigate to Cline Settings → Terminal → Default Terminal Profile and select "bash" from the dropdown. Restart VSCode after making this change.
Still having issues? Try increasing the shell integration timeout. Go to Cline Settings → Terminal → Shell Integration Timeout and change it from 4 seconds to 10 seconds. Heavy shell configurations need more time to initialize properly.
If commands are running in the wrong directories or you're seeing weird behavior, disable aggressive terminal reuse. In Cline Settings → Terminal, uncheck "Enable aggressive terminal reuse." This creates more terminal instances but ensures each command runs in a clean environment.
</bad_exaxmple>
The first part is total filler, useless to any serious developer. You can tell it's written by a non technical person that doesn't value clean, straightforward information.
<good_example>
## Shell Integration Issues
If you're seeing "Shell integration unavailable" or Cline can't read command output, your shell configuration is interfering with VSCode's terminal integration.
**Switch to bash first.** Go to Cline Settings → Terminal → Default Terminal Profile and select "bash." This fixes 90% of problems.
Still broken? Try these:
- Increase shell integration timeout to 10 seconds in Cline Settings → Terminal
- Disable "aggressive terminal reuse" if commands run in wrong directories
- Restart VSCode after making changes
</good_example>
The good version cuts straight to the problem and solution. No hand-holding, no emotional language about frustration, just the facts: what's wrong, how to fix it, what to try next. Respects that developers want information, not sympathy.RetryClaude can make mistakes. Please double-check responses.
ALWAYS consider your audience. And your audience is devs who don't want their time wasted. Give them the info. I cannot stress this enough. Use bullet points and numbered lists. Prose is good, but every word should actually mean something to the dev reading it.
# Lastly, before you start writing docs
1. Internalize these guidelines. I mean it.
2. Read `docs/docs.json` and get an understanding of the structure of the docs. This will come in handly at the end when you're doing a final pass so you can cross link to docs where relevant.
3. Read some good examples that I personally wrote and am proud of:
- docs/features/slash-commands/workflows.mdx
- docs/features/slash-commands/new-task.mdx
- docs/features/at-mentions/overview.mdx
- docs/features/drag-and-drop.mdx
4. If the user specifies any other instructions make sure you follow them.
+1 -2
View File
@@ -7,7 +7,6 @@ tmp
*.vsix
.DS_Store
.idea
pnpm-lock.yaml
@@ -38,4 +37,4 @@ src/hosts/vscode/*/methods.ts
src/hosts/vscode/*/index.ts
src/hosts/vscode/client/host-grpc-client.ts
src/hosts/vscode/host-grpc-service-config.ts
src/standalone/server-setup.ts
src/standalone/server-setup.ts
-14
View File
@@ -1,19 +1,5 @@
# Changelog
## [3.18.3]
- Improve Cerebras Qwen model performance by removing thinking tokens from model input (Thanks @kevint-cerebras!)
- Improve Claude Code provider with better error handling and performance optimizations (Thanks @BarreiroT!)
## [3.18.2]
- Fix issue where terminal output would not be captured if shell integration fails by falling back to capturing the terminal content.
- Add confirmation popup when deleting tasks
- Add support for Claude Sonnet 4 and Opus 4 model in SAP AI Core provider (Thanks @lizzzcai!)
- Add support for `litellm_session_id` to group requests in a single session (Thanks @jorgegarciarey!)
- Add "Thinking Budget" customization for Claude Code (Thanks @BarreiroT!)
- Fix issue where the extension would use the user's environment variables for authentication when using Claude Code (Thanks @BarreiroT!)
## [3.18.1]
- Add support for Claude 4 Sonnet in SAP AI Core provider (Thanks @GTxx!)
-4
View File
@@ -170,10 +170,6 @@
"running-models-locally/ollama"
]
},
{
"group": "Troubleshooting",
"pages": ["troubleshooting/terminal-quick-fixes", "troubleshooting/terminal-integration-guide"]
},
{
"group": "More Info",
"pages": ["more-info/telemetry"]
@@ -58,16 +58,3 @@ When you use the terminal mention in your message, here's what happens behind th
6. The AI can now "see" the complete terminal output with all formatting preserved
This process happens automatically whenever you use the terminal mention, giving the AI access to your command results, error messages, and other terminal output without you having to copy it manually.
## Troubleshooting Terminal Issues
If you're experiencing issues with terminal mentions or terminal integration in general (such as "Shell Integration Unavailable" or commands not showing output), please refer to our comprehensive [Terminal Integration Troubleshooting Guide](/troubleshooting/terminal-integration-guide).
Common issues include:
- Terminal mentions not capturing output
- "Shell Integration Unavailable" messages in Cline chat
- Commands executing but output not visible to Cline
- Terminal integration working inconsistently
The troubleshooting guide provides platform-specific solutions and detailed configuration steps to resolve these issues.
@@ -74,25 +74,8 @@ This approach ensures that all terminal output, including colors and formatting,
- **Select specific output when needed**: By default, the integration captures all terminal content, but you can also select specific lines before right-clicking to focus on just the relevant output.
- **Combine terminal outputs with file mentions**: After sending terminal output to Cline, you can enhance your question by mentioning relevant files using the @ mentions feature.
- **Combine with file mentions**: After sending terminal output to Cline, you can enhance your question by mentioning relevant files using the @ mentions feature.
- **Contextualize build & test outputs with the terminal**: Terminal integration is particularly useful for understanding complex build errors or test failures that span multiple lines.
- **Use for build and test output**: Terminal integration is particularly useful for understanding complex build errors or test failures that span multiple lines.
Next time you're staring at a cryptic error message in your terminal, try using Cline's terminal integration instead of copying and pasting. You'll get more accurate help because Cline can see the complete terminal context with proper formatting.
## Troubleshooting Terminal Issues
If you're experiencing issues with terminal integration, such as "Shell Integration Unavailable" or commands not showing output, please refer to our comprehensive [Terminal Integration Troubleshooting Guide](/troubleshooting/terminal-integration-guide).
The troubleshooting guide covers:
- Common terminal integration issues and quick fixes
- Platform-specific solutions for Windows, macOS, and Linux
- Shell-specific configurations for zsh, bash, PowerShell, and more
- Advanced debugging techniques
- Terminal settings optimization
<Tip>
**Quick Fix**: Most terminal issues can be resolved by switching to bash in the Cline settings and increasing the shell
integration timeout to 10 seconds.
</Tip>
@@ -1,399 +0,0 @@
---
title: "Terminal Integration Troubleshooting Guide"
sidebarTitle: "Terminal Troubleshooting"
description: "Complete guide to resolving terminal integration issues in Cline"
---
This guide helps you resolve terminal integration issues in Cline. Terminal integration is crucial for Cline to execute commands and read their output, enabling it to understand errors, test results, and command responses.
<Tip>
If you're experiencing terminal issues, try switching to a simpler shell like `bash` in the Cline settings, under "Terminal Settings"
This resolves most terminal integration problems.
</Tip>
## Quick Diagnosis Flowchart
Follow this flowchart to quickly identify your issue:
```mermaid
graph TD
A[Terminal Issue] --> B{Can Cline execute commands?}
B -->|No| C[Shell Integration Unavailable]
B -->|Yes| D{Can Cline see the output?}
D -->|No| E[Output Capture Failed]
D -->|Yes| F{Is the output corrupted?}
F -->|Yes| G[Character Filtering Issue]
F -->|No| H{Does the command hang?}
H -->|Yes| I[Long-Running Command Issue]
H -->|No| J[Check Terminal Settings]
C --> K[Try Solution 1]
E --> L[Try Solution 2]
G --> M[Try Solution 3]
I --> N[Try Solution 4]
style A fill:#f9f,stroke:#333,stroke-width:2px
style K fill:#9f9,stroke:#333,stroke-width:2px
style L fill:#9f9,stroke:#333,stroke-width:2px
style M fill:#9f9,stroke:#333,stroke-width:2px
style N fill:#9f9,stroke:#333,stroke-width:2px
```
## Common Issues & Quick Solutions
### 1. Shell Integration Unavailable
**Symptoms:**
- Message: "Shell Integration Unavailable"
- Commands execute but Cline can't read output
- Terminal works fine manually but not with Cline
**Quick Solutions:**
#### macOS
- **Switch to bash**
1. Go to Cline Settings
2. Left-Click the **"Terminal Settings"** tab
3. Navigate to **"Default Terminal Profile"** and select **"bash"** from the drop-down menu
- **Disable Oh-My-Zsh temporarily**:
1. If using zsh, enter `mv ~/.zshrc ~/.zshrc.backup` into the terminal
2. Restart VSCode
- **Set environment**:
1.a For Zsh users, use one of the following Zsh commands to edit your shell profile:
- `nano ~/.zshrc`
- `vim ~/.zshrc`
- `code ~/.zshrc`
1.b For Bash users
- nano ~/.bash_profile
2. Add the following to your shell config: `export TERM=xterm-256color`
3. Save your configuration
#### Windows
- **Use PowerShell 7**
1. Install from Microsoft Store
2. Go to Cline Settings
3. Left-Click the **"Terminal Settings"** tab
4. Navigate to **"Default Terminal Profile"** and select **"PowerShell 7"** from the drop-down menu
- **Disable Windows ConPTY**
1. Navigate to your VSCode Settings
2. Enter "Integrated: Windows Enable Conpty" into the Settings searchbar
3. Uncheck the option
- **Try Command Prompt**
1. Go to Cline Settings
2. Left-Click the **"Terminal Settings"** tab
3. Navigate to **"Default Terminal Profile"** and select **"Command Prompt"** from the drop-down menu
#### Linux
- **Use bash**
1. Go to Cline Settings
2. Left-Click the **"Terminal Settings"** tab
3. Navigate to **"Default Terminal Profile"** and select **"bash"** from the drop-down menu
- **Check permissions**
1. Ensure VSCode has terminal access permissions
- **Disable custom prompts**
1. Comment out prompt customizations in `.bashrc`
### 2. Command Output Not Visible
**Symptoms:**
- Cline states in chat: "[Command is running but producing no output]"
- Commands complete but Cline doesn't see results
- Commands work sometimes but not consistently
**Solutions:**
- **Increase Shell Integration Timeout**
1. Within Cline, left-click the **Settings** button in the top right-hand corner of the chat window
2. Once in the **Settings** window, left-click the **"Terminal Settings"** tab from the left-hand column
3. Navigate to "Shell integration timeout (seconds)" and enter **"10"** into the text field
- **Disable Terminal Reuse**
1. Within Cline, left-click the **Settings** button in the top right-hand corner of the chat window
2. Once in the **Settings** window, left-click the **"Terminal Settings"** tab from the left-hand column
3. Look for **"Enable aggressive terminal reuse"**, and **uncheck** this option
- **Check for interfering extensions**
1. Disable other terminal-related VSCode extensions
### 3. Character Filtering Issues
**Symptoms:**
- Commas missing from output (JSON appears corrupted)
- Special characters stripped from terminal output
- Syntax errors that don't appear when running manually
**Solution:**
This is a known bug in output processing. Workarounds:
- Recommend AI to use file output instead
1. Tell Cline in chat or Cline rules, to use `command > output.txt` before reading the file/s
<Tip>
This family of issues is only partially solved in the latest Cline versions, so if you still face this, create a GitHub issue
if it is a persistent problem.
</Tip>
### 4. Long-Running Commands & Progress Bars
**Symptoms:**
- Docker builds never complete in Cline
- Progress bars consume thousands of tokens
- The Cline button "Proceed while running" doesn't work properly in chat
<Tip>
This family of issues has been solved in latest Cline versions but if you still face any issues, then create a GitHub issue
for this.
</Tip>
## Terminal Settings Explained
Access these in Cline by clicking the settings icon, and navigating to the "Terminal Settings" section:
### Default Terminal Profile
- **What it does**: Selects which shell Cline uses for commands
- **When to change**: If experiencing shell integration issues with your default shell
- **Recommended**: - macOS: bash (if zsh has issues) - Windows: PowerShell 7 - Linux: bash
### Shell Integration Timeout
- **What it does**: How long Cline waits for the terminal to be ready
- **Default**: 4 seconds
- **When to increase**:
- Slow shell startup (heavy .zshrc/.bashrc)
- WSL environments
- SSH connections
- **Recommended**: - Start with 10 seconds if having issues
### Enable Aggressive Terminal Reuse
- **What it does**: Reuses existing terminals even if not in the correct directory
- **When to disable**:
- Commands execute in wrong directory
- Virtual environment issues
- Terminal state corruption
- **Trade-off**: - Disabling creates more terminals but ensures clean state
### Terminal Output Line Limit
- **What it does**: Limits how many lines Cline reads from terminal output
- **Default**: 500 lines
- **When to adjust**:
- Increase for verbose build outputs
- Decrease if hitting token limits
- Set to 100 for commands with progress bars
## Platform-Specific Solutions
### macOS Issues
#### Oh-My-Zsh Conflicts
Oh-My-Zsh often interferes with shell integration. Solutions:
1. Create a minimal `.zshrc` for VSCode:
```bash
# ~/.zshrc-vscode
export TERM=xterm-256color
export PAGER=cat
# Minimal PATH and environment setup
```
2. Configure VSCode to use it:
```json
{
"terminal.integrated.env.osx": {
"ZDOTDIR": "~/.zshrc-vscode"
}
}
```
#### macOS 15+ Issues
Recent macOS versions have stricter terminal permissions:
1. System Preferences → Privacy & Security → Developer Tools
2. Add Visual Studio Code
3. Restart VSCode completely
### Windows Issues
#### PowerShell Execution Policy
If commands fail silently:
```powershell
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser
```
#### WSL Integration
For WSL issues:
1. Use WSL extension for VSCode
2. Open folder in WSL: `code .` from WSL terminal
3. Select "WSL Bash" as terminal profile in Cline
#### Path Issues
Windows path problems:
1. Use forward slashes in Cline: `C:/Users/...`
2. Quote paths with spaces: `"C:/Program Files/..."`
3. Avoid `~` - use full paths
### Linux/SSH/Container Issues
#### SSH Connections
For remote development:
1. Install Cline on the remote machine, not locally
2. Use SSH extension's integrated terminal
3. Increase timeout to 15+ seconds
#### Docker Containers
When developing in containers:
1. Install Cline in the container
2. Use Dev Containers extension
3. Ensure shell integration scripts are available
## Shell-Specific Fixes
### Zsh
```bash
# Add to ~/.zshrc
export TERM=xterm-256color
export PAGER=cat
# Disable fancy prompts for VSCode
if [[ "$TERM_PROGRAM" == "vscode" ]]; then
PS1="%n@%m %1~ %# "
fi
```
### Bash
```bash
# Add to ~/.bashrc
export TERM=xterm-256color
export PAGER=cat
# Simple prompt for VSCode
if [[ "$TERM_PROGRAM" == "vscode" ]]; then
PS1='\u@\h:\w\$ '
fi
```
### Fish
```fish
# Add to ~/.config/fish/config.fish
set -x TERM xterm-256color
set -x PAGER cat
# Disable fancy features in VSCode
if test "$TERM_PROGRAM" = "vscode"
function fish_prompt
echo (whoami)'@'(hostname)':'(pwd)'> '
end
end
```
### PowerShell
```powershell
# Add to $PROFILE
$env:PAGER = "cat"
# Disable progress bars
$ProgressPreference = 'SilentlyContinue'
```
## Advanced Troubleshooting
### Debug Mode
Enable terminal debugging to see what's happening:
1. Open VSCode Command Palette (Cmd/Ctrl+Shift+P)
2. Run: "Developer: Set Log Level..."
3. Choose "Trace"
4. Check Output panel → "Cline" for terminal logs
### Manual Shell Integration Test
Test if shell integration works at all:
```bash
# In VSCode terminal
echo $TERM_PROGRAM # Should show "vscode"
echo $VSCODE_SHELL_INTEGRATION # Should be "1"
```
## FAQ
### Why does Cline create so many terminals?
When shell integration fails, Cline can't reuse terminals safely (they might be running long processes). Enable shell integration or adjust the terminal reuse setting.
### Can I use my custom shell (nushell, xonsh, etc.)?
Cline officially supports bash, zsh, fish, and PowerShell. Custom shells may work but aren't guaranteed. Use bash as a fallback.
### Why do some commands work but others don't?
Commands that use interactive features (pagers, progress bars, curses) often fail. Set `PAGER=cat` and use non-interactive flags.
### How do I know if shell integration is working?
Working integration shows command output in Cline's chat. Failed integration shows "Shell Integration Unavailable" or "[Command is running but producing no output]".
## Still Having Issues?
If you've tried everything:
1. **Collect Debug Info**:
```bash
echo "Shell: $SHELL"
echo "Term: $TERM"
echo "VSCode: $TERM_PROGRAM"
which bash
bash --version
```
2. **Report the Issue**:
- Use `/reportbug` in Cline github issues
- Include your debug info
- Mention which solutions you tried
<Tip>
Remember: Most terminal issues are resolved by switching to bash and increasing the timeout. Start there before trying complex
solutions.
</Tip>
@@ -1,51 +0,0 @@
---
title: "Terminal Quick Fixes"
sidebarTitle: "Terminal Quick Fixes"
description: "Quick solutions for common terminal issues"
---
**Here is a list of common fixes, starting with the most applicable:**
- **Switch to bash** (solves most instances)
1. Within Cline, left-click the **Settings** button in the top right-hand corner of the chat window
2. Once in the **Settings** window, left-click the **"Terminal Settings"** tab from the left-hand column
3. Navigate to **"Default Terminal Profile"** and select **"bash"** from the drop-down
- **Increase timeout**
1. Within Cline, left-click the **Settings** button in the top right-hand corner of the chat window
2. Once in the **Settings** window, left-click the **"Terminal Settings"** tab from the left-hand column
3. Navigate to "Shell integration timeout (seconds)" and enter **"10"** into the text field
- **Disable terminal reuse**
1. Within Cline, left-click the **Settings** button in the top right-hand corner of the chat window
2. Once in the **Settings** window, left-click the **"Terminal Settings"** tab from the left-hand column
3. Look for **"Enable aggressive terminal reuse"**, and **uncheck** this option
## Platform-Specific Fixes
### macOS + Oh-My-Zsh
```bash
# Create minimal config for VSCode
echo 'export TERM=xterm-256color' > ~/.zshrc-vscode
echo 'export PAGER=cat' >> ~/.zshrc-vscode
```
### Windows PowerShell
```powershell
# Run as Administrator
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser
```
### WSL
- Open folder from WSL: `code .`
- Select **"WSL Bash"** in Cline settings, under **"Terminal Settings"**
- Increase **"Shell integration timeout (seconds)"** to **15**
## Full Guide
For detailed troubleshooting, see the [Complete Terminal Troubleshooting Guide](/troubleshooting/terminal-integration-guide).
-5
View File
@@ -6,7 +6,6 @@ interface RunDiffEvalOptions {
modelIds: string
systemPromptName: string
validAttemptsPerCase: number
maxAttemptsPerCase?: number
parsingFunction: string
diffEditFunction: string
thinkingBudget: number
@@ -72,10 +71,6 @@ export async function runDiffEvalHandler(options: RunDiffEvalOptions) {
args.push("--verbose")
}
if (options.maxAttemptsPerCase) {
args.push("--max-attempts-per-case", String(options.maxAttemptsPerCase))
}
if (options.maxCases) {
args.push("--max-cases", String(options.maxCases))
}
-2
View File
@@ -87,7 +87,6 @@ program
.option("--model-ids <model_ids>", "Comma-separated list of model IDs to test")
.option("--system-prompt-name <name>", "The name of the system prompt to use", "basicSystemPrompt")
.option("-n, --valid-attempts-per-case <number>", "Number of valid attempts per test case per model (will retry until this many valid attempts are collected)", "1")
.option("--max-attempts-per-case <number>", "Maximum total attempts per test case (default: 10x valid attempts)")
.option("--max-cases <number>", "Maximum number of test cases to run (limits total cases loaded)")
.option("--parsing-function <name>", "The parsing function to use", "parseAssistantMessageV2")
.option("--diff-edit-function <name>", "The diff editing function to use", "constructNewFileContentV2")
@@ -103,7 +102,6 @@ program
const fullOptions = {
...options,
validAttemptsPerCase: parseInt(options.validAttemptsPerCase, 10),
maxAttemptsPerCase: options.maxAttemptsPerCase ? parseInt(options.maxAttemptsPerCase, 10) : undefined,
thinkingBudget: parseInt(options.thinkingBudget, 10),
maxCases: options.maxCases ? parseInt(options.maxCases, 10) : undefined,
}
+11 -12
View File
@@ -30,7 +30,6 @@ const diffEditingFunctions: Record<string, ConstructNewFileContentFn> = {
}
import { TestInput, TestResult, ExtractedToolCall } from "./types"
import { log } from "./helpers"
export { TestInput, TestResult, ExtractedToolCall }
interface StreamResult {
@@ -285,21 +284,21 @@ export async function runSingleEvaluation(input: TestInput): Promise<TestResult>
}
// check that we are editing the correct file path
log(input.isVerbose, `Expected file path: "${originalFilePath}"`)
log(input.isVerbose, `Actual file path used: "${diffToolPath}"`)
console.log(`Expected file path: "${originalFilePath}"`);
console.log(`Actual file path used: "${diffToolPath}"`);
if (diffToolPath !== originalFilePath) {
log(input.isVerbose, `❌ File path mismatch detected!`)
console.log(`❌ File path mismatch detected!`);
// Enhanced logging:
if (streamResult?.assistantMessage) {
log(input.isVerbose, ` Full model output (assistantMessage):`)
log(input.isVerbose, ` -----------------------------------------`)
log(input.isVerbose, ` ${streamResult.assistantMessage}`)
log(input.isVerbose, ` -----------------------------------------`)
console.log(` Full model output (assistantMessage):`);
console.log(` -----------------------------------------`);
console.log(` ${streamResult.assistantMessage}`);
console.log(` -----------------------------------------`);
}
if (toolCall) {
log(input.isVerbose, ` Parsed tool call that caused mismatch:`)
log(input.isVerbose, ` ${JSON.stringify(toolCall, null, 2)}`)
log(input.isVerbose, ` -----------------------------------------`)
console.log(` Parsed tool call that caused mismatch:`);
console.log(` ${JSON.stringify(toolCall, null, 2)}`);
console.log(` -----------------------------------------`);
}
return {
success: false,
@@ -322,7 +321,7 @@ export async function runSingleEvaluation(input: TestInput): Promise<TestResult>
// If it's just a string, diffSuccess stays true and replacementData stays undefined
} catch (error: any) {
diffSuccess = false
log(input.isVerbose, `ERROR: ${error}`)
console.log("ERROR:",error)
}
return {
+10 -12
View File
@@ -7,7 +7,7 @@ import { constructNewFileContent as constructNewFileContent_06_26_25 } from "./d
import { constructNewFileContent as constructNewFileContentV3 } from "../../src/core/assistant-message/diff"
import { basicSystemPrompt } from "./prompts/basicSystemPrompt-06-06-25"
import { claude4SystemPrompt } from "./prompts/claude4SystemPrompt-06-06-25"
import { formatResponse, log } from "./helpers"
import { formatResponse } from "./helpers"
import { Anthropic } from "@anthropic-ai/sdk"
import * as fs from "fs"
import * as path from "path"
@@ -40,6 +40,12 @@ const encoding = get_encoding("cl100k_base");
let openRouterModelDataGlobal: Record<string, EvalOpenRouterModelInfo> = {}; // Global to store fetched data
function log(isVerbose: boolean, message: string) {
if (isVerbose) {
console.log(message)
}
}
const systemPromptGeneratorLookup: Record<string, ConstructSystemPromptFn> = {
basicSystemPrompt: basicSystemPrompt,
claude4SystemPrompt: claude4SystemPrompt,
@@ -635,7 +641,6 @@ class NodeTestRunner {
thinkingBudgetTokens: testConfig.thinking_tokens_budget,
originalDiffEditToolCallMessage: testConfig.replay ? testCase.original_diff_edit_tool_call_message : undefined,
diffApplyFile: testConfig.diff_apply_file,
isVerbose: isVerbose,
}
if (isVerbose) {
@@ -802,8 +807,8 @@ class NodeTestRunner {
log(isVerbose, `Warning: Failed to store result in database: ${error}`);
}
// Safety check to prevent infinite loops - use configurable max attempts limit
if (totalAttempts >= testConfig.max_attempts_per_case) {
// Safety check to prevent infinite loops - limit to 10 attempts per valid attempt requested
if (totalAttempts >= testConfig.number_of_runs * 10) {
log(isVerbose, ` ⚠️ Reached maximum attempts (${totalAttempts}) for test case ${testCase.test_id}. Only got ${validAttempts}/${testConfig.number_of_runs} valid attempts.`);
break;
}
@@ -922,7 +927,6 @@ async function main() {
.option("--model-ids <model_ids>", "Comma-separated list of model IDs to test")
.option("--system-prompt-name <name>", "The name of the system prompt to use", "basicSystemPrompt")
.option("-n, --valid-attempts-per-case <number>", "Number of valid attempts per test case per model (will retry until this many valid attempts are collected)", "1")
.option("--max-attempts-per-case <number>", "Maximum total attempts per test case (default: 10x valid attempts)")
.option("--max-cases <number>", "Maximum number of test cases to run (limits total cases loaded)")
.option("--parsing-function <name>", "The parsing function to use", "parseAssistantMessageV2")
.option("--diff-edit-function <name>", "The diff editing function to use", "diff-06-25-25")
@@ -953,11 +957,6 @@ async function main() {
}
const validAttemptsPerCase = parseInt(options.validAttemptsPerCase, 10);
// Compute dynamic default for max attempts: 10x valid attempts if not specified
const maxAttemptsPerCase = options.maxAttemptsPerCase
? parseInt(options.maxAttemptsPerCase, 10)
: validAttemptsPerCase * 10;
const runner = new NodeTestRunner(options.replay || !!options.replayRunId)
@@ -1063,7 +1062,6 @@ async function main() {
model_id: modelId,
system_prompt_name: options.systemPromptName,
number_of_runs: validAttemptsPerCase,
max_attempts_per_case: maxAttemptsPerCase,
parsing_function: options.parsingFunction,
diff_edit_function: options.diffEditFunction,
thinking_tokens_budget: parseInt(options.thinkingBudget, 10),
@@ -1131,7 +1129,7 @@ async function main() {
remainingTasks = remainingTasks.filter(task => {
const taskId = `${task.modelId}-${task.testCase.test_id}`;
if (taskStates[taskId].total >= task.testConfig.max_attempts_per_case) {
if (taskStates[taskId].total >= validAttemptsPerCase * 10) {
log(isVerbose, ` ⚠️ Reached maximum attempts for ${task.testCase.test_id} with ${task.modelId}.`);
return false;
}
@@ -492,12 +492,6 @@ async function constructNewFileContentV1(diffContent: string, originalContent: s
if (isReplaceBlockEnd(line)) {
// Finished one replace block
if (searchMatchIndex === -1) {
throw new Error(
`The SEARCH block:\n${currentSearchContent.trimEnd()}\n...is malformatted.`,
)
}
// Store this replacement
replacements.push({
start: searchMatchIndex,
-6
View File
@@ -23,9 +23,3 @@ export const formatResponse = {
return formatImagesIntoBlocks(images)
},
}
export function log(isVerbose: boolean, message: string) {
if (isVerbose) {
console.log(message)
}
}
-2
View File
@@ -29,7 +29,6 @@ export interface TestConfig {
model_id: string
system_prompt_name: string
number_of_runs: number
max_attempts_per_case: number
parsing_function: string
diff_edit_function: string
thinking_tokens_budget: number
@@ -104,5 +103,4 @@ export interface TestInput {
thinkingBudgetTokens: number
originalDiffEditToolCallMessage?: string
diffApplyFile?: string
isVerbose: boolean
}
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "claude-dev",
"version": "3.18.3",
"version": "3.18.1",
"lockfileVersion": 2,
"requires": true,
"packages": {
"": {
"name": "claude-dev",
"version": "3.18.3",
"version": "3.18.1",
"license": "Apache-2.0",
"dependencies": {
"@anthropic-ai/sdk": "^0.37.0",
+1 -1
View File
@@ -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.18.3",
"version": "3.18.1",
"icon": "assets/icons/icon.png",
"engines": {
"vscode": "^1.84.0"
-1
View File
@@ -26,6 +26,5 @@ export const hostServiceNameMap = {
watch: "host.WatchService",
workspace: "host.WorkspaceService",
env: "host.EnvService",
window: "host.WindowService",
// Add new host services here
}
-48
View File
@@ -1,48 +0,0 @@
syntax = "proto3";
package host;
option java_package = "bot.cline.host.proto";
option java_multiple_files = true;
import "common.proto";
// Provides methods for working with IDE windows and editors.
service WindowService {
// Opens a text document in the editor and returns editor information.
rpc showTextDocument(ShowTextDocumentRequest) returns (TextEditorInfo);
rpc showOpenDialogue(ShowOpenDialogueRequest) returns (SelectedResources);
}
message ShowTextDocumentRequest {
cline.Metadata metadata = 1;
string path = 2;
optional ShowTextDocumentOptions options = 3;
}
// See https://code.visualstudio.com/api/references/vscode-api#TextDocumentShowOptions
message ShowTextDocumentOptions {
optional bool preview = 1;
optional bool preserve_focus = 2;
optional int32 view_column = 3;
}
message TextEditorInfo {
string document_path = 1;
optional int32 view_column = 2;
bool is_active = 3;
}
message ShowOpenDialogueRequest {
cline.Metadata metadata = 1;
optional bool can_select_many = 2;
optional string open_label = 3;
optional ShowOpenDialogueFilterOption filters = 4;
}
message ShowOpenDialogueFilterOption {
repeated string files = 1;
}
message SelectedResources {
repeated string paths = 1;
}
-1
View File
@@ -18,7 +18,6 @@ service StateService {
rpc updateAutoApprovalSettings(AutoApprovalSettingsRequest) returns (Empty);
rpc updateSettings(UpdateSettingsRequest) returns (Empty);
rpc updateTelemetrySetting(TelemetrySettingRequest) returns (Empty);
rpc setWelcomeViewCompleted(BooleanRequest) returns (Empty);
}
message State {
+3 -6
View File
@@ -45,10 +45,8 @@ describe("OllamaHandler", () => {
this.skip()
}
this.timeout(5000)
// Ensure client is initialized
const client = (handler as any).ensureClient()
// Mock the Ollama client's chat method
const chatStub = sinon.stub(client, "chat").resolves({
const chatStub = sinon.stub(handler["client"], "chat").resolves({
[Symbol.asyncIterator]: async function* () {
yield {
message: { content: "Hello, world!" },
@@ -141,9 +139,8 @@ describe("OllamaHandler", () => {
// Restore real timers for this test
clock.restore()
// Ensure client is initialized and mock the Ollama client's chat method to fail on first call and succeed on second
const client = (handler as any).ensureClient()
const chatStub = sinon.stub(client, "chat")
// Mock the Ollama client's chat method to fail on first call and succeed on second
const chatStub = sinon.stub(handler["client"], "chat")
// First call throws an error
chatStub.onFirstCall().rejects(new Error("API Error"))
+7 -22
View File
@@ -7,33 +7,18 @@ import { ApiStream } from "../transform/stream"
export class AnthropicHandler implements ApiHandler {
private options: ApiHandlerOptions
private client: Anthropic | undefined
private client: Anthropic
constructor(options: ApiHandlerOptions) {
this.options = options
}
private ensureClient(): Anthropic {
if (!this.client) {
if (!this.options.apiKey) {
throw new Error("Anthropic API key is required")
}
try {
this.client = new Anthropic({
apiKey: this.options.apiKey,
baseURL: this.options.anthropicBaseUrl || undefined,
})
} catch (error) {
throw new Error(`Error creating Anthropic client: ${error.message}`)
}
}
return this.client
this.client = new Anthropic({
apiKey: this.options.apiKey,
baseURL: this.options.anthropicBaseUrl || undefined,
})
}
@withRetry()
async *createMessage(systemPrompt: string, messages: Anthropic.Messages.MessageParam[]): ApiStream {
const client = this.ensureClient()
const model = this.getModel()
let stream: AnthropicStream<Anthropic.RawMessageStreamEvent>
const modelId = model.id
@@ -59,7 +44,7 @@ export class AnthropicHandler implements ApiHandler {
)
const lastUserMsgIndex = userMsgIndices[userMsgIndices.length - 1] ?? -1
const secondLastMsgUserIndex = userMsgIndices[userMsgIndices.length - 2] ?? -1
stream = await client.messages.create(
stream = await this.client.messages.create(
{
model: modelId,
thinking: reasoningOn ? { type: "enabled", budget_tokens: budget_tokens } : undefined,
@@ -133,7 +118,7 @@ export class AnthropicHandler implements ApiHandler {
break
}
default: {
stream = await client.messages.create({
stream = await this.client.messages.create({
model: modelId,
max_tokens: model.info.maxTokens || 8192,
temperature: 0,
+14 -39
View File
@@ -7,52 +7,32 @@ import { ApiStream } from "@api/transform/stream"
export class CerebrasHandler implements ApiHandler {
private options: ApiHandlerOptions
private client: Cerebras | undefined
private client: Cerebras
constructor(options: ApiHandlerOptions) {
this.options = options
}
private ensureClient(): Cerebras {
if (!this.client) {
// Clean and validate the API key
const cleanApiKey = this.options.cerebrasApiKey?.trim()
// Clean and validate the API key
const cleanApiKey = this.options.cerebrasApiKey?.trim()
if (!cleanApiKey) {
throw new Error("Cerebras API key is required")
}
try {
this.client = new Cerebras({
apiKey: cleanApiKey,
timeout: 30000, // 30 second timeout
})
} catch (error) {
throw new Error(`Error creating Cerebras client: ${error.message}`)
}
if (!cleanApiKey) {
throw new Error("Cerebras API key is required")
}
return this.client
this.client = new Cerebras({
apiKey: cleanApiKey,
timeout: 30000, // 30 second timeout
})
}
@withRetry()
async *createMessage(systemPrompt: string, messages: Anthropic.Messages.MessageParam[]): ApiStream {
const client = this.ensureClient()
// Convert Anthropic messages to Cerebras format
const cerebrasMessages: Array<{
role: "system" | "user" | "assistant"
content: string
}> = [{ role: "system", content: systemPrompt }]
// Helper function to strip thinking tags from content
const stripThinkingTags = (content: string): string => {
return content.replace(/<think>[\s\S]*?<\/think>/g, "").trim()
}
// Check if this is a reasoning model that uses thinking tags
const modelId = this.getModel().id
const isReasoningModel = modelId.includes("qwen") || modelId.includes("deepseek-r1-distill")
// Convert Anthropic messages to Cerebras format
for (const message of messages) {
if (message.role === "user") {
@@ -70,7 +50,7 @@ export class CerebrasHandler implements ApiHandler {
: message.content
cerebrasMessages.push({ role: "user", content })
} else if (message.role === "assistant") {
let content = Array.isArray(message.content)
const content = Array.isArray(message.content)
? message.content
.map((block) => {
if (block.type === "text") {
@@ -80,19 +60,12 @@ export class CerebrasHandler implements ApiHandler {
})
.join("\n")
: message.content || ""
// Strip thinking tags from assistant messages for reasoning models
// so the model doesn't see its own thinking in the conversation history
if (isReasoningModel) {
content = stripThinkingTags(content)
}
cerebrasMessages.push({ role: "assistant", content })
}
}
try {
const stream = await client.chat.completions.create({
const stream = await this.client.chat.completions.create({
model: this.getModel().id,
messages: cerebrasMessages,
temperature: 0,
@@ -101,6 +74,8 @@ export class CerebrasHandler implements ApiHandler {
// 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
-1
View File
@@ -27,7 +27,6 @@ export class ClaudeCodeHandler implements ApiHandler {
messages: filteredMessages,
path: this.options.claudeCodePath,
modelId: this.getModel().id,
thinkingBudgetTokens: this.options.thinkingBudgetTokens,
})
// Usage is included with assistant messages,
+11 -25
View File
@@ -10,42 +10,28 @@ import { withRetry } from "../retry"
export class ClineHandler implements ApiHandler {
private options: ApiHandlerOptions
private client: OpenAI | undefined
private client: OpenAI
lastGenerationId?: string
constructor(options: ApiHandlerOptions) {
this.options = options
}
private ensureClient(): OpenAI {
if (!this.client) {
if (!this.options.clineApiKey) {
throw new Error("You don't seem to be logged in to a Cline account.")
}
try {
this.client = new OpenAI({
baseURL: "https://api.cline.bot/v1",
apiKey: this.options.clineApiKey || "",
defaultHeaders: {
"HTTP-Referer": "https://cline.bot", // Optional, for including your app on cline.bot rankings.
"X-Title": "Cline", // Optional. Shows in rankings on cline.bot.
"X-Task-ID": this.options.taskId || "", // Include the task ID in the request headers
},
})
} catch (error) {
throw new Error(`Error creating Cline client: ${error.message}`)
}
}
return this.client
this.client = new OpenAI({
baseURL: "https://api.cline.bot/v1",
apiKey: this.options.clineApiKey || "",
defaultHeaders: {
"HTTP-Referer": "https://cline.bot", // Optional, for including your app on cline.bot rankings.
"X-Title": "Cline", // Optional. Shows in rankings on cline.bot.
"X-Task-ID": this.options.taskId || "", // Include the task ID in the request headers
},
})
}
@withRetry()
async *createMessage(systemPrompt: string, messages: Anthropic.Messages.MessageParam[]): ApiStream {
const client = this.ensureClient()
this.lastGenerationId = undefined
const stream = await createOpenRouterStream(
client,
this.client,
systemPrompt,
messages,
this.getModel(),
+6 -20
View File
@@ -10,27 +10,14 @@ import { convertToR1Format } from "../transform/r1-format"
export class DeepSeekHandler implements ApiHandler {
private options: ApiHandlerOptions
private client: OpenAI | undefined
private client: OpenAI
constructor(options: ApiHandlerOptions) {
this.options = options
}
private ensureClient(): OpenAI {
if (!this.client) {
if (!this.options.deepSeekApiKey) {
throw new Error("DeepSeek API key is required")
}
try {
this.client = new OpenAI({
baseURL: "https://api.deepseek.com/v1",
apiKey: this.options.deepSeekApiKey,
})
} catch (error) {
throw new Error(`Error creating DeepSeek client: ${error.message}`)
}
}
return this.client
this.client = new OpenAI({
baseURL: "https://api.deepseek.com/v1",
apiKey: this.options.deepSeekApiKey,
})
}
private async *yieldUsage(info: ModelInfo, usage: OpenAI.Completions.CompletionUsage | undefined): ApiStream {
@@ -67,7 +54,6 @@ export class DeepSeekHandler implements ApiHandler {
@withRetry()
async *createMessage(systemPrompt: string, messages: Anthropic.Messages.MessageParam[]): ApiStream {
const client = this.ensureClient()
const model = this.getModel()
const isDeepseekReasoner = model.id.includes("deepseek-reasoner")
@@ -81,7 +67,7 @@ export class DeepSeekHandler implements ApiHandler {
openAiMessages = convertToR1Format([{ role: "user", content: systemPrompt }, ...messages])
}
const stream = await client.chat.completions.create({
const stream = await this.client.chat.completions.create({
model: model.id,
max_completion_tokens: model.info.maxTokens,
messages: openAiMessages,
+6 -20
View File
@@ -8,26 +8,13 @@ import { withRetry } from "../retry"
export class DoubaoHandler implements ApiHandler {
private options: ApiHandlerOptions
private client: OpenAI | undefined
private client: OpenAI
constructor(options: ApiHandlerOptions) {
this.options = options
}
private ensureClient(): OpenAI {
if (!this.client) {
if (!this.options.doubaoApiKey) {
throw new Error("Doubao API key is required")
}
try {
this.client = new OpenAI({
baseURL: "https://ark.cn-beijing.volces.com/api/v3/",
apiKey: this.options.doubaoApiKey,
})
} catch (error) {
throw new Error(`Error creating Doubao client: ${error.message}`)
}
}
return this.client
this.client = new OpenAI({
baseURL: "https://ark.cn-beijing.volces.com/api/v3/",
apiKey: this.options.doubaoApiKey,
})
}
getModel(): { id: DoubaoModelId; info: ModelInfo } {
@@ -44,13 +31,12 @@ export class DoubaoHandler implements ApiHandler {
@withRetry()
async *createMessage(systemPrompt: string, messages: Anthropic.Messages.MessageParam[]): ApiStream {
const client = this.ensureClient()
const model = this.getModel()
let openAiMessages: OpenAI.Chat.ChatCompletionMessageParam[] = [
{ role: "system", content: systemPrompt },
...convertToOpenAiMessages(messages),
]
const stream = await client.chat.completions.create({
const stream = await this.client.chat.completions.create({
model: model.id,
max_completion_tokens: model.info.maxTokens,
messages: openAiMessages,
+6 -20
View File
@@ -15,32 +15,18 @@ import { ApiStream } from "../transform/stream"
export class FireworksHandler implements ApiHandler {
private options: ApiHandlerOptions
private client: OpenAI | undefined
private client: OpenAI
constructor(options: ApiHandlerOptions) {
this.options = options
}
private ensureClient(): OpenAI {
if (!this.client) {
if (!this.options.fireworksApiKey) {
throw new Error("Fireworks API key is required")
}
try {
this.client = new OpenAI({
baseURL: "https://api.fireworks.ai/inference/v1",
apiKey: this.options.fireworksApiKey,
})
} catch (error) {
throw new Error(`Error creating Fireworks client: ${error.message}`)
}
}
return this.client
this.client = new OpenAI({
baseURL: "https://api.fireworks.ai/inference/v1",
apiKey: this.options.fireworksApiKey,
})
}
@withRetry()
async *createMessage(systemPrompt: string, messages: Anthropic.Messages.MessageParam[]): ApiStream {
const client = this.ensureClient()
const modelId = this.options.fireworksModelId ?? ""
const openAiMessages: OpenAI.Chat.ChatCompletionMessageParam[] = [
@@ -48,7 +34,7 @@ export class FireworksHandler implements ApiHandler {
...convertToOpenAiMessages(messages),
]
const stream = await client.chat.completions.create({
const stream = await this.client.chat.completions.create({
model: modelId,
...(this.options.fireworksModelMaxCompletionTokens
? { max_completion_tokens: this.options.fireworksModelMaxCompletionTokens }
+18 -35
View File
@@ -38,45 +38,30 @@ interface GeminiHandlerOptions extends ApiHandlerOptions {
*/
export class GeminiHandler implements ApiHandler {
private options: ApiHandlerOptions
private client: GoogleGenAI | undefined
private client: GoogleGenAI
constructor(options: GeminiHandlerOptions) {
// Store the options
this.options = options
}
private ensureClient(): GoogleGenAI {
if (!this.client) {
const options = this.options as GeminiHandlerOptions
if (options.isVertex) {
// Initialize with Vertex AI configuration
const project = this.options.vertexProjectId ?? "not-provided"
const location = this.options.vertexRegion ?? "not-provided"
if (options.isVertex) {
// Initialize with Vertex AI configuration
const project = this.options.vertexProjectId ?? "not-provided"
const location = this.options.vertexRegion ?? "not-provided"
try {
this.client = new GoogleGenAI({
vertexai: true,
project,
location,
})
} catch (error) {
throw new Error(`Error creating Gemini Vertex AI client: ${error.message}`)
}
} else {
// Initialize with standard API key
if (!options.geminiApiKey) {
throw new Error("API key is required for Google Gemini when not using Vertex AI")
}
try {
this.client = new GoogleGenAI({ apiKey: options.geminiApiKey })
} catch (error) {
throw new Error(`Error creating Gemini client: ${error.message}`)
}
this.client = new GoogleGenAI({
vertexai: true,
project,
location,
})
} else {
// Initialize with standard API key
if (!options.geminiApiKey) {
throw new Error("API key is required for Google Gemini when not using Vertex AI")
}
this.client = new GoogleGenAI({ apiKey: options.geminiApiKey })
}
return this.client
}
/**
@@ -95,7 +80,6 @@ export class GeminiHandler implements ApiHandler {
maxDelay: 15000,
})
async *createMessage(systemPrompt: string, messages: Anthropic.Messages.MessageParam[]): ApiStream {
const client = this.ensureClient()
const { id: modelId, info } = this.getModel()
const contents = messages.map(convertAnthropicMessageToGemini)
@@ -133,7 +117,7 @@ export class GeminiHandler implements ApiHandler {
let lastUsageMetadata: GenerateContentResponseUsageMetadata | undefined
try {
const result = await client.models.generateContentStream({
const result = await this.client.models.generateContentStream({
model: modelId,
contents: contents,
config: {
@@ -367,7 +351,6 @@ export class GeminiHandler implements ApiHandler {
*/
async countTokens(content: Array<any>): Promise<number> {
try {
const client = this.ensureClient()
const { id: model } = this.getModel()
// Convert content to Gemini format
@@ -379,7 +362,7 @@ export class GeminiHandler implements ApiHandler {
})
// Use Gemini's token counting API
const response = await client.models.countTokens({
const response = await this.client.models.countTokens({
model,
contents: [{ parts: geminiContent }],
})
+15 -24
View File
@@ -8,35 +8,21 @@ import { withRetry } from "../retry"
export class LiteLlmHandler implements ApiHandler {
private options: ApiHandlerOptions
private client: OpenAI | undefined
private client: OpenAI
constructor(options: ApiHandlerOptions) {
this.options = options
}
private ensureClient(): OpenAI {
if (!this.client) {
if (!this.options.liteLlmApiKey) {
throw new Error("LiteLLM API key is required")
}
try {
this.client = new OpenAI({
baseURL: this.options.liteLlmBaseUrl || "http://localhost:4000",
apiKey: this.options.liteLlmApiKey || "noop",
})
} catch (error) {
throw new Error(`Error creating LiteLLM client: ${error.message}`)
}
}
return this.client
this.client = new OpenAI({
baseURL: this.options.liteLlmBaseUrl || "http://localhost:4000",
apiKey: this.options.liteLlmApiKey || "noop",
})
}
async calculateCost(prompt_tokens: number, completion_tokens: number): Promise<number | undefined> {
// Reference: https://github.com/BerriAI/litellm/blob/122ee634f434014267af104814022af1d9a0882f/litellm/proxy/spend_tracking/spend_management_endpoints.py#L1473
const client = this.ensureClient()
const modelId = this.options.liteLlmModelId || liteLlmDefaultModelId
try {
const response = await fetch(`${client.baseURL}/spend/calculate`, {
const response = await fetch(`${this.client.baseURL}/spend/calculate`, {
method: "POST",
headers: {
"Content-Type": "application/json",
@@ -68,7 +54,6 @@ export class LiteLlmHandler implements ApiHandler {
@withRetry()
async *createMessage(systemPrompt: string, messages: Anthropic.Messages.MessageParam[]): ApiStream {
const client = this.ensureClient()
const formattedMessages = convertToOpenAiMessages(messages)
const systemMessage: OpenAI.Chat.ChatCompletionSystemMessageParam = {
role: "system",
@@ -116,15 +101,21 @@ export class LiteLlmHandler implements ApiHandler {
return message
})
const stream = await client.chat.completions.create({
const requestPayload: OpenAI.Chat.Completions.ChatCompletionCreateParamsStreaming & {
metadata?: { cline_task_id: string }
} = {
model: this.options.liteLlmModelId || liteLlmDefaultModelId,
messages: [enhancedSystemMessage, ...enhancedMessages],
temperature,
stream: true,
stream_options: { include_usage: true },
...(thinkingConfig && { thinking: thinkingConfig }), // Add thinking configuration when applicable
...(this.options.taskId && { litellm_session_id: `cline-${this.options.taskId}` }), // Add session ID for LiteLLM tracking
})
...(this.options.taskId && {
metadata: { cline_task_id: this.options.taskId },
}),
}
const stream = await this.client.chat.completions.create(requestPayload)
const inputCost = (await this.calculateCost(1e6, 0)) || 0
const outputCost = (await this.calculateCost(0, 1e6)) || 0
+6 -17
View File
@@ -8,36 +8,25 @@ import { withRetry } from "../retry"
export class LmStudioHandler implements ApiHandler {
private options: ApiHandlerOptions
private client: OpenAI | undefined
private client: OpenAI
constructor(options: ApiHandlerOptions) {
this.options = options
}
private ensureClient(): OpenAI {
if (!this.client) {
try {
this.client = new OpenAI({
baseURL: (this.options.lmStudioBaseUrl || "http://localhost:1234") + "/v1",
apiKey: "noop",
})
} catch (error) {
throw new Error(`Error creating LM Studio client: ${error.message}`)
}
}
return this.client
this.client = new OpenAI({
baseURL: (this.options.lmStudioBaseUrl || "http://localhost:1234") + "/v1",
apiKey: "noop",
})
}
@withRetry({ retryAllErrors: true })
async *createMessage(systemPrompt: string, messages: Anthropic.Messages.MessageParam[]): ApiStream {
const client = this.ensureClient()
const openAiMessages: OpenAI.Chat.ChatCompletionMessageParam[] = [
{ role: "system", content: systemPrompt },
...convertToOpenAiMessages(messages),
]
try {
const stream = await client.chat.completions.create({
const stream = await this.client.chat.completions.create({
model: this.getModel().id,
messages: openAiMessages,
stream: true,
+5 -19
View File
@@ -8,32 +8,18 @@ import { ApiStream } from "../transform/stream"
export class MistralHandler implements ApiHandler {
private options: ApiHandlerOptions
private client: Mistral | undefined
private client: Mistral
constructor(options: ApiHandlerOptions) {
this.options = options
}
private ensureClient(): Mistral {
if (!this.client) {
if (!this.options.mistralApiKey) {
throw new Error("Mistral API key is required")
}
try {
this.client = new Mistral({
apiKey: this.options.mistralApiKey,
})
} catch (error) {
throw new Error(`Error creating Mistral client: ${error.message}`)
}
}
return this.client
this.client = new Mistral({
apiKey: this.options.mistralApiKey,
})
}
@withRetry()
async *createMessage(systemPrompt: string, messages: Anthropic.Messages.MessageParam[]): ApiStream {
const client = this.ensureClient()
const stream = await client.chat
const stream = await this.client.chat
.stream({
model: this.getModel().id,
// max_completion_tokens: this.getModel().info.maxTokens,
+7 -20
View File
@@ -8,37 +8,24 @@ import { convertToR1Format } from "../transform/r1-format"
import { nebiusDefaultModelId, nebiusModels, type ModelInfo, type ApiHandlerOptions, type NebiusModelId } from "../../shared/api"
export class NebiusHandler implements ApiHandler {
private client: OpenAI | undefined
private client: OpenAI
constructor(private readonly options: ApiHandlerOptions) {}
private ensureClient(): OpenAI {
if (!this.client) {
if (!this.options.nebiusApiKey) {
throw new Error("Nebius API key is required")
}
try {
this.client = new OpenAI({
baseURL: "https://api.studio.nebius.ai/v1",
apiKey: this.options.nebiusApiKey,
})
} catch (error) {
throw new Error(`Error creating Nebius client: ${error.message}`)
}
}
return this.client
constructor(private readonly options: ApiHandlerOptions) {
this.client = new OpenAI({
baseURL: "https://api.studio.nebius.ai/v1",
apiKey: this.options.nebiusApiKey,
})
}
@withRetry()
async *createMessage(systemPrompt: string, messages: Anthropic.Messages.MessageParam[]): ApiStream {
const client = this.ensureClient()
const model = this.getModel()
const openAiMessages: OpenAI.Chat.ChatCompletionMessageParam[] = model.id.includes("DeepSeek-R1")
? convertToR1Format([{ role: "user", content: systemPrompt }, ...messages])
: [{ role: "system", content: systemPrompt }, ...convertToOpenAiMessages(messages)]
const stream = await client.chat.completions.create({
const stream = await this.client.chat.completions.create({
model: model.id,
messages: openAiMessages,
temperature: 0,
+3 -14
View File
@@ -8,26 +8,15 @@ import { withRetry } from "../retry"
export class OllamaHandler implements ApiHandler {
private options: ApiHandlerOptions
private client: Ollama | undefined
private client: Ollama
constructor(options: ApiHandlerOptions) {
this.options = options
}
private ensureClient(): Ollama {
if (!this.client) {
try {
this.client = new Ollama({ host: this.options.ollamaBaseUrl || "http://localhost:11434" })
} catch (error) {
throw new Error(`Error creating Ollama client: ${error.message}`)
}
}
return this.client
this.client = new Ollama({ host: this.options.ollamaBaseUrl || "http://localhost:11434" })
}
@withRetry({ retryAllErrors: true })
async *createMessage(systemPrompt: string, messages: Anthropic.Messages.MessageParam[]): ApiStream {
const client = this.ensureClient()
const ollamaMessages: Message[] = [{ role: "system", content: systemPrompt }, ...convertToOllamaMessages(messages)]
try {
@@ -38,7 +27,7 @@ export class OllamaHandler implements ApiHandler {
})
// Create the actual API request promise
const apiPromise = client.chat({
const apiPromise = this.client.chat({
model: this.getModel().id,
messages: ollamaMessages,
stream: true,
+7 -21
View File
@@ -10,26 +10,13 @@ import type { ChatCompletionReasoningEffort } from "openai/resources/chat/comple
export class OpenAiNativeHandler implements ApiHandler {
private options: ApiHandlerOptions
private client: OpenAI | undefined
private client: OpenAI
constructor(options: ApiHandlerOptions) {
this.options = options
}
private ensureClient(): OpenAI {
if (!this.client) {
if (!this.options.openAiNativeApiKey) {
throw new Error("OpenAI API key is required")
}
try {
this.client = new OpenAI({
apiKey: this.options.openAiNativeApiKey,
})
} catch (error: any) {
throw new Error(`Error creating OpenAI client: ${error.message}`)
}
}
return this.client
this.client = new OpenAI({
apiKey: this.options.openAiNativeApiKey,
})
}
private async *yieldUsage(info: ModelInfo, usage: OpenAI.Completions.CompletionUsage | undefined): ApiStream {
@@ -51,7 +38,6 @@ export class OpenAiNativeHandler implements ApiHandler {
@withRetry()
async *createMessage(systemPrompt: string, messages: Anthropic.Messages.MessageParam[]): ApiStream {
const client = this.ensureClient()
const model = this.getModel()
switch (model.id) {
@@ -59,7 +45,7 @@ export class OpenAiNativeHandler implements ApiHandler {
case "o1-preview":
case "o1-mini": {
// o1 doesn't support streaming, non-1 temp, or system prompt
const response = await client.chat.completions.create({
const response = await this.client.chat.completions.create({
model: model.id,
messages: [{ role: "user", content: systemPrompt }, ...convertToOpenAiMessages(messages)],
})
@@ -75,7 +61,7 @@ export class OpenAiNativeHandler implements ApiHandler {
case "o4-mini":
case "o3":
case "o3-mini": {
const stream = await client.chat.completions.create({
const stream = await this.client.chat.completions.create({
model: model.id,
messages: [{ role: "developer", content: systemPrompt }, ...convertToOpenAiMessages(messages)],
stream: true,
@@ -99,7 +85,7 @@ export class OpenAiNativeHandler implements ApiHandler {
break
}
default: {
const stream = await client.chat.completions.create({
const stream = await this.client.chat.completions.create({
model: model.id,
// max_completion_tokens: this.getModel().info.maxTokens,
temperature: 0,
+22 -36
View File
@@ -10,49 +10,35 @@ import type { ChatCompletionReasoningEffort } from "openai/resources/chat/comple
export class OpenAiHandler implements ApiHandler {
private options: ApiHandlerOptions
private client: OpenAI | undefined
private client: OpenAI
constructor(options: ApiHandlerOptions) {
this.options = options
}
private ensureClient(): OpenAI {
if (!this.client) {
if (!this.options.openAiApiKey) {
throw new Error("OpenAI API key is required")
}
try {
// Azure API shape slightly differs from the core API shape: https://github.com/openai/openai-node?tab=readme-ov-file#microsoft-azure-openai
// Use azureApiVersion to determine if this is an Azure endpoint, since the URL may not always contain 'azure.com'
if (
this.options.azureApiVersion ||
((this.options.openAiBaseUrl?.toLowerCase().includes("azure.com") ||
this.options.openAiBaseUrl?.toLowerCase().includes("azure.us")) &&
!this.options.openAiModelId?.toLowerCase().includes("deepseek"))
) {
this.client = new AzureOpenAI({
baseURL: this.options.openAiBaseUrl,
apiKey: this.options.openAiApiKey,
apiVersion: this.options.azureApiVersion || azureOpenAiDefaultApiVersion,
defaultHeaders: this.options.openAiHeaders,
})
} else {
this.client = new OpenAI({
baseURL: this.options.openAiBaseUrl,
apiKey: this.options.openAiApiKey,
defaultHeaders: this.options.openAiHeaders,
})
}
} catch (error: any) {
throw new Error(`Error creating OpenAI client: ${error.message}`)
}
// Azure API shape slightly differs from the core API shape: https://github.com/openai/openai-node?tab=readme-ov-file#microsoft-azure-openai
// Use azureApiVersion to determine if this is an Azure endpoint, since the URL may not always contain 'azure.com'
if (
this.options.azureApiVersion ||
((this.options.openAiBaseUrl?.toLowerCase().includes("azure.com") ||
this.options.openAiBaseUrl?.toLowerCase().includes("azure.us")) &&
!this.options.openAiModelId?.toLowerCase().includes("deepseek"))
) {
this.client = new AzureOpenAI({
baseURL: this.options.openAiBaseUrl,
apiKey: this.options.openAiApiKey,
apiVersion: this.options.azureApiVersion || azureOpenAiDefaultApiVersion,
defaultHeaders: this.options.openAiHeaders,
})
} else {
this.client = new OpenAI({
baseURL: this.options.openAiBaseUrl,
apiKey: this.options.openAiApiKey,
defaultHeaders: this.options.openAiHeaders,
})
}
return this.client
}
@withRetry()
async *createMessage(systemPrompt: string, messages: Anthropic.Messages.MessageParam[]): ApiStream {
const client = this.ensureClient()
const modelId = this.options.openAiModelId ?? ""
const isDeepseekReasoner = modelId.includes("deepseek-reasoner")
const isR1FormatRequired = this.options.openAiModelInfo?.isR1FormatRequired ?? false
@@ -82,7 +68,7 @@ export class OpenAiHandler implements ApiHandler {
reasoningEffort = (this.options.reasoningEffort as ChatCompletionReasoningEffort) || "medium"
}
const stream = await client.chat.completions.create({
const stream = await this.client.chat.completions.create({
model: modelId,
messages: openAiMessages,
temperature,
+10 -24
View File
@@ -11,41 +11,27 @@ import { OpenRouterErrorResponse } from "./types"
export class OpenRouterHandler implements ApiHandler {
private options: ApiHandlerOptions
private client: OpenAI | undefined
private client: OpenAI
lastGenerationId?: string
constructor(options: ApiHandlerOptions) {
this.options = options
}
private ensureClient(): OpenAI {
if (!this.client) {
if (!this.options.openRouterApiKey) {
throw new Error("OpenRouter API key is required")
}
try {
this.client = new OpenAI({
baseURL: "https://openrouter.ai/api/v1",
apiKey: this.options.openRouterApiKey,
defaultHeaders: {
"HTTP-Referer": "https://cline.bot", // Optional, for including your app on openrouter.ai rankings.
"X-Title": "Cline", // Optional. Shows in rankings on openrouter.ai.
},
})
} catch (error: any) {
throw new Error(`Error creating OpenRouter client: ${error.message}`)
}
}
return this.client
this.client = new OpenAI({
baseURL: "https://openrouter.ai/api/v1",
apiKey: this.options.openRouterApiKey,
defaultHeaders: {
"HTTP-Referer": "https://cline.bot", // Optional, for including your app on openrouter.ai rankings.
"X-Title": "Cline", // Optional. Shows in rankings on openrouter.ai.
},
})
}
@withRetry()
async *createMessage(systemPrompt: string, messages: Anthropic.Messages.MessageParam[]): ApiStream {
const client = this.ensureClient()
this.lastGenerationId = undefined
const stream = await createOpenRouterStream(
client,
this.client,
systemPrompt,
messages,
this.getModel(),
+9 -23
View File
@@ -18,30 +18,17 @@ import { withRetry } from "../retry"
export class QwenHandler implements ApiHandler {
private options: ApiHandlerOptions
private client: OpenAI | undefined
private client: OpenAI
constructor(options: ApiHandlerOptions) {
this.options = options
}
private ensureClient(): OpenAI {
if (!this.client) {
if (!this.options.qwenApiKey) {
throw new Error("Alibaba API key is required")
}
try {
this.client = new OpenAI({
baseURL:
this.options.qwenApiLine === "china"
? "https://dashscope.aliyuncs.com/compatible-mode/v1"
: "https://dashscope-intl.aliyuncs.com/compatible-mode/v1",
apiKey: this.options.qwenApiKey,
})
} catch (error: any) {
throw new Error(`Error creating Alibaba client: ${error.message}`)
}
}
return this.client
this.client = new OpenAI({
baseURL:
this.options.qwenApiLine === "china"
? "https://dashscope.aliyuncs.com/compatible-mode/v1"
: "https://dashscope-intl.aliyuncs.com/compatible-mode/v1",
apiKey: this.options.qwenApiKey,
})
}
getModel(): { id: MainlandQwenModelId | InternationalQwenModelId; info: ModelInfo } {
@@ -64,7 +51,6 @@ export class QwenHandler implements ApiHandler {
@withRetry()
async *createMessage(systemPrompt: string, messages: Anthropic.Messages.MessageParam[]): ApiStream {
const client = this.ensureClient()
const model = this.getModel()
const isDeepseekReasoner = model.id.includes("deepseek-r1")
const isReasoningModelFamily = model.id.includes("qwen3") || ["qwen-plus-latest", "qwen-turbo-latest"].includes(model.id)
@@ -90,7 +76,7 @@ export class QwenHandler implements ApiHandler {
temperature = undefined
}
const stream = await client.chat.completions.create({
const stream = await this.client.chat.completions.create({
model: model.id,
max_completion_tokens: model.info.maxTokens,
messages: openAiMessages,
+10 -24
View File
@@ -19,36 +19,22 @@ interface RequestyUsage extends OpenAI.CompletionUsage {
export class RequestyHandler implements ApiHandler {
private options: ApiHandlerOptions
private client: OpenAI | undefined
private client: OpenAI
constructor(options: ApiHandlerOptions) {
this.options = options
}
private ensureClient(): OpenAI {
if (!this.client) {
if (!this.options.requestyApiKey) {
throw new Error("Requesty API key is required")
}
try {
this.client = new OpenAI({
baseURL: "https://router.requesty.ai/v1",
apiKey: this.options.requestyApiKey,
defaultHeaders: {
"HTTP-Referer": "https://cline.bot",
"X-Title": "Cline",
},
})
} catch (error: any) {
throw new Error(`Error creating Requesty client: ${error.message}`)
}
}
return this.client
this.client = new OpenAI({
baseURL: "https://router.requesty.ai/v1",
apiKey: this.options.requestyApiKey,
defaultHeaders: {
"HTTP-Referer": "https://cline.bot",
"X-Title": "Cline",
},
})
}
@withRetry()
async *createMessage(systemPrompt: string, messages: Anthropic.Messages.MessageParam[]): ApiStream {
const client = this.ensureClient()
const model = this.getModel()
const openAiMessages: OpenAI.Chat.ChatCompletionMessageParam[] = [
@@ -71,7 +57,7 @@ export class RequestyHandler implements ApiHandler {
: {}
// @ts-ignore-next-line
const stream = await client.chat.completions.create({
const stream = await this.client.chat.completions.create({
model: model.id,
max_tokens: model.info.maxTokens || undefined,
messages: openAiMessages,
+6 -20
View File
@@ -9,32 +9,18 @@ import { convertToR1Format } from "@api/transform/r1-format"
export class SambanovaHandler implements ApiHandler {
private options: ApiHandlerOptions
private client: OpenAI | undefined
private client: OpenAI
constructor(options: ApiHandlerOptions) {
this.options = options
}
private ensureClient(): OpenAI {
if (!this.client) {
if (!this.options.sambanovaApiKey) {
throw new Error("SambaNova API key is required")
}
try {
this.client = new OpenAI({
baseURL: "https://api.sambanova.ai/v1",
apiKey: this.options.sambanovaApiKey,
})
} catch (error: any) {
throw new Error(`Error creating SambaNova client: ${error.message}`)
}
}
return this.client
this.client = new OpenAI({
baseURL: "https://api.sambanova.ai/v1",
apiKey: this.options.sambanovaApiKey,
})
}
@withRetry()
async *createMessage(systemPrompt: string, messages: Anthropic.Messages.MessageParam[]): ApiStream {
const client = this.ensureClient()
const model = this.getModel()
let openAiMessages: OpenAI.Chat.ChatCompletionMessageParam[] = [
@@ -48,7 +34,7 @@ export class SambanovaHandler implements ApiHandler {
openAiMessages = convertToR1Format([{ role: "user", content: systemPrompt }, ...messages])
}
const stream = await client.chat.completions.create({
const stream = await this.client.chat.completions.create({
model: this.getModel().id,
messages: openAiMessages,
temperature: 0,
-133
View File
@@ -133,8 +133,6 @@ export class SapAiCoreHandler implements ApiHandler {
const openAIModels = ["gpt-4o", "gpt-4", "gpt-4o-mini", "o1", "gpt-4.1", "gpt-4.1-nano", "o3-mini", "o3", "o4-mini"]
const geminiModels = ["gemini-2.5-flash", "gemini-2.5-pro"]
let url: string
let payload: any
if (anthropicModels.includes(model.id)) {
@@ -189,9 +187,6 @@ export class SapAiCoreHandler implements ApiHandler {
delete payload.stream
delete payload.stream_options
}
} else if (geminiModels.includes(model.id)) {
url = `${this.options.sapAiCoreBaseUrl}/v2/inference/deployments/${deploymentId}/models/${model.id}:streamGenerateContent`
payload = this.convertToGeminiFormat(systemPrompt, messages)
} else {
throw new Error(`Unsupported model: ${model.id}`)
}
@@ -238,8 +233,6 @@ export class SapAiCoreHandler implements ApiHandler {
model.id === "anthropic--claude-3.7-sonnet"
) {
yield* this.streamCompletionSonnet37(response.data, model)
} else if (geminiModels.includes(model.id)) {
yield* this.streamCompletionGemini(response.data, model)
} else {
yield* this.streamCompletion(response.data, model)
}
@@ -468,88 +461,6 @@ export class SapAiCoreHandler implements ApiHandler {
}
}
private async *streamCompletionGemini(
stream: any,
model: { id: SapAiCoreModelId; info: ModelInfo },
): AsyncGenerator<any, void, unknown> {
let promptTokens = 0
let outputTokens = 0
let cacheReadTokens = 0
let thoughtsTokenCount = 0
try {
for await (const chunk of stream) {
const lines = chunk.toString().split("\n").filter(Boolean)
for (const line of lines) {
if (line.startsWith("data: ")) {
const jsonData = line.slice(6)
try {
const data = JSON.parse(jsonData)
const candidateForThoughts = data?.candidates?.[0]
const partsForThoughts = candidateForThoughts?.content?.parts
let thoughts = ""
if (partsForThoughts) {
for (const part of partsForThoughts) {
const { thought, text } = part
if (thought && text) {
thoughts += text + "\n"
}
}
}
if (thoughts.trim() !== "") {
yield {
type: "reasoning",
reasoning: thoughts.trim(),
}
}
if (data.text) {
yield {
type: "text",
text: data.text,
}
}
if (data.candidates && data.candidates[0]?.content?.parts) {
for (const part of data.candidates[0].content.parts) {
if (part.text && !part.thought) {
// Only non-thought text
yield {
type: "text",
text: part.text,
}
}
}
}
if (data.usageMetadata) {
promptTokens = data.usageMetadata.promptTokenCount ?? promptTokens
outputTokens = data.usageMetadata.candidatesTokenCount ?? outputTokens
thoughtsTokenCount = data.usageMetadata.thoughtsTokenCount ?? thoughtsTokenCount
cacheReadTokens = data.usageMetadata.cachedContentTokenCount ?? cacheReadTokens
yield {
type: "usage",
inputTokens: promptTokens - cacheReadTokens,
outputTokens,
thoughtsTokenCount,
cacheReadTokens,
}
}
} catch (error) {
console.error("Failed to parse Gemini JSON data:", error)
}
}
}
}
} catch (error) {
console.error("Error streaming Gemini completion:", error)
throw error
}
}
createUserReadableRequest(
userContent: Array<
Anthropic.TextBlockParam | Anthropic.ImageBlockParam | Anthropic.ToolUseBlockParam | Anthropic.ToolResultBlockParam
@@ -584,50 +495,6 @@ export class SapAiCoreHandler implements ApiHandler {
throw new Error(`Unsupported image format: ${format}`)
}
private convertToGeminiFormat(systemPrompt: string, messages: Anthropic.Messages.MessageParam[]) {
const contents = messages.map(this.convertAnthropicMessageToGemini)
const payload = {
contents,
systemInstruction: {
parts: [
{
text: systemPrompt,
},
],
},
generationConfig: {
maxOutputTokens: this.getModel().info.maxTokens,
temperature: 0.0,
},
}
return payload
}
private convertAnthropicMessageToGemini(message: Anthropic.Messages.MessageParam) {
const role = message.role === "assistant" ? "model" : "user"
const parts = []
if (typeof message.content === "string") {
parts.push({ text: message.content })
} else if (Array.isArray(message.content)) {
for (const block of message.content) {
if (block.type === "text") {
parts.push({ text: block.text })
} else if (block.type === "image") {
parts.push({
inlineData: {
mimeType: block.source.media_type,
data: block.source.data,
},
})
}
}
}
return { role, parts }
}
private formatAnthropicMessages(messages: Anthropic.Messages.MessageParam[]): any[] {
return messages.map((m) => {
const contentBlocks: any[] = []
+6 -20
View File
@@ -9,32 +9,18 @@ import { convertToR1Format } from "@api/transform/r1-format"
export class TogetherHandler implements ApiHandler {
private options: ApiHandlerOptions
private client: OpenAI | undefined
private client: OpenAI
constructor(options: ApiHandlerOptions) {
this.options = options
}
private ensureClient(): OpenAI {
if (!this.client) {
if (!this.options.togetherApiKey) {
throw new Error("Together API key is required")
}
try {
this.client = new OpenAI({
baseURL: "https://api.together.xyz/v1",
apiKey: this.options.togetherApiKey,
})
} catch (error: any) {
throw new Error(`Error creating Together client: ${error.message}`)
}
}
return this.client
this.client = new OpenAI({
baseURL: "https://api.together.xyz/v1",
apiKey: this.options.togetherApiKey,
})
}
@withRetry()
async *createMessage(systemPrompt: string, messages: Anthropic.Messages.MessageParam[]): ApiStream {
const client = this.ensureClient()
const modelId = this.options.togetherModelId ?? ""
const isDeepseekReasoner = modelId.includes("deepseek-reasoner")
@@ -47,7 +33,7 @@ export class TogetherHandler implements ApiHandler {
openAiMessages = convertToR1Format([{ role: "user", content: systemPrompt }, ...messages])
}
const stream = await client.chat.completions.create({
const stream = await this.client.chat.completions.create({
model: modelId,
messages: openAiMessages,
temperature: 0,
+16 -43
View File
@@ -7,49 +7,25 @@ import { ApiStream } from "@api/transform/stream"
import { GeminiHandler } from "./gemini"
export class VertexHandler implements ApiHandler {
private geminiHandler: GeminiHandler | undefined
private clientAnthropic: AnthropicVertex | undefined
private geminiHandler: GeminiHandler
private clientAnthropic: AnthropicVertex
private options: ApiHandlerOptions
constructor(options: ApiHandlerOptions) {
this.options = options
}
private ensureGeminiHandler(): GeminiHandler {
if (!this.geminiHandler) {
try {
// Create a GeminiHandler with isVertex flag for Gemini models
this.geminiHandler = new GeminiHandler({
...this.options,
isVertex: true,
})
} catch (error: any) {
throw new Error(`Error creating Vertex AI Gemini handler: ${error.message}`)
}
}
return this.geminiHandler
}
// Create a GeminiHandler with isVertex flag for Gemini models
this.geminiHandler = new GeminiHandler({
...options,
isVertex: true,
})
private ensureAnthropicClient(): AnthropicVertex {
if (!this.clientAnthropic) {
if (!this.options.vertexProjectId) {
throw new Error("Vertex AI project ID is required")
}
if (!this.options.vertexRegion) {
throw new Error("Vertex AI region is required")
}
try {
// Initialize Anthropic client for Claude models
this.clientAnthropic = new AnthropicVertex({
projectId: this.options.vertexProjectId,
// https://cloud.google.com/vertex-ai/generative-ai/docs/partner-models/use-claude#regions
region: this.options.vertexRegion,
})
} catch (error: any) {
throw new Error(`Error creating Vertex AI Anthropic client: ${error.message}`)
}
}
return this.clientAnthropic
// Initialize Anthropic client for Claude models
this.clientAnthropic = new AnthropicVertex({
projectId: this.options.vertexProjectId,
// https://cloud.google.com/vertex-ai/generative-ai/docs/partner-models/use-claude#regions
region: this.options.vertexRegion,
})
}
@withRetry()
@@ -59,13 +35,10 @@ export class VertexHandler implements ApiHandler {
// For Gemini models, use the GeminiHandler
if (!modelId.includes("claude")) {
const geminiHandler = this.ensureGeminiHandler()
yield* geminiHandler.createMessage(systemPrompt, messages)
yield* this.geminiHandler.createMessage(systemPrompt, messages)
return
}
const clientAnthropic = this.ensureAnthropicClient()
// Claude implementation
let budget_tokens = this.options.thinkingBudgetTokens || 0
const reasoningOn =
@@ -90,7 +63,7 @@ export class VertexHandler implements ApiHandler {
)
const lastUserMsgIndex = userMsgIndices[userMsgIndices.length - 1] ?? -1
const secondLastMsgUserIndex = userMsgIndices[userMsgIndices.length - 2] ?? -1
stream = await clientAnthropic.beta.messages.create(
stream = await this.clientAnthropic.beta.messages.create(
{
model: modelId,
max_tokens: model.info.maxTokens || 8192,
@@ -152,7 +125,7 @@ export class VertexHandler implements ApiHandler {
break
}
default: {
stream = await clientAnthropic.beta.messages.create({
stream = await this.clientAnthropic.beta.messages.create({
model: modelId,
max_tokens: model.info.maxTokens || 8192,
temperature: 0,
+6 -20
View File
@@ -9,32 +9,18 @@ import { withRetry } from "../retry"
export class XAIHandler implements ApiHandler {
private options: ApiHandlerOptions
private client: OpenAI | undefined
private client: OpenAI
constructor(options: ApiHandlerOptions) {
this.options = options
}
private ensureClient(): OpenAI {
if (!this.client) {
if (!this.options.xaiApiKey) {
throw new Error("xAI API key is required")
}
try {
this.client = new OpenAI({
baseURL: "https://api.x.ai/v1",
apiKey: this.options.xaiApiKey,
})
} catch (error: any) {
throw new Error(`Error creating xAI client: ${error.message}`)
}
}
return this.client
this.client = new OpenAI({
baseURL: "https://api.x.ai/v1",
apiKey: this.options.xaiApiKey,
})
}
@withRetry()
async *createMessage(systemPrompt: string, messages: Anthropic.Messages.MessageParam[]): ApiStream {
const client = this.ensureClient()
const modelId = this.getModel().id
// ensure reasoning effort is either "low" or "high" for grok-3-mini
let reasoningEffort: ChatCompletionReasoningEffort | undefined
@@ -44,7 +30,7 @@ export class XAIHandler implements ApiHandler {
reasoningEffort = undefined
}
}
const stream = await client.chat.completions.create({
const stream = await this.client.chat.completions.create({
model: modelId,
max_completion_tokens: this.getModel().info.maxTokens,
temperature: 0,
-39
View File
@@ -156,45 +156,6 @@ replaced
expected: "line2\nreplaced\nline4",
isFinal: true,
},
{
name: "malformed diff - missing separator",
original: "line1\nline2\nline3",
diff: `------- SEARCH
line2
+++++++ REPLACE
replaced`,
shouldThrow: true,
},
{
name: "malformed diff - trailing space on separator",
original: "line1\nline2\nline3",
diff: `------- SEARCH
line2
=======
replaced
+++++++ REPLACE`,
shouldThrow: true,
},
{
name: "malformed diff - double replace markers",
original: "line1\nline2\nline3",
diff: `------- SEARCH
line2
+++++++ REPLACE
first replacement
+++++++ REPLACE`,
shouldThrow: true,
},
{
name: "malformed diff - malformed separator with dashes",
original: "line1\nline2\nline3",
diff: `------- SEARCH
line2
------- =======
replaced
+++++++ REPLACE`,
shouldThrow: true,
},
]
//.filter(({name}) => name === "multiple ordered replacements")
//.filter(({name}) => name === "delete then replace")
-4
View File
@@ -380,10 +380,6 @@ async function constructNewFileContentV1(diffContent: string, originalContent: s
if (isReplaceBlockEnd(line)) {
// Finished one replace block
if (searchMatchIndex === -1) {
throw new Error(`The SEARCH block:\n${currentSearchContent.trimEnd()}\n...is malformatted.`)
}
// Store this replacement
replacements.push({
start: searchMatchIndex,
@@ -36,6 +36,17 @@ export class FileContextTracker {
this.taskId = taskId
}
/**
* Gets the current working directory or returns undefined if it cannot be determined
*/
private async getCwd(): Promise<string | undefined> {
const cwd = await getCwd(undefined)
if (!cwd) {
console.info("No workspace folder available - cannot determine current working directory")
}
return cwd
}
/**
* File watchers are set up for each file that is tracked in the task metadata.
*/
@@ -45,9 +56,8 @@ export class FileContextTracker {
return
}
const cwd = await getCwd()
const cwd = await this.getCwd()
if (!cwd) {
console.info("No workspace folder available - cannot determine current working directory")
return
}
@@ -77,9 +87,8 @@ export class FileContextTracker {
*/
async trackFileContext(filePath: string, operation: "read_tool" | "user_edited" | "cline_edited" | "file_mentioned") {
try {
const cwd = await getCwd()
const cwd = await this.getCwd()
if (!cwd) {
console.info("No workspace folder available - cannot determine current working directory")
return
}
@@ -235,9 +244,7 @@ export class FileContextTracker {
async storePendingFileContextWarning(files: string[]): Promise<void> {
try {
const key = `pendingFileContextWarning_${this.taskId}`
// NOTE: Using 'as any' because dynamic keys like pendingFileContextWarning_${taskId}
// are legitimate workspace state keys but don't fit the strict LocalStateKey type system
await updateWorkspaceState(this.context, key as any, files)
await updateWorkspaceState(this.context, key, files)
} catch (error) {
console.error("Error storing pending file context warning:", error)
}
@@ -249,7 +256,7 @@ export class FileContextTracker {
async retrievePendingFileContextWarning(): Promise<string[] | undefined> {
try {
const key = `pendingFileContextWarning_${this.taskId}`
const files = (await getWorkspaceState(this.context, key as any)) as string[]
const files = (await getWorkspaceState(this.context, key)) as string[]
return files
} catch (error) {
console.error("Error retrieving pending file context warning:", error)
@@ -264,7 +271,7 @@ export class FileContextTracker {
try {
const files = await this.retrievePendingFileContextWarning()
if (files) {
await updateWorkspaceState(this.context, `pendingFileContextWarning_${this.taskId}` as any, undefined)
await updateWorkspaceState(this.context, `pendingFileContextWarning_${this.taskId}`, undefined)
return files
}
} catch (error) {
@@ -295,7 +302,7 @@ export class FileContextTracker {
if (orphanedPendingContextTasks.length > 0) {
for (const key of orphanedPendingContextTasks) {
await updateWorkspaceState(context, key as any, undefined)
await updateWorkspaceState(context, key, undefined)
}
}
+1 -2
View File
@@ -6,8 +6,8 @@ import { createRuleFile as createRuleFileImpl } from "@core/context/instructions
import * as vscode from "vscode"
import * as path from "path"
import { handleFileServiceRequest } from "./index"
import { cwd } from "@core/task"
import { refreshWorkflowToggles } from "@/core/context/instructions/user-instructions/workflows"
import { getCwd, getDesktopDir } from "@/utils/path"
/**
* Creates a rule file in either global or workspace rules directory
@@ -32,7 +32,6 @@ export const createRuleFile: FileMethodHandler = async (controller: Controller,
throw new Error("Missing or invalid parameters")
}
const cwd = await getCwd(getDesktopDir())
const { filePath, fileExists } = await createRuleFileImpl(request.isGlobal, request.filename, cwd, request.type)
if (!filePath) {
+8 -4
View File
@@ -1,9 +1,13 @@
import { deleteRuleFile as deleteRuleFileImpl } from "@core/context/instructions/user-instructions/rule-helpers"
import { RuleFile, RuleFileRequest } from "@shared/proto/file"
import * as path from "path"
import * as vscode from "vscode"
import { Controller } from ".."
import { RuleFileRequest, RuleFile } from "@shared/proto/file"
import { FileMethodHandler } from "./index"
import { refreshClineRulesToggles } from "@core/context/instructions/user-instructions/cline-rules"
import { deleteRuleFile as deleteRuleFileImpl } from "@core/context/instructions/user-instructions/rule-helpers"
import { refreshExternalRulesToggles } from "@core/context/instructions/user-instructions/external-rules"
import { refreshWorkflowToggles } from "@core/context/instructions/user-instructions/workflows"
import * as vscode from "vscode"
import * as path from "path"
import { cwd } from "@core/task"
/**
* Deletes a rule file from either global or workspace rules directory
+2 -1
View File
@@ -3,7 +3,7 @@ import { RelativePathsRequest, RelativePaths } from "@shared/proto/file"
import { FileMethodHandler } from "./index"
import * as vscode from "vscode"
import * as path from "path"
import { StringRequest } from "@shared/proto/common"
import { Metadata, StringRequest } from "@shared/proto/common"
import { getHostBridgeProvider } from "@hosts/host-providers"
/**
@@ -22,6 +22,7 @@ export const getRelativePaths: FileMethodHandler = async (
// Use the host URI service client instead of directly using vscode.Uri.parse
const parseResponse = await getHostBridgeProvider().uriServiceClient.parse(
StringRequest.create({
metadata: Metadata.create({}),
value: uriString,
}),
)
+1 -2
View File
@@ -4,7 +4,7 @@ import type { Controller } from "../index"
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"
import { getCwd, getDesktopDir } from "@/utils/path"
import { cwd } from "@core/task"
/**
* Refreshes all rule toggles (Cline, External, and Workflows)
@@ -14,7 +14,6 @@ import { getCwd, getDesktopDir } from "@/utils/path"
*/
export async function refreshRules(controller: Controller, _request: EmptyRequest): Promise<RefreshedRules> {
try {
const cwd = await getCwd(getDesktopDir())
const { globalToggles, localToggles } = await refreshClineRulesToggles(controller.context, cwd)
const { cursorLocalToggles, windsurfLocalToggles } = await refreshExternalRulesToggles(controller.context, cwd)
const { localWorkflowToggles, globalWorkflowToggles } = await refreshWorkflowToggles(controller.context, cwd)
+69 -55
View File
@@ -1,5 +1,5 @@
import { telemetryService } from "@/services/posthog/telemetry/TelemetryService"
import { getCwd, getDesktopDir } from "@/utils/path"
import { getCwd } from "@/utils/path"
import { Anthropic } from "@anthropic-ai/sdk"
import { buildApiHandler } from "@api/index"
import { cleanupLegacyCheckpoints } from "@integrations/checkpoints/CheckpointMigration"
@@ -78,10 +78,13 @@ export class Controller {
(msg) => this.postMessageToWebview(msg),
this.context.extension?.packageJSON?.version ?? "1.0.0",
)
this.accountService = new ClineAccountService(async () => {
const { apiConfiguration } = await this.getStateToPostToWebview()
return apiConfiguration?.clineApiKey
})
this.accountService = new ClineAccountService(
(msg) => this.postMessageToWebview(msg),
async () => {
const { apiConfiguration } = await this.getStateToPostToWebview()
return apiConfiguration?.clineApiKey
},
)
// Clean up legacy checkpoints
cleanupLegacyCheckpoints(this.context.globalStorageUri.fsPath, this.outputChannel).catch((error) => {
@@ -113,7 +116,7 @@ export class Controller {
try {
await storeSecret(this.context, "clineApiKey", undefined)
await updateGlobalState(this.context, "userInfo", undefined)
await updateGlobalState(this.context, "apiProvider", "openrouter")
await updateWorkspaceState(this.context, "apiProvider", "openrouter")
await this.postStateToWebview()
vscode.window.showInformationMessage("Successfully logged out of Cline")
} catch (error) {
@@ -179,7 +182,6 @@ export class Controller {
terminalOutputLineLimit ?? 500,
defaultTerminalProfile ?? "default",
enableCheckpointsSetting ?? true,
await getCwd(getDesktopDir()),
task,
images,
files,
@@ -256,6 +258,11 @@ export class Controller {
previousModeReasoningEffort: newReasoningEffort,
previousModeAwsBedrockCustomSelected: newAwsBedrockCustomSelected,
previousModeAwsBedrockCustomModelBaseId: newAwsBedrockCustomModelBaseId,
previousModeSapAiCoreClientId: newSapAiCoreClientId,
previousModeSapAiCoreClientSecret: newSapAiCoreClientSecret,
previousModeSapAiCoreBaseUrl: newSapAiCoreBaseUrl,
previousModeSapAiCoreTokenUrl: newSapAiCoreTokenUrl,
previousModeSapAiCoreResourceGroup: newSapAiResourceGroup,
previousModeSapAiCoreModelId: newSapAiCoreModelId,
planActSeparateModelsSetting,
} = await getAllExtensionState(this.context)
@@ -264,9 +271,9 @@ export class Controller {
if (shouldSwitchModel) {
// Save the last model used in this mode
await updateGlobalState(this.context, "previousModeApiProvider", apiConfiguration.apiProvider)
await updateGlobalState(this.context, "previousModeThinkingBudgetTokens", apiConfiguration.thinkingBudgetTokens)
await updateGlobalState(this.context, "previousModeReasoningEffort", apiConfiguration.reasoningEffort)
await updateWorkspaceState(this.context, "previousModeApiProvider", apiConfiguration.apiProvider)
await updateWorkspaceState(this.context, "previousModeThinkingBudgetTokens", apiConfiguration.thinkingBudgetTokens)
await updateWorkspaceState(this.context, "previousModeReasoningEffort", apiConfiguration.reasoningEffort)
switch (apiConfiguration.apiProvider) {
case "anthropic":
case "vertex":
@@ -276,16 +283,16 @@ export class Controller {
case "qwen":
case "deepseek":
case "xai":
await updateGlobalState(this.context, "previousModeModelId", apiConfiguration.apiModelId)
await updateWorkspaceState(this.context, "previousModeModelId", apiConfiguration.apiModelId)
break
case "bedrock":
await updateGlobalState(this.context, "previousModeModelId", apiConfiguration.apiModelId)
await updateGlobalState(
await updateWorkspaceState(this.context, "previousModeModelId", apiConfiguration.apiModelId)
await updateWorkspaceState(
this.context,
"previousModeAwsBedrockCustomSelected",
apiConfiguration.awsBedrockCustomSelected,
)
await updateGlobalState(
await updateWorkspaceState(
this.context,
"previousModeAwsBedrockCustomModelBaseId",
apiConfiguration.awsBedrockCustomModelBaseId,
@@ -293,38 +300,51 @@ export class Controller {
break
case "openrouter":
case "cline":
await updateGlobalState(this.context, "previousModeModelId", apiConfiguration.openRouterModelId)
await updateGlobalState(this.context, "previousModeModelInfo", apiConfiguration.openRouterModelInfo)
await updateWorkspaceState(this.context, "previousModeModelId", apiConfiguration.openRouterModelId)
await updateWorkspaceState(this.context, "previousModeModelInfo", apiConfiguration.openRouterModelInfo)
break
case "vscode-lm":
// Important we don't set modelId to this, as it's an object not string (webview expects model id to be a string)
await updateGlobalState(
await updateWorkspaceState(
this.context,
"previousModeVsCodeLmModelSelector",
apiConfiguration.vsCodeLmModelSelector,
)
break
case "openai":
await updateGlobalState(this.context, "previousModeModelId", apiConfiguration.openAiModelId)
await updateGlobalState(this.context, "previousModeModelInfo", apiConfiguration.openAiModelInfo)
await updateWorkspaceState(this.context, "previousModeModelId", apiConfiguration.openAiModelId)
await updateWorkspaceState(this.context, "previousModeModelInfo", apiConfiguration.openAiModelInfo)
break
case "ollama":
await updateGlobalState(this.context, "previousModeModelId", apiConfiguration.ollamaModelId)
await updateWorkspaceState(this.context, "previousModeModelId", apiConfiguration.ollamaModelId)
break
case "lmstudio":
await updateGlobalState(this.context, "previousModeModelId", apiConfiguration.lmStudioModelId)
await updateWorkspaceState(this.context, "previousModeModelId", apiConfiguration.lmStudioModelId)
break
case "litellm":
await updateGlobalState(this.context, "previousModeModelId", apiConfiguration.liteLlmModelId)
await updateGlobalState(this.context, "previousModeModelInfo", apiConfiguration.liteLlmModelInfo)
await updateWorkspaceState(this.context, "previousModeModelId", apiConfiguration.liteLlmModelId)
await updateWorkspaceState(this.context, "previousModeModelInfo", apiConfiguration.liteLlmModelInfo)
break
case "requesty":
await updateGlobalState(this.context, "previousModeModelId", apiConfiguration.requestyModelId)
await updateGlobalState(this.context, "previousModeModelInfo", apiConfiguration.requestyModelInfo)
await updateWorkspaceState(this.context, "previousModeModelId", apiConfiguration.requestyModelId)
await updateWorkspaceState(this.context, "previousModeModelInfo", apiConfiguration.requestyModelInfo)
break
case "sapaicore":
await updateGlobalState(this.context, "previousModeModelId", apiConfiguration.apiModelId)
await updateGlobalState(this.context, "previousModeSapAiCoreModelId", apiConfiguration.sapAiCoreModelId)
await updateWorkspaceState(this.context, "previousModeModelId", apiConfiguration.apiModelId)
await updateWorkspaceState(this.context, "previousModeSapAiCoreClientId", apiConfiguration.sapAiCoreClientId)
await updateWorkspaceState(
this.context,
"previousModeSapAiCoreClientSecret",
apiConfiguration.sapAiCoreClientSecret,
)
await updateWorkspaceState(this.context, "previousModeSapAiCoreBaseUrl", apiConfiguration.sapAiCoreBaseUrl)
await updateWorkspaceState(this.context, "previousModeSapAiCoreTokenUrl", apiConfiguration.sapAiCoreTokenUrl)
await updateWorkspaceState(
this.context,
"previousModeSapAiCoreResourceGroup",
apiConfiguration.sapAiResourceGroup,
)
await updateWorkspaceState(this.context, "previousModeSapAiCoreModelId", apiConfiguration.sapAiCoreModelId)
break
}
@@ -336,9 +356,9 @@ export class Controller {
newReasoningEffort ||
newVsCodeLmModelSelector
) {
await updateGlobalState(this.context, "apiProvider", newApiProvider)
await updateGlobalState(this.context, "thinkingBudgetTokens", newThinkingBudgetTokens)
await updateGlobalState(this.context, "reasoningEffort", newReasoningEffort)
await updateWorkspaceState(this.context, "apiProvider", newApiProvider)
await updateWorkspaceState(this.context, "thinkingBudgetTokens", newThinkingBudgetTokens)
await updateWorkspaceState(this.context, "reasoningEffort", newReasoningEffort)
switch (newApiProvider) {
case "anthropic":
case "vertex":
@@ -348,42 +368,41 @@ export class Controller {
case "qwen":
case "deepseek":
case "xai":
await updateGlobalState(this.context, "apiModelId", newModelId)
await updateWorkspaceState(this.context, "apiModelId", newModelId)
break
case "bedrock":
await updateGlobalState(this.context, "apiModelId", newModelId)
await updateGlobalState(this.context, "awsBedrockCustomSelected", newAwsBedrockCustomSelected)
await updateGlobalState(this.context, "awsBedrockCustomModelBaseId", newAwsBedrockCustomModelBaseId)
await updateWorkspaceState(this.context, "apiModelId", newModelId)
await updateWorkspaceState(this.context, "awsBedrockCustomSelected", newAwsBedrockCustomSelected)
await updateWorkspaceState(this.context, "awsBedrockCustomModelBaseId", newAwsBedrockCustomModelBaseId)
break
case "openrouter":
case "cline":
await updateGlobalState(this.context, "openRouterModelId", newModelId)
await updateGlobalState(this.context, "openRouterModelInfo", newModelInfo)
await updateWorkspaceState(this.context, "openRouterModelId", newModelId)
await updateWorkspaceState(this.context, "openRouterModelInfo", newModelInfo)
break
case "vscode-lm":
await updateGlobalState(this.context, "vsCodeLmModelSelector", newVsCodeLmModelSelector)
await updateWorkspaceState(this.context, "vsCodeLmModelSelector", newVsCodeLmModelSelector)
break
case "openai":
await updateGlobalState(this.context, "openAiModelId", newModelId)
await updateGlobalState(this.context, "openAiModelInfo", newModelInfo)
await updateWorkspaceState(this.context, "openAiModelId", newModelId)
await updateWorkspaceState(this.context, "openAiModelInfo", newModelInfo)
break
case "ollama":
await updateGlobalState(this.context, "ollamaModelId", newModelId)
await updateWorkspaceState(this.context, "ollamaModelId", newModelId)
break
case "lmstudio":
await updateGlobalState(this.context, "lmStudioModelId", newModelId)
await updateWorkspaceState(this.context, "lmStudioModelId", newModelId)
break
case "litellm":
await updateGlobalState(this.context, "liteLlmModelId", newModelId)
await updateGlobalState(this.context, "liteLlmModelInfo", newModelInfo)
await updateWorkspaceState(this.context, "liteLlmModelId", newModelId)
await updateWorkspaceState(this.context, "liteLlmModelInfo", newModelInfo)
break
case "requesty":
await updateGlobalState(this.context, "requestyModelId", newModelId)
await updateGlobalState(this.context, "requestyModelInfo", newModelInfo)
await updateWorkspaceState(this.context, "requestyModelId", newModelId)
await updateWorkspaceState(this.context, "requestyModelInfo", newModelInfo)
break
case "sapaicore":
await updateGlobalState(this.context, "apiModelId", newModelId)
await updateGlobalState(this.context, "sapAiCoreModelId", newSapAiCoreModelId)
await updateWorkspaceState(this.context, "apiModelId", newModelId)
break
}
@@ -396,7 +415,7 @@ export class Controller {
// Save only non-mode properties to workspace storage
const { mode, ...persistentChatSettings }: { mode: string } & StoredChatSettings = chatSettings
await updateGlobalState(this.context, "chatSettings", persistentChatSettings)
await updateWorkspaceState(this.context, "chatSettings", persistentChatSettings)
await this.postStateToWebview()
if (this.task) {
@@ -470,10 +489,7 @@ export class Controller {
await sendAuthCallbackEvent(customToken)
const clineProvider: ApiProvider = "cline"
await updateGlobalState(this.context, "apiProvider", clineProvider)
// Mark welcome view as completed since user has successfully logged in
await updateGlobalState(this.context, "welcomeViewCompleted", true)
await updateWorkspaceState(this.context, "apiProvider", clineProvider)
// Update API configuration with the new provider and API key
const { apiConfiguration } = await getAllExtensionState(this.context)
@@ -632,7 +648,7 @@ export class Controller {
}
const openrouter: ApiProvider = "openrouter"
await updateGlobalState(this.context, "apiProvider", openrouter)
await updateWorkspaceState(this.context, "apiProvider", openrouter)
await storeSecret(this.context, "openRouterApiKey", apiKey)
await this.postStateToWebview()
if (this.task) {
@@ -832,7 +848,6 @@ export class Controller {
terminalReuseEnabled,
defaultTerminalProfile,
isNewUser,
welcomeViewCompleted,
mcpResponsesCollapsed,
terminalOutputLineLimit,
} = await getAllExtensionState(this.context)
@@ -887,7 +902,6 @@ export class Controller {
terminalReuseEnabled,
defaultTerminalProfile,
isNewUser,
welcomeViewCompleted: welcomeViewCompleted as boolean, // Can be undefined but is set to either true or false by the migration that runs on extension launch in extension.ts
mcpResponsesCollapsed,
terminalOutputLineLimit,
}
@@ -1,25 +0,0 @@
import type { BooleanRequest } from "../../../shared/proto/common"
import { Empty } from "../../../shared/proto/common"
import type { Controller } from "../index"
import { updateGlobalState } from "../../storage/state"
/**
* Sets the welcomeViewCompleted flag to the specified boolean value
* @param controller The controller instance
* @param request The boolean request containing the value to set
* @returns Empty response
*/
export async function setWelcomeViewCompleted(controller: Controller, request: BooleanRequest): Promise<Empty> {
try {
// Update the global state to set welcomeViewCompleted to the requested value
await updateGlobalState(controller.context, "welcomeViewCompleted", request.value)
await controller.postStateToWebview()
console.log(`Welcome view completed set to: ${request.value}`)
return Empty.create({})
} catch (error) {
console.error("Failed to set welcome view completed:", error)
throw error
}
}
@@ -1,6 +1,5 @@
import path from "path"
import fs from "fs/promises"
import vscode from "vscode"
import { Controller } from ".."
import { Empty, StringArrayRequest, BooleanRequest } from "../../../shared/proto/common"
import { TaskMethodHandler } from "./index"
@@ -21,18 +20,6 @@ export const deleteTasksWithIds: TaskMethodHandler = async (
throw new Error("Missing task IDs")
}
const taskCount = request.value.length
const message =
taskCount === 1
? "Are you sure you want to delete this task? This action cannot be undone."
: `Are you sure you want to delete these ${taskCount} tasks? This action cannot be undone.`
const userChoice = await vscode.window.showWarningMessage(message, { modal: true }, "Delete")
if (userChoice === undefined) {
return Empty.create()
}
for (const id of request.value) {
await deleteTaskWithId(controller, id)
}
+2 -2
View File
@@ -1,7 +1,7 @@
import type { Controller } from "../index"
import { EmptyRequest, Empty } from "@shared/proto/common"
import { handleModelsServiceRequest } from "../models"
import { getAllExtensionState, getGlobalState, updateGlobalState } from "../../storage/state"
import { getAllExtensionState, getGlobalState, updateWorkspaceState } from "../../storage/state"
import { sendOpenRouterModelsEvent } from "../models/subscribeToOpenRouterModels"
import { sendMcpMarketplaceCatalogEvent } from "../mcp/subscribeToMcpMarketplaceCatalog"
import { telemetryService } from "@/services/posthog/telemetry/TelemetryService"
@@ -32,7 +32,7 @@ export async function initializeWebview(controller: Controller, request: EmptyRe
// Update model info in state (this needs to be done here since we don't want to update state while settings is open, and we may refresh models there)
const { apiConfiguration } = await getAllExtensionState(controller.context)
if (apiConfiguration.openRouterModelId && response.models[apiConfiguration.openRouterModelId]) {
await updateGlobalState(
await updateWorkspaceState(
controller.context,
"openRouterModelInfo",
response.models[apiConfiguration.openRouterModelId],
@@ -234,9 +234,10 @@ In each user message, the environment_details will specify the current mode. The
## 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.
- Once you've gained more context about the user's request, you should architect a detailed plan for how you will 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.
====
+3 -2
View File
@@ -574,9 +574,10 @@ In each user message, the environment_details will specify the current mode. The
## 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 read_file or search_files to get more context about the task. You may also ask the user clarifying questions with ask_followup_question to get a better understanding of the task.
- Once you've gained more context about the user's request, you should architect a detailed plan for how you will accomplish the task. Present the plan to the user using the plan_mode_respond tool.
- When starting in PLAN MODE, depending on the user's request, you may need to do some information gathering e.g. using read_file or search_files to get more context about the task. You may also ask the user clarifying questions with ask_followup_question 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. Present the plan to the user using the plan_mode_respond tool.
- 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.
====
-3
View File
@@ -35,9 +35,6 @@ Otherwise, if you have not completed the task and do not need additional informa
tooManyMistakes: (feedback?: string) =>
`You seem to be having trouble proceeding. The user has provided the following feedback to help guide you:\n<feedback>\n${feedback}\n</feedback>`,
autoApprovalMaxReached: (feedback?: string) =>
`Auto-approval limit reached. The user has provided the following feedback to help guide you:\n<feedback>\n${feedback}\n</feedback>`,
missingToolParameterError: (paramName: string) =>
`Missing value for required parameter '${paramName}'. Please retry with complete response.\n\n${toolUseInstructionsReminder}`,
+3 -2
View File
@@ -568,9 +568,10 @@ In each user message, the environment_details will specify the current mode. The
## 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 read_file or search_files to get more context about the task. You may also ask the user clarifying questions to get a better understanding of the task.
- Once you've gained more context about the user's request, you should architect a detailed plan for how you will 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 read_file or search_files 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.
====
+11 -5
View File
@@ -71,14 +71,18 @@ export type GlobalStateKey =
| "terminalReuseEnabled"
| "defaultTerminalProfile"
| "isNewUser"
| "welcomeViewCompleted"
| "terminalOutputLineLimit"
| "mcpRichDisplayEnabled"
| "sapAiCoreTokenUrl"
| "sapAiCoreBaseUrl"
| "sapAiResourceGroup"
| "sapAiCoreClientId"
| "sapAiCoreClientSecret"
| "sapAiCoreModelId"
| "claudeCodePath"
// Settings around plan/act and ephemeral model configuration
export type LocalStateKey =
| "localClineRulesToggles"
| "chatSettings"
// Current active model configuration (per workspace)
| "apiProvider"
@@ -100,7 +104,6 @@ export type GlobalStateKey =
| "requestyModelInfo"
| "togetherModelId"
| "fireworksModelId"
| "sapAiCoreModelId"
// Previous mode saved configurations (per workspace)
| "previousModeApiProvider"
| "previousModeModelId"
@@ -110,6 +113,9 @@ export type GlobalStateKey =
| "previousModeReasoningEffort"
| "previousModeAwsBedrockCustomSelected"
| "previousModeAwsBedrockCustomModelBaseId"
| "previousModeSapAiCoreClientId"
| "previousModeSapAiCoreClientSecret"
| "previousModeSapAiCoreBaseUrl"
| "previousModeSapAiCoreTokenUrl"
| "previousModeSapAiCoreResourceGroup"
| "previousModeSapAiCoreModelId"
export type LocalStateKey = "localClineRulesToggles" | "localCursorRulesToggles" | "localWindsurfRulesToggles" | "workflowToggles"
+20 -95
View File
@@ -2,11 +2,11 @@ import * as vscode from "vscode"
import { ensureRulesDirectoryExists } from "./disk"
import fs from "fs/promises"
import path from "path"
import { updateGlobalState, getAllExtensionState, getGlobalState } from "./state"
import { getGlobalState, getWorkspaceState, updateGlobalState, updateWorkspaceState } from "./state"
import { GlobalStateKey } from "./state-keys"
export async function migrateWorkspaceToGlobalStorage(context: vscode.ExtensionContext) {
// Keys to migrate from workspace storage back to global storage
export async function migratePlanActGlobalToWorkspaceStorage(context: vscode.ExtensionContext) {
// Keys that were migrated from global storage to workspace storage
const keysToMigrate = [
// Core settings
"apiProvider",
@@ -31,7 +31,6 @@ export async function migrateWorkspaceToGlobalStorage(context: vscode.ExtensionC
"requestyModelInfo",
"togetherModelId",
"fireworksModelId",
"sapAiCoreModelId",
// Previous mode settings
"previousModeApiProvider",
@@ -42,24 +41,17 @@ export async function migrateWorkspaceToGlobalStorage(context: vscode.ExtensionC
"previousModeReasoningEffort",
"previousModeAwsBedrockCustomSelected",
"previousModeAwsBedrockCustomModelBaseId",
"previousModeSapAiCoreModelId",
]
for (const key of keysToMigrate) {
// Use raw workspace state since these keys shouldn't be in workspace storage
const workspaceValue = await context.workspaceState.get(key)
const globalValue = await context.globalState.get(key)
if (workspaceValue !== undefined && globalValue === undefined) {
console.log(`[Storage Migration] migrating key: ${key} to global storage. Current value: ${workspaceValue}`)
// Move to global storage
await updateGlobalState(context, key as GlobalStateKey, workspaceValue)
// Remove from workspace storage
await context.workspaceState.update(key, undefined)
const newWorkspaceValue = await context.workspaceState.get(key)
console.log(`[Storage Migration] migrated key: ${key} to global storage. Current value: ${newWorkspaceValue}`)
const globalValue = await getGlobalState(context, key as GlobalStateKey)
if (globalValue !== undefined) {
const workspaceValue = await getWorkspaceState(context, key)
if (workspaceValue === undefined) {
await updateWorkspaceState(context, key, globalValue)
}
// Delete from global storage regardless of whether we copied it
await updateGlobalState(context, key as GlobalStateKey, undefined)
}
}
}
@@ -134,89 +126,22 @@ export async function migrateCustomInstructionsToGlobalRules(context: vscode.Ext
export async function migrateModeFromWorkspaceStorageToControllerState(context: vscode.ExtensionContext) {
try {
// Check legacy workspace storage (use raw methods since chatSettings is now global)
const workspaceChatSettings = (await context.workspaceState.get("chatSettings")) as any
// Get current chatSettings from workspace storage
const chatSettings = (await getWorkspaceState(context, "chatSettings")) as any
if (workspaceChatSettings && typeof workspaceChatSettings === "object" && "mode" in workspaceChatSettings) {
console.log("Cleaning up mode from legacy workspace storage...")
if (chatSettings && typeof chatSettings === "object" && "mode" in chatSettings) {
console.log("Cleaning up mode from workspace storage...")
// Remove mode property from chatSettings
const { mode, ...cleanedChatSettings } = workspaceChatSettings
const { mode, ...cleanedChatSettings } = chatSettings
// Save cleaned chatSettings back to workspace storage (will be migrated later)
await context.workspaceState.update("chatSettings", cleanedChatSettings)
// Save cleaned chatSettings back to workspace storage
await updateWorkspaceState(context, "chatSettings", cleanedChatSettings)
console.log("Successfully removed mode from legacy workspace storage chatSettings")
}
// Also check global storage for any mode cleanup needed
const globalChatSettings = (await context.globalState.get("chatSettings")) as any
if (globalChatSettings && typeof globalChatSettings === "object" && "mode" in globalChatSettings) {
console.log("Cleaning up mode from global storage...")
// Remove mode property from chatSettings
const { mode, ...cleanedChatSettings } = globalChatSettings
// Save cleaned chatSettings back to global storage
await updateGlobalState(context, "chatSettings", cleanedChatSettings)
console.log("Successfully removed mode from global storage chatSettings")
console.log("Successfully removed mode from workspace storage chatSettings")
}
} catch (error) {
console.error("Failed to cleanup mode from storage:", error)
// Continue execution - migration failure shouldn't break extension startup
}
}
export async function migrateWelcomeViewCompleted(context: vscode.ExtensionContext) {
try {
// Check if welcomeViewCompleted is already set
const welcomeViewCompleted = await getGlobalState(context, "welcomeViewCompleted")
if (welcomeViewCompleted === undefined) {
console.log("Migrating welcomeViewCompleted setting...")
// Get all extension state to check for existing API keys
const extensionState = await getAllExtensionState(context)
const config = extensionState.apiConfiguration
// This is the original logic used for checking is the welcome view should be shown
// It was located in the ExtensionStateContextProvider
const hasKey = config
? [
config.apiKey,
config.openRouterApiKey,
config.awsRegion,
config.vertexProjectId,
config.openAiApiKey,
config.ollamaModelId,
config.lmStudioModelId,
config.liteLlmApiKey,
config.geminiApiKey,
config.openAiNativeApiKey,
config.deepSeekApiKey,
config.requestyApiKey,
config.togetherApiKey,
config.qwenApiKey,
config.doubaoApiKey,
config.mistralApiKey,
config.vsCodeLmModelSelector,
config.clineApiKey,
config.asksageApiKey,
config.xaiApiKey,
config.sambanovaApiKey,
config.sapAiCoreClientId,
].some((key) => key !== undefined)
: false
// Set welcomeViewCompleted based on whether user has keys
await updateGlobalState(context, "welcomeViewCompleted", hasKey)
console.log(`Migration: Set welcomeViewCompleted to ${hasKey} based on existing API keys`)
}
} catch (error) {
console.error("Failed to migrate welcomeViewCompleted:", error)
console.error("Failed to cleanup mode from workspace storage:", error)
// Continue execution - migration failure shouldn't break extension startup
}
}
+72 -59
View File
@@ -2,7 +2,7 @@ import * as vscode from "vscode"
import { DEFAULT_CHAT_SETTINGS } from "@shared/ChatSettings"
import { DEFAULT_BROWSER_SETTINGS } from "@shared/BrowserSettings"
import { DEFAULT_AUTO_APPROVAL_SETTINGS } from "@shared/AutoApprovalSettings"
import { GlobalStateKey, LocalStateKey, SecretKey } from "./state-keys"
import { GlobalStateKey, SecretKey } from "./state-keys"
import { ApiConfiguration, ApiProvider, BedrockModelId, ModelInfo } from "@shared/api"
import { HistoryItem } from "@shared/HistoryItem"
import { AutoApprovalSettings } from "@shared/AutoApprovalSettings"
@@ -44,18 +44,17 @@ export async function getSecret(context: vscode.ExtensionContext, key: SecretKey
// workspace
export async function updateWorkspaceState(context: vscode.ExtensionContext, key: LocalStateKey, value: any) {
export async function updateWorkspaceState(context: vscode.ExtensionContext, key: string, value: any) {
await context.workspaceState.update(key, value)
}
export async function getWorkspaceState(context: vscode.ExtensionContext, key: LocalStateKey) {
export async function getWorkspaceState(context: vscode.ExtensionContext, key: string) {
return await context.workspaceState.get(key)
}
export async function getAllExtensionState(context: vscode.ExtensionContext) {
const [
isNewUser,
welcomeViewCompleted,
apiKey,
openRouterApiKey,
clineApiKey,
@@ -125,10 +124,10 @@ export async function getAllExtensionState(context: vscode.ExtensionContext) {
sapAiCoreBaseUrl,
sapAiCoreTokenUrl,
sapAiResourceGroup,
sapAiCoreModelId,
claudeCodePath,
] = await Promise.all([
getGlobalState(context, "isNewUser") as Promise<boolean | undefined>,
getGlobalState(context, "welcomeViewCompleted") as Promise<boolean | undefined>,
getSecret(context, "apiKey") as Promise<string | undefined>,
getSecret(context, "openRouterApiKey") as Promise<string | undefined>,
getSecret(context, "clineApiKey") as Promise<string | undefined>,
@@ -198,6 +197,7 @@ export async function getAllExtensionState(context: vscode.ExtensionContext) {
getGlobalState(context, "sapAiCoreBaseUrl") as Promise<string | undefined>,
getGlobalState(context, "sapAiCoreTokenUrl") as Promise<string | undefined>,
getGlobalState(context, "sapAiResourceGroup") as Promise<string | undefined>,
getGlobalState(context, "sapAiCoreModelId") as Promise<string | undefined>,
getGlobalState(context, "claudeCodePath") as Promise<string | undefined>,
])
@@ -232,39 +232,47 @@ export async function getAllExtensionState(context: vscode.ExtensionContext) {
previousModeReasoningEffort,
previousModeAwsBedrockCustomSelected,
previousModeAwsBedrockCustomModelBaseId,
previousModeSapAiCoreClientId,
previousModeSapAiCoreClientSecret,
previousModeSapAiCoreBaseUrl,
previousModeSapAiCoreTokenUrl,
previousModeSapAiCoreResourceGroup,
previousModeSapAiCoreModelId,
sapAiCoreModelId,
] = await Promise.all([
getGlobalState(context, "chatSettings") as Promise<StoredChatSettings | undefined>,
getGlobalState(context, "apiProvider") as Promise<ApiProvider | undefined>,
getGlobalState(context, "apiModelId") as Promise<string | undefined>,
getGlobalState(context, "thinkingBudgetTokens") as Promise<number | undefined>,
getGlobalState(context, "reasoningEffort") as Promise<string | undefined>,
getGlobalState(context, "vsCodeLmModelSelector") as Promise<vscode.LanguageModelChatSelector | undefined>,
getGlobalState(context, "awsBedrockCustomSelected") as Promise<boolean | undefined>,
getGlobalState(context, "awsBedrockCustomModelBaseId") as Promise<BedrockModelId | undefined>,
getGlobalState(context, "openRouterModelId") as Promise<string | undefined>,
getGlobalState(context, "openRouterModelInfo") as Promise<ModelInfo | undefined>,
getGlobalState(context, "openAiModelId") as Promise<string | undefined>,
getGlobalState(context, "openAiModelInfo") as Promise<ModelInfo | undefined>,
getGlobalState(context, "ollamaModelId") as Promise<string | undefined>,
getGlobalState(context, "lmStudioModelId") as Promise<string | undefined>,
getGlobalState(context, "liteLlmModelId") as Promise<string | undefined>,
getGlobalState(context, "liteLlmModelInfo") as Promise<ModelInfo | undefined>,
getGlobalState(context, "requestyModelId") as Promise<string | undefined>,
getGlobalState(context, "requestyModelInfo") as Promise<ModelInfo | undefined>,
getGlobalState(context, "togetherModelId") as Promise<string | undefined>,
getGlobalState(context, "fireworksModelId") as Promise<string | undefined>,
getGlobalState(context, "previousModeApiProvider") as Promise<ApiProvider | undefined>,
getGlobalState(context, "previousModeModelId") as Promise<string | undefined>,
getGlobalState(context, "previousModeModelInfo") as Promise<ModelInfo | undefined>,
getGlobalState(context, "previousModeVsCodeLmModelSelector") as Promise<vscode.LanguageModelChatSelector | undefined>,
getGlobalState(context, "previousModeThinkingBudgetTokens") as Promise<number | undefined>,
getGlobalState(context, "previousModeReasoningEffort") as Promise<string | undefined>,
getGlobalState(context, "previousModeAwsBedrockCustomSelected") as Promise<boolean | undefined>,
getGlobalState(context, "previousModeAwsBedrockCustomModelBaseId") as Promise<BedrockModelId | undefined>,
getGlobalState(context, "previousModeSapAiCoreModelId") as Promise<string | undefined>,
getGlobalState(context, "sapAiCoreModelId") as Promise<string | undefined>,
getWorkspaceState(context, "chatSettings") as Promise<StoredChatSettings | undefined>,
getWorkspaceState(context, "apiProvider") as Promise<ApiProvider | undefined>,
getWorkspaceState(context, "apiModelId") as Promise<string | undefined>,
getWorkspaceState(context, "thinkingBudgetTokens") as Promise<number | undefined>,
getWorkspaceState(context, "reasoningEffort") as Promise<string | undefined>,
getWorkspaceState(context, "vsCodeLmModelSelector") as Promise<vscode.LanguageModelChatSelector | undefined>,
getWorkspaceState(context, "awsBedrockCustomSelected") as Promise<boolean | undefined>,
getWorkspaceState(context, "awsBedrockCustomModelBaseId") as Promise<BedrockModelId | undefined>,
getWorkspaceState(context, "openRouterModelId") as Promise<string | undefined>,
getWorkspaceState(context, "openRouterModelInfo") as Promise<ModelInfo | undefined>,
getWorkspaceState(context, "openAiModelId") as Promise<string | undefined>,
getWorkspaceState(context, "openAiModelInfo") as Promise<ModelInfo | undefined>,
getWorkspaceState(context, "ollamaModelId") as Promise<string | undefined>,
getWorkspaceState(context, "lmStudioModelId") as Promise<string | undefined>,
getWorkspaceState(context, "liteLlmModelId") as Promise<string | undefined>,
getWorkspaceState(context, "liteLlmModelInfo") as Promise<ModelInfo | undefined>,
getWorkspaceState(context, "requestyModelId") as Promise<string | undefined>,
getWorkspaceState(context, "requestyModelInfo") as Promise<ModelInfo | undefined>,
getWorkspaceState(context, "togetherModelId") as Promise<string | undefined>,
getWorkspaceState(context, "fireworksModelId") as Promise<string | undefined>,
getWorkspaceState(context, "previousModeApiProvider") as Promise<ApiProvider | undefined>,
getWorkspaceState(context, "previousModeModelId") as Promise<string | undefined>,
getWorkspaceState(context, "previousModeModelInfo") as Promise<ModelInfo | undefined>,
getWorkspaceState(context, "previousModeVsCodeLmModelSelector") as Promise<vscode.LanguageModelChatSelector | undefined>,
getWorkspaceState(context, "previousModeThinkingBudgetTokens") as Promise<number | undefined>,
getWorkspaceState(context, "previousModeReasoningEffort") as Promise<string | undefined>,
getWorkspaceState(context, "previousModeAwsBedrockCustomSelected") as Promise<boolean | undefined>,
getWorkspaceState(context, "previousModeAwsBedrockCustomModelBaseId") as Promise<BedrockModelId | undefined>,
getWorkspaceState(context, "previousModeSapAiCoreClientId") as Promise<string | undefined>,
getWorkspaceState(context, "previousModeSapAiCoreClientSecret") as Promise<string | undefined>,
getWorkspaceState(context, "previousModeSapAiCoreBaseUrl") as Promise<string | undefined>,
getWorkspaceState(context, "previousModeSapAiCoreTokenUrl") as Promise<string | undefined>,
getWorkspaceState(context, "previousModeSapAiCoreResourceGroup") as Promise<string | undefined>,
getWorkspaceState(context, "previousModeSapAiCoreModelId") as Promise<string | undefined>,
])
let apiProvider: ApiProvider
@@ -380,7 +388,6 @@ export async function getAllExtensionState(context: vscode.ExtensionContext) {
sapAiCoreModelId,
},
isNewUser: isNewUser ?? true,
welcomeViewCompleted,
lastShownAnnouncementId,
taskHistory,
autoApprovalSettings: autoApprovalSettings || DEFAULT_AUTO_APPROVAL_SETTINGS, // default value can be 0 or empty string
@@ -400,6 +407,11 @@ export async function getAllExtensionState(context: vscode.ExtensionContext) {
previousModeReasoningEffort,
previousModeAwsBedrockCustomSelected,
previousModeAwsBedrockCustomModelBaseId,
previousModeSapAiCoreClientId,
previousModeSapAiCoreClientSecret,
previousModeSapAiCoreBaseUrl,
previousModeSapAiCoreTokenUrl,
previousModeSapAiCoreResourceGroup,
previousModeSapAiCoreModelId,
mcpMarketplaceEnabled: mcpMarketplaceEnabled,
mcpRichDisplayEnabled: mcpRichDisplayEnabled ?? true,
@@ -490,28 +502,26 @@ export async function updateApiConfiguration(context: vscode.ExtensionContext, a
sapAiCoreModelId,
claudeCodePath,
} = apiConfiguration
// Ephemeral model config updates
await updateGlobalState(context, "apiProvider", apiProvider)
await updateGlobalState(context, "apiModelId", apiModelId)
await updateGlobalState(context, "thinkingBudgetTokens", thinkingBudgetTokens)
await updateGlobalState(context, "reasoningEffort", reasoningEffort)
await updateGlobalState(context, "vsCodeLmModelSelector", vsCodeLmModelSelector)
await updateGlobalState(context, "awsBedrockCustomSelected", awsBedrockCustomSelected)
await updateGlobalState(context, "awsBedrockCustomModelBaseId", awsBedrockCustomModelBaseId)
await updateGlobalState(context, "openRouterModelId", openRouterModelId)
await updateGlobalState(context, "openRouterModelInfo", openRouterModelInfo)
await updateGlobalState(context, "openAiModelId", openAiModelId)
await updateGlobalState(context, "openAiModelInfo", openAiModelInfo)
await updateGlobalState(context, "ollamaModelId", ollamaModelId)
await updateGlobalState(context, "lmStudioModelId", lmStudioModelId)
await updateGlobalState(context, "liteLlmModelId", liteLlmModelId)
await updateGlobalState(context, "liteLlmModelInfo", liteLlmModelInfo)
await updateGlobalState(context, "requestyModelId", requestyModelId)
await updateGlobalState(context, "requestyModelInfo", requestyModelInfo)
await updateGlobalState(context, "togetherModelId", togetherModelId)
await updateGlobalState(context, "fireworksModelId", fireworksModelId)
await updateGlobalState(context, "sapAiCoreModelId", sapAiCoreModelId)
// Workspace state updates
await updateWorkspaceState(context, "apiProvider", apiProvider)
await updateWorkspaceState(context, "apiModelId", apiModelId)
await updateWorkspaceState(context, "thinkingBudgetTokens", thinkingBudgetTokens)
await updateWorkspaceState(context, "reasoningEffort", reasoningEffort)
await updateWorkspaceState(context, "vsCodeLmModelSelector", vsCodeLmModelSelector)
await updateWorkspaceState(context, "awsBedrockCustomSelected", awsBedrockCustomSelected)
await updateWorkspaceState(context, "awsBedrockCustomModelBaseId", awsBedrockCustomModelBaseId)
await updateWorkspaceState(context, "openRouterModelId", openRouterModelId)
await updateWorkspaceState(context, "openRouterModelInfo", openRouterModelInfo)
await updateWorkspaceState(context, "openAiModelId", openAiModelId)
await updateWorkspaceState(context, "openAiModelInfo", openAiModelInfo)
await updateWorkspaceState(context, "ollamaModelId", ollamaModelId)
await updateWorkspaceState(context, "lmStudioModelId", lmStudioModelId)
await updateWorkspaceState(context, "liteLlmModelId", liteLlmModelId)
await updateWorkspaceState(context, "liteLlmModelInfo", liteLlmModelInfo)
await updateWorkspaceState(context, "requestyModelId", requestyModelId)
await updateWorkspaceState(context, "requestyModelInfo", requestyModelInfo)
await updateWorkspaceState(context, "togetherModelId", togetherModelId)
await updateWorkspaceState(context, "fireworksModelId", fireworksModelId)
// Global state updates
await updateGlobalState(context, "awsRegion", awsRegion)
@@ -539,9 +549,12 @@ export async function updateApiConfiguration(context: vscode.ExtensionContext, a
await updateGlobalState(context, "requestTimeoutMs", apiConfiguration.requestTimeoutMs)
await updateGlobalState(context, "fireworksModelMaxCompletionTokens", fireworksModelMaxCompletionTokens)
await updateGlobalState(context, "fireworksModelMaxTokens", fireworksModelMaxTokens)
await updateGlobalState(context, "favoritedModelIds", favoritedModelIds)
await updateGlobalState(context, "requestTimeoutMs", apiConfiguration.requestTimeoutMs)
await updateGlobalState(context, "sapAiCoreBaseUrl", sapAiCoreBaseUrl)
await updateGlobalState(context, "sapAiCoreTokenUrl", sapAiCoreTokenUrl)
await updateGlobalState(context, "sapAiResourceGroup", sapAiResourceGroup)
await updateGlobalState(context, "sapAiCoreModelId", sapAiCoreModelId)
await updateGlobalState(context, "claudeCodePath", claudeCodePath)
// Secret updates
+55 -50
View File
@@ -1,23 +1,17 @@
import { showSystemNotification } from "@/integrations/notifications"
import { listFiles } from "@/services/glob/list-files"
import { telemetryService } from "@/services/posthog/telemetry/TelemetryService"
import { regexSearchFiles } from "@/services/ripgrep"
import { parseSourceCodeForDefinitionsTopLevel } from "@/services/tree-sitter"
import { findLast, findLastIndex, parsePartialArrayString } from "@/shared/array"
import { createAndOpenGitHubIssue } from "@/utils/github-url-utils"
import { getReadablePath, isLocatedInWorkspace } from "@/utils/path"
import Anthropic from "@anthropic-ai/sdk"
import * as vscode from "vscode"
import { TaskState } from "./TaskState"
import { MessageStateHandler } from "./message-state"
import { ApiHandler } from "@api/index"
import { TerminalManager } from "@integrations/terminal/TerminalManager"
import { BrowserSession } from "@services/browser/BrowserSession"
import { DiffViewProvider } from "@integrations/editor/DiffViewProvider"
import { McpHub } from "@services/mcp/McpHub"
import { FileContextTracker } from "@core/context/context-tracking/FileContextTracker"
import { ClineIgnoreController } from "@core/ignore/ClineIgnoreController"
import { DiffViewProvider } from "@integrations/editor/DiffViewProvider"
import { extractTextFromFile, processFilesIntoText } from "@integrations/misc/extract-text"
import WorkspaceTracker from "@integrations/workspace/WorkspaceTracker"
import { BrowserSession } from "@services/browser/BrowserSession"
import { UrlContentFetcher } from "@services/browser/UrlContentFetcher"
import { McpHub } from "@services/mcp/McpHub"
import { AutoApprovalSettings } from "@shared/AutoApprovalSettings"
import { BrowserSettings } from "@shared/BrowserSettings"
import { ChatSettings } from "@shared/ChatSettings"
import { ToolParamName, ToolUse, ToolUseName } from "../assistant-message"
import { AutoApprove } from "./tools/autoApprove"
import {
BrowserAction,
BrowserActionResult,
@@ -31,29 +25,37 @@ import {
ClineSayTool,
COMPLETION_RESULT_CHANGES_FLAG,
} from "@shared/ExtensionMessage"
import WorkspaceTracker from "@integrations/workspace/WorkspaceTracker"
import { BrowserSettings } from "@shared/BrowserSettings"
import { ClineAskResponse } from "@shared/WebviewMessage"
import { COMMAND_REQ_APP_STRING } from "@shared/combineCommandSequences"
import { fileExistsAtPath } from "@utils/fs"
import { isClaude4ModelFamily, isGemini2dot5ModelFamily } from "@utils/model-utils"
import { fixModelHtmlEscaping, removeInvalidChars } from "@utils/string"
import { setTimeout as setTimeoutPromise } from "node:timers/promises"
import os from "os"
import * as path from "path"
import { serializeError } from "serialize-error"
import * as vscode from "vscode"
import { ToolResponse, USE_EXPERIMENTAL_CLAUDE4_FEATURES } from "."
import { ToolParamName, ToolUse, ToolUseName } from "../assistant-message"
import { constructNewFileContent } from "../assistant-message/diff"
import { ChangeLocation, StreamingJsonReplacer } from "../assistant-message/diff-json"
import { ContextManager } from "../context/context-management/ContextManager"
import { loadMcpDocumentation } from "../prompts/loadMcpDocumentation"
import { fileExistsAtPath } from "@utils/fs"
import { formatResponse } from "../prompts/responses"
import { ensureTaskDirectoryExists } from "../storage/disk"
import { getGlobalState, getWorkspaceState } from "../storage/state"
import { TaskState } from "./TaskState"
import { MessageStateHandler } from "./message-state"
import { AutoApprove } from "./tools/autoApprove"
import { isClaude4ModelFamily, isGemini2dot5ModelFamily } from "@utils/model-utils"
import { ToolResponse, USE_EXPERIMENTAL_CLAUDE4_FEATURES } from "."
import { serializeError } from "serialize-error"
import * as path from "path"
import { extractTextFromFile, processFilesIntoText } from "@integrations/misc/extract-text"
import { COMMAND_REQ_APP_STRING } from "@shared/combineCommandSequences"
import { UrlContentFetcher } from "@services/browser/UrlContentFetcher"
import { constructNewFileContent } from "../assistant-message/diff"
import { getReadablePath, isLocatedInWorkspace } from "@/utils/path"
import { listFiles } from "@/services/glob/list-files"
import { showNotificationForApprovalIfAutoApprovalEnabled } from "./utils"
import { parseSourceCodeForDefinitionsTopLevel } from "@/services/tree-sitter"
import { regexSearchFiles } from "@/services/ripgrep"
import { showSystemNotification } from "@/integrations/notifications"
import { findLast, findLastIndex, parsePartialArrayString } from "@/shared/array"
import { ensureTaskDirectoryExists } from "../storage/disk"
import { telemetryService } from "@/services/posthog/telemetry/TelemetryService"
import { loadMcpDocumentation } from "../prompts/loadMcpDocumentation"
import Anthropic from "@anthropic-ai/sdk"
import { createAndOpenGitHubIssue } from "@/utils/github-url-utils"
import { getWorkspaceState } from "../storage/state"
import os from "os"
import { ContextManager } from "../context/context-management/ContextManager"
import { setTimeout as setTimeoutPromise } from "node:timers/promises"
import { ChangeLocation, StreamingJsonReplacer } from "../assistant-message/diff-json"
export class ToolExecutor {
private autoApprover: AutoApprove
@@ -63,10 +65,7 @@ export class ToolExecutor {
return this.autoApprover.shouldAutoApproveTool(toolName)
}
private async shouldAutoApproveToolWithPath(
blockname: ToolUseName,
autoApproveActionpath: string | undefined,
): Promise<boolean> {
private shouldAutoApproveToolWithPath(blockname: ToolUseName, autoApproveActionpath: string | undefined): boolean {
return this.autoApprover.shouldAutoApproveToolWithPath(blockname, autoApproveActionpath)
}
@@ -76,6 +75,7 @@ export class ToolExecutor {
private taskState: TaskState,
private messageStateHandler: MessageStateHandler,
private api: ApiHandler,
private terminalManager: TerminalManager,
private urlContentFetcher: UrlContentFetcher,
private browserSession: BrowserSession,
private diffViewProvider: DiffViewProvider,
@@ -88,6 +88,7 @@ export class ToolExecutor {
// Configuration & Settings
private autoApprovalSettings: AutoApprovalSettings,
private browserSettings: BrowserSettings,
private chatSettings: ChatSettings,
private cwd: string,
private taskId: string,
@@ -105,6 +106,8 @@ export class ToolExecutor {
partial?: boolean,
) => Promise<{ response: ClineAskResponse; text?: string; images?: string[]; files?: string[] }>,
private saveCheckpoint: (isAttemptCompletionMessage?: boolean) => Promise<void>,
private reinitExistingTaskFromId: (taskId: string) => Promise<void>,
private cancelTask: () => Promise<void>,
private sayAndCreateMissingParamError: (toolName: ToolUseName, paramName: string, relPath?: string) => Promise<any>,
private removeLastPartialMessageIfExistsWithType: (type: "ask" | "say", askOrSay: ClineAsk | ClineSay) => Promise<void>,
private executeCommandTool: (command: string) => Promise<[boolean, any]>,
@@ -333,6 +336,8 @@ export class ToolExecutor {
// Handle write error
return { shouldBreak: true, error: `Write error: ${e}` }
}
const newContentParsed = this.taskState.streamingJsonReplacer.getSuccessfullyParsedItems()
}
return { shouldBreak: true } // Wait for more chunks
@@ -576,7 +581,7 @@ export class ToolExecutor {
// update gui message
const partialMessage = JSON.stringify(sharedMessageProps)
if (await this.shouldAutoApproveToolWithPath(block.name, relPath)) {
if (this.shouldAutoApproveToolWithPath(block.name, relPath)) {
this.removeLastPartialMessageIfExistsWithType("ask", "tool") // in case the user changes auto-approval settings mid stream
await this.say("tool", partialMessage, undefined, undefined, block.partial)
} else {
@@ -648,7 +653,7 @@ export class ToolExecutor {
// )
// : undefined,
} satisfies ClineSayTool)
if (await this.shouldAutoApproveToolWithPath(block.name, relPath)) {
if (this.shouldAutoApproveToolWithPath(block.name, relPath)) {
this.removeLastPartialMessageIfExistsWithType("ask", "tool")
await this.say("tool", completeMessage, undefined, undefined, false)
this.taskState.consecutiveAutoApprovedRequestsCount++
@@ -785,7 +790,7 @@ export class ToolExecutor {
content: undefined,
operationIsLocatedInWorkspace: await isLocatedInWorkspace(relPath),
} satisfies ClineSayTool)
if (await this.shouldAutoApproveToolWithPath(block.name, block.params.path)) {
if (this.shouldAutoApproveToolWithPath(block.name, block.params.path)) {
this.removeLastPartialMessageIfExistsWithType("ask", "tool")
await this.say("tool", partialMessage, undefined, undefined, block.partial)
} else {
@@ -816,7 +821,7 @@ export class ToolExecutor {
content: absolutePath,
operationIsLocatedInWorkspace: await isLocatedInWorkspace(relPath),
} satisfies ClineSayTool)
if (await this.shouldAutoApproveToolWithPath(block.name, block.params.path)) {
if (this.shouldAutoApproveToolWithPath(block.name, block.params.path)) {
this.removeLastPartialMessageIfExistsWithType("ask", "tool")
await this.say("tool", completeMessage, undefined, undefined, false) // need to be sending partialValue bool, since undefined has its own purpose in that the message is treated neither as a partial or completion of a partial, but as a single complete message
this.taskState.consecutiveAutoApprovedRequestsCount++
@@ -867,7 +872,7 @@ export class ToolExecutor {
content: "",
operationIsLocatedInWorkspace: await isLocatedInWorkspace(block.params.path),
} satisfies ClineSayTool)
if (await this.shouldAutoApproveToolWithPath(block.name, block.params.path)) {
if (this.shouldAutoApproveToolWithPath(block.name, block.params.path)) {
this.removeLastPartialMessageIfExistsWithType("ask", "tool")
await this.say("tool", partialMessage, undefined, undefined, block.partial)
} else {
@@ -899,7 +904,7 @@ export class ToolExecutor {
content: result,
operationIsLocatedInWorkspace: await isLocatedInWorkspace(block.params.path),
} satisfies ClineSayTool)
if (await this.shouldAutoApproveToolWithPath(block.name, block.params.path)) {
if (this.shouldAutoApproveToolWithPath(block.name, block.params.path)) {
this.removeLastPartialMessageIfExistsWithType("ask", "tool")
await this.say("tool", completeMessage, undefined, undefined, false)
this.taskState.consecutiveAutoApprovedRequestsCount++
@@ -942,7 +947,7 @@ export class ToolExecutor {
content: "",
operationIsLocatedInWorkspace: await isLocatedInWorkspace(block.params.path),
} satisfies ClineSayTool)
if (await this.shouldAutoApproveToolWithPath(block.name, block.params.path)) {
if (this.shouldAutoApproveToolWithPath(block.name, block.params.path)) {
this.removeLastPartialMessageIfExistsWithType("ask", "tool")
await this.say("tool", partialMessage, undefined, undefined, block.partial)
} else {
@@ -971,7 +976,7 @@ export class ToolExecutor {
content: result,
operationIsLocatedInWorkspace: await isLocatedInWorkspace(block.params.path),
} satisfies ClineSayTool)
if (await this.shouldAutoApproveToolWithPath(block.name, block.params.path)) {
if (this.shouldAutoApproveToolWithPath(block.name, block.params.path)) {
this.removeLastPartialMessageIfExistsWithType("ask", "tool")
await this.say("tool", completeMessage, undefined, undefined, false)
this.taskState.consecutiveAutoApprovedRequestsCount++
@@ -1018,7 +1023,7 @@ export class ToolExecutor {
content: "",
operationIsLocatedInWorkspace: await isLocatedInWorkspace(block.params.path),
} satisfies ClineSayTool)
if (await this.shouldAutoApproveToolWithPath(block.name, block.params.path)) {
if (this.shouldAutoApproveToolWithPath(block.name, block.params.path)) {
this.removeLastPartialMessageIfExistsWithType("ask", "tool")
await this.say("tool", partialMessage, undefined, undefined, block.partial)
} else {
@@ -1055,7 +1060,7 @@ export class ToolExecutor {
content: results,
operationIsLocatedInWorkspace: await isLocatedInWorkspace(block.params.path),
} satisfies ClineSayTool)
if (await this.shouldAutoApproveToolWithPath(block.name, block.params.path)) {
if (this.shouldAutoApproveToolWithPath(block.name, block.params.path)) {
this.removeLastPartialMessageIfExistsWithType("ask", "tool")
await this.say("tool", completeMessage, undefined, undefined, false)
this.taskState.consecutiveAutoApprovedRequestsCount++
@@ -1917,7 +1922,7 @@ export class ToolExecutor {
const clineVersion =
vscode.extensions.getExtension("saoudrizwan.claude-dev")?.packageJSON.version || "Unknown"
const systemInfo = `VSCode: ${vscode.version}, Node.js: ${process.version}, Architecture: ${os.arch()}`
const providerAndModel = `${await getGlobalState(this.context, "apiProvider")} / ${this.api.getModel().id}`
const providerAndModel = `${(await getWorkspaceState(this.context, "apiProvider")) as string} / ${this.api.getModel().id}`
// Ask user for confirmation
const bugReportData = JSON.stringify({
+31 -80
View File
@@ -26,11 +26,11 @@ import { getApiMetrics } from "@shared/getApiMetrics"
import { HistoryItem } from "@shared/HistoryItem"
import { DEFAULT_LANGUAGE_SETTINGS, getLanguageKey, LanguageDisplay } from "@shared/Languages"
import { ClineAskResponse, ClineCheckpointRestore } from "@shared/WebviewMessage"
import { getGitRemoteUrls } from "@utils/git"
import { arePathsEqual, getDesktopDir } from "@utils/path"
import { arePathsEqual } from "@utils/path"
import cloneDeep from "clone-deep"
import { execa } from "execa"
import { setTimeout as setTimeoutPromise } from "node:timers/promises"
import os from "os"
import pTimeout from "p-timeout"
import pWaitFor from "p-wait-for"
import * as path from "path"
@@ -69,7 +69,7 @@ import {
getSavedClineMessages,
GlobalFileNames,
} from "@core/storage/disk"
import { getGlobalState } from "@core/storage/state"
import { getWorkspaceState } from "@core/storage/state"
import { processFilesIntoText } from "@integrations/misc/extract-text"
import WorkspaceTracker from "@integrations/workspace/WorkspaceTracker"
import { McpHub } from "@services/mcp/McpHub"
@@ -85,6 +85,9 @@ import { formatErrorWithStatusCode, updateApiReqMsg } from "./utils"
export const USE_EXPERIMENTAL_CLAUDE4_FEATURES = false
export const cwd =
vscode.workspace.workspaceFolders?.map((folder) => folder.uri.fsPath).at(0) ?? path.join(os.homedir(), "Desktop") // may or may not exist but fs checking existence would immediately ask for permission which would be bad UX, need to come up with a better solution
export type ToolResponse = string | Array<Anthropic.TextBlockParam | Anthropic.ImageBlockParam>
type UserContent = Array<Anthropic.ContentBlockParam>
@@ -92,7 +95,6 @@ export class Task {
// Core task variables
readonly taskId: string
private taskIsFavorited?: boolean
private cwd: string
taskState: TaskState
@@ -149,7 +151,6 @@ export class Task {
terminalOutputLineLimit: number,
defaultTerminalProfile: string,
enableCheckpointsSetting: boolean,
cwd: string,
task?: string,
images?: string[],
files?: string[],
@@ -179,7 +180,6 @@ export class Task {
this.browserSettings = browserSettings
this.chatSettings = chatSettings
this.enableCheckpoints = enableCheckpointsSetting
this.cwd = cwd
// Set up MCP notification callback for real-time notifications
this.mcpHub.setNotificationCallback(async (serverName: string, level: string, message: string) => {
@@ -279,6 +279,7 @@ export class Task {
this.taskState,
this.messageStateHandler,
this.api,
this.terminalManager,
this.urlContentFetcher,
this.browserSession,
this.diffViewProvider,
@@ -289,11 +290,14 @@ export class Task {
this.contextManager,
this.autoApprovalSettings,
this.browserSettings,
this.chatSettings,
cwd,
this.taskId,
this.say.bind(this),
this.ask.bind(this),
this.saveCheckpoint.bind(this),
this.reinitExistingTaskFromId.bind(this),
this.cancelTask.bind(this),
this.sayAndCreateMissingParamError.bind(this),
this.removeLastPartialMessageIfExistsWithType.bind(this),
this.executeCommandTool.bind(this),
@@ -1096,7 +1100,7 @@ export class Task {
const [taskResumptionMessage, userResponseMessage] = formatResponse.taskResumption(
this.chatSettings?.mode === "plan" ? "plan" : "act",
agoText,
this.cwd,
cwd,
wasRecent,
responseText,
hasPendingFileContextWarnings,
@@ -1327,7 +1331,7 @@ export class Task {
// Create a child process
const childProcess = execa(command, {
shell: true,
cwd: this.cwd,
cwd,
reject: false,
all: true, // Merge stdout and stderr
})
@@ -1404,7 +1408,7 @@ export class Task {
}
Logger.info("Executing command in VS code terminal: " + command)
const terminalInfo = await this.terminalManager.getOrCreateTerminal(this.cwd)
const terminalInfo = await this.terminalManager.getOrCreateTerminal(cwd)
terminalInfo.terminal.show() // weird visual bug when creating new terminals (even manually) where there's an empty space at the top.
const process = this.terminalManager.runCommand(terminalInfo, command)
@@ -1436,10 +1440,7 @@ export class Task {
try {
const { response, text, images, files } = await this.ask("command_output", chunk)
if (response === "yesButtonClicked") {
// proceed while running - but still capture user feedback if provided
if (text || (images && images.length > 0) || (files && files.length > 0)) {
userFeedback = { text, images, files }
}
// proceed while running
} else {
userFeedback = { text, images, files }
}
@@ -1580,7 +1581,7 @@ export class Task {
const supportsBrowserUse = modelSupportsBrowserUse && !disableBrowserTool // only enable browser use if the model supports it and the user hasn't disabled it
const isNextGenModel = isClaude4ModelFamily(this.api) || isGemini2dot5ModelFamily(this.api)
let systemPrompt = await SYSTEM_PROMPT(this.cwd, supportsBrowserUse, this.mcpHub, this.browserSettings, isNextGenModel)
let systemPrompt = await SYSTEM_PROMPT(cwd, supportsBrowserUse, this.mcpHub, this.browserSettings, isNextGenModel)
await this.migratePreferredLanguageToolSetting()
const preferredLanguage = getLanguageKey(this.chatSettings.preferredLanguage as LanguageDisplay)
@@ -1589,18 +1590,18 @@ export class Task {
? `# Preferred Language\n\nSpeak in ${preferredLanguage}.`
: ""
const { globalToggles, localToggles } = await refreshClineRulesToggles(this.getContext(), this.cwd)
const { windsurfLocalToggles, cursorLocalToggles } = await refreshExternalRulesToggles(this.getContext(), this.cwd)
const { globalToggles, localToggles } = await refreshClineRulesToggles(this.getContext(), cwd)
const { windsurfLocalToggles, cursorLocalToggles } = await refreshExternalRulesToggles(this.getContext(), cwd)
const globalClineRulesFilePath = await ensureRulesDirectoryExists()
const globalClineRulesFileInstructions = await getGlobalClineRules(globalClineRulesFilePath, globalToggles)
const localClineRulesFileInstructions = await getLocalClineRules(this.cwd, localToggles)
const localClineRulesFileInstructions = await getLocalClineRules(cwd, localToggles)
const [localCursorRulesFileInstructions, localCursorRulesDirInstructions] = await getLocalCursorRules(
this.cwd,
cwd,
cursorLocalToggles,
)
const localWindsurfRulesFileInstructions = await getLocalWindsurfRules(this.cwd, windsurfLocalToggles)
const localWindsurfRulesFileInstructions = await getLocalWindsurfRules(cwd, windsurfLocalToggles)
const clineIgnoreContent = this.clineIgnoreController.clineIgnoreContent
let clineIgnoreInstructions: string | undefined
@@ -1872,7 +1873,7 @@ export class Task {
}
// Used to know what models were used in the task if user wants to export metadata for error reporting purposes
const currentProviderId = (await getGlobalState(this.getContext(), "apiProvider")) as string
const currentProviderId = (await getWorkspaceState(this.getContext(), "apiProvider")) as string
if (currentProviderId && this.api.getModel().id) {
try {
await this.modelContextTracker.recordModelUsage(currentProviderId, this.api.getModel().id, this.chatSettings.mode)
@@ -1930,42 +1931,12 @@ export class Task {
message: `Cline has auto-approved ${this.autoApprovalSettings.maxRequests.toString()} API requests.`,
})
}
const { response, text, images, files } = await this.ask(
await this.ask(
"auto_approval_max_req_reached",
`Cline has auto-approved ${this.autoApprovalSettings.maxRequests.toString()} API requests. Would you like to reset the count and proceed with the task?`,
)
// if we get past the promise it means the user approved and did not start a new task
this.taskState.consecutiveAutoApprovedRequestsCount = 0
// Process user feedback if provided
if (response === "messageResponse") {
// Display the user's message in the chat UI
await this.say("user_feedback", text, images, files)
// This userContent is for the *next* API call.
const feedbackUserContent: UserContent = []
feedbackUserContent.push({
type: "text",
text: formatResponse.autoApprovalMaxReached(text),
})
if (images && images.length > 0) {
feedbackUserContent.push(...formatResponse.imageBlocks(images))
}
let fileContentString = ""
if (files && files.length > 0) {
fileContentString = await processFilesIntoText(files)
}
if (fileContentString) {
feedbackUserContent.push({
type: "text",
text: fileContentString,
})
}
userContent = feedbackUserContent
}
}
// get previous api req's index to check token usage and determine if we need to truncate conversation history
@@ -2124,13 +2095,6 @@ export class Task {
this.api.getModel().id,
"assistant",
true,
{
tokensIn: inputTokens,
tokensOut: outputTokens,
cacheWriteTokens,
cacheReadTokens,
totalCost,
},
)
// signals to provider that it can retrieve the saved messages from disk, as abortTask can not be awaited on in nature
@@ -2304,13 +2268,6 @@ export class Task {
this.api.getModel().id,
"assistant",
true,
{
tokensIn: inputTokens,
tokensOut: outputTokens,
cacheWriteTokens,
cacheReadTokens,
totalCost,
},
)
await this.messageStateHandler.addToApiConversationHistory({
@@ -2370,7 +2327,7 @@ export class Task {
// Track if we need to check clinerulesFile
let needsClinerulesFileCheck = false
const { localWorkflowToggles, globalWorkflowToggles } = await refreshWorkflowToggles(this.getContext(), this.cwd)
const { localWorkflowToggles, globalWorkflowToggles } = await refreshWorkflowToggles(this.getContext(), cwd)
const processUserContent = async () => {
// This is a temporary solution to dynamically load context mentions from tool results. It checks for the presence of tags that indicate that the tool was rejected and feedback was provided (see formatToolDeniedFeedback, attemptCompletion, executeCommand, and consecutiveMistakeCount >= 3) or "<answer>" (see askFollowupQuestion), we place all user generated content in these tags so they can effectively be used as markers for when we should parse mentions). However if we allow multiple tools responses in the future, we will need to parse mentions specifically within the user content tags.
@@ -2388,7 +2345,7 @@ export class Task {
) {
const parsedText = await parseMentions(
block.text,
this.cwd,
cwd,
this.urlContentFetcher,
this.fileContextTracker,
)
@@ -2424,7 +2381,7 @@ export class Task {
// After processing content, check clinerulesData if needed
let clinerulesError = false
if (needsClinerulesFileCheck) {
clinerulesError = await ensureLocalClineDirExists(this.cwd, GlobalFileNames.clineRules)
clinerulesError = await ensureLocalClineDirExists(cwd, GlobalFileNames.clineRules)
}
// Return all results
@@ -2439,7 +2396,7 @@ export class Task {
const visibleFilePaths = vscode.window.visibleTextEditors
?.map((editor) => editor.document?.uri?.fsPath)
.filter(Boolean)
.map((absolutePath) => path.relative(this.cwd, absolutePath))
.map((absolutePath) => path.relative(cwd, absolutePath))
// Filter paths through clineIgnoreController
const allowedVisibleFiles = this.clineIgnoreController
@@ -2458,7 +2415,7 @@ export class Task {
.flatMap((group) => group.tabs)
.map((tab) => (tab.input as vscode.TabInputText)?.uri?.fsPath)
.filter(Boolean)
.map((absolutePath) => path.relative(this.cwd, absolutePath))
.map((absolutePath) => path.relative(cwd, absolutePath))
// Filter paths through clineIgnoreController
const allowedOpenTabs = this.clineIgnoreController
@@ -2584,22 +2541,16 @@ export class Task {
details += `\n\n# Current Time\n${formatter.format(now)} (${timeZone}, UTC${timeZoneOffsetStr})`
if (includeFileDetails) {
details += `\n\n# Current Working Directory (${this.cwd.toPosix()}) Files\n`
const isDesktop = arePathsEqual(this.cwd, getDesktopDir())
details += `\n\n# Current Working Directory (${cwd.toPosix()}) Files\n`
const isDesktop = arePathsEqual(cwd, path.join(os.homedir(), "Desktop"))
if (isDesktop) {
// don't want to immediately access desktop since it would show permission popup
details += "(Desktop files not shown automatically. Use list_files to explore if needed.)"
} else {
const [files, didHitLimit] = await listFiles(this.cwd, true, 200)
const result = formatResponse.formatFilesList(this.cwd, files, didHitLimit, this.clineIgnoreController)
const [files, didHitLimit] = await listFiles(cwd, true, 200)
const result = formatResponse.formatFilesList(cwd, files, didHitLimit, this.clineIgnoreController)
details += result
}
// Add git remote URLs section
const gitRemotes = await getGitRemoteUrls(this.cwd)
if (gitRemotes.length > 0) {
details += `\n\n# Git Remote URLs\n${gitRemotes.join("\n")}`
}
}
// Add context window usage information
+2 -2
View File
@@ -12,7 +12,7 @@ import CheckpointTracker from "@integrations/checkpoints/CheckpointTracker"
import { HistoryItem } from "@/shared/HistoryItem"
import Anthropic from "@anthropic-ai/sdk"
import { TaskState } from "./TaskState"
import { getCwd, getDesktopDir } from "@/utils/path"
import { getCwd } from "@/utils/path"
interface MessageStateHandlerParams {
context: vscode.ExtensionContext
@@ -83,7 +83,7 @@ export class MessageStateHandler {
} catch (error) {
console.error("Failed to get task directory size:", taskDir, error)
}
const cwd = await getCwd(getDesktopDir())
const cwd = await getCwd(path.join(os.homedir(), "Desktop"))
await this.updateTaskHistory({
id: this.taskId,
ts: lastRelevantMessage.ts,
+5 -3
View File
@@ -1,8 +1,11 @@
import { AutoApprovalSettings } from "@shared/AutoApprovalSettings"
import { ToolUseName } from "@core/assistant-message"
import * as path from "path"
import * as vscode from "vscode"
import os from "os"
import { getCwd, getDesktopDir } from "@/utils/path"
export const cwd =
vscode.workspace.workspaceFolders?.map((folder) => folder.uri.fsPath).at(0) ?? path.join(os.homedir(), "Desktop")
export class AutoApprove {
autoApprovalSettings: AutoApprovalSettings
@@ -51,10 +54,9 @@ export class AutoApprove {
// Check if the tool should be auto-approved based on the settings
// and the path of the action. Returns true if the tool should be auto-approved
// based on the user's settings and the path of the action.
async shouldAutoApproveToolWithPath(blockname: ToolUseName, autoApproveActionpath: string | undefined): Promise<boolean> {
shouldAutoApproveToolWithPath(blockname: ToolUseName, autoApproveActionpath: string | undefined): boolean {
let isLocalRead: boolean = false
if (autoApproveActionpath) {
const cwd = await getCwd(getDesktopDir())
const absolutePath = path.resolve(cwd, autoApproveActionpath)
isLocalRead = absolutePath.startsWith(cwd)
} else {
+4 -16
View File
@@ -23,10 +23,9 @@ import { WebviewProviderType } from "./shared/webview/types"
import { sendHistoryButtonClickedEvent } from "./core/controller/ui/subscribeToHistoryButtonClicked"
import { sendAccountButtonClickedEvent } from "./core/controller/ui/subscribeToAccountButtonClicked"
import {
migrateWorkspaceToGlobalStorage,
migratePlanActGlobalToWorkspaceStorage,
migrateCustomInstructionsToGlobalRules,
migrateModeFromWorkspaceStorageToControllerState,
migrateWelcomeViewCompleted,
} from "./core/storage/state-migrations"
import { sendFocusChatInputEvent } from "./core/controller/ui/subscribeToFocusChatInput"
@@ -60,18 +59,15 @@ export async function activate(context: vscode.ExtensionContext) {
maybeSetupHostProviders(context)
// Migrate global storage values to workspace storage (one-time cleanup)
await migratePlanActGlobalToWorkspaceStorage(context)
// Migrate custom instructions to global Cline rules (one-time cleanup)
await migrateCustomInstructionsToGlobalRules(context)
// Migrate mode from workspace storage to controller state (one-time cleanup)
await migrateModeFromWorkspaceStorageToControllerState(context)
// Migrate welcomeViewCompleted setting based on existing API keys (one-time cleanup)
await migrateWelcomeViewCompleted(context)
// Migrate workspace storage values back to global storage (reverting previous migration)
await migrateWorkspaceToGlobalStorage(context)
// Clean up orphaned file context warnings (startup cleanup)
await FileContextTracker.cleanupOrphanedWarnings(context)
@@ -644,14 +640,6 @@ export async function activate(context: vscode.ExtensionContext) {
}),
)
// Register the openWalkthrough command handler
context.subscriptions.push(
vscode.commands.registerCommand("cline.openWalkthrough", async () => {
await vscode.commands.executeCommand("workbench.action.openWalkthrough", "saoudrizwan.claude-dev#ClineWalkthrough")
telemetryService.captureButtonClick("command_openWalkthrough", undefined, true)
}),
)
// Register the generateGitCommitMessage command handler
context.subscriptions.push(
vscode.commands.registerCommand("cline.generateGitCommitMessage", async () => {
-2
View File
@@ -3,7 +3,6 @@ import {
WatchServiceClientInterface,
WorkspaceServiceClientInterface,
EnvServiceClientInterface,
WindowServiceClientInterface,
} from "@generated/hosts/host-bridge-client-types"
/**
@@ -14,7 +13,6 @@ export interface HostBridgeClientProvider {
watchServiceClient: WatchServiceClientInterface
workspaceClient: WorkspaceServiceClientInterface
envClient: EnvServiceClientInterface
windowClient: WindowServiceClientInterface
}
/**
@@ -7,5 +7,4 @@ export const vscodeHostBridgeClient: HostBridgeClientProvider = {
watchServiceClient: createGrpcClient(host.WatchServiceDefinition),
workspaceClient: createGrpcClient(host.WorkspaceServiceDefinition),
envClient: createGrpcClient(host.EnvServiceDefinition),
windowClient: createGrpcClient(host.WindowServiceDefinition),
}
@@ -1,27 +0,0 @@
import * as vscode from "vscode"
import { ShowOpenDialogueRequest, SelectedResources } from "@/shared/proto/host/window"
export async function showOpenDialogue(request: ShowOpenDialogueRequest): Promise<SelectedResources> {
const options: vscode.OpenDialogOptions = {}
if (request.canSelectMany !== undefined) {
options.canSelectMany = request.canSelectMany
}
if (request.openLabel !== undefined) {
options.openLabel = request.openLabel
}
if (request.filters?.files) {
options.filters = {
Files: request.filters.files,
}
}
const selectedResources = await vscode.window.showOpenDialog(options)
// Convert back to path format
return SelectedResources.create({
paths: selectedResources ? selectedResources.map((uri) => uri.fsPath) : [],
})
}
@@ -1,26 +0,0 @@
import * as vscode from "vscode"
import { ShowTextDocumentRequest, TextEditorInfo } from "@/shared/proto/host/window"
export async function showTextDocument(request: ShowTextDocumentRequest): Promise<TextEditorInfo> {
// Convert file path to URI
const uri = vscode.Uri.file(request.path)
const options: vscode.TextDocumentShowOptions = {}
if (request.options?.preview !== undefined) {
options.preview = request.options.preview
}
if (request.options?.preserveFocus !== undefined) {
options.preserveFocus = request.options.preserveFocus
}
if (request.options?.viewColumn !== undefined) {
options.viewColumn = request.options.viewColumn
}
const editor = await vscode.window.showTextDocument(uri, options)
return TextEditorInfo.create({
documentPath: editor.document.uri.fsPath,
viewColumn: editor.viewColumn,
isActive: vscode.window.activeTextEditor === editor,
})
}
@@ -0,0 +1,73 @@
import * as vscode from "vscode"
import fs from "fs/promises"
import path from "path"
import os from "os"
import CheckpointTracker from "./CheckpointTracker"
export async function createTestEnvironment() {
// Create temp directory structure
const tempDir = path.join(os.tmpdir(), `checkpoint-test-${Date.now()}`)
await fs.mkdir(tempDir, { recursive: true })
// Create storage path outside of working directory to avoid submodule issues
const globalStoragePath = path.join(os.tmpdir(), `storage-${Date.now()}`)
await fs.mkdir(globalStoragePath, { recursive: true })
// Create test file in a subdirectory
const testDir = path.join(tempDir, "src")
await fs.mkdir(testDir, { recursive: true })
const testFilePath = path.join(testDir, "test.txt")
// Create .gitignore to prevent git from treating directories as submodules
await fs.writeFile(path.join(tempDir, ".gitignore"), "storage/\n")
// Mock VS Code workspace
const mockWorkspaceFolders = [
{
uri: { fsPath: tempDir },
name: "test",
index: 0,
},
]
const originalDescriptor = Object.getOwnPropertyDescriptor(vscode.workspace, "workspaceFolders")
Object.defineProperty(vscode.workspace, "workspaceFolders", {
get: () => mockWorkspaceFolders,
})
// Mock findFiles to return no nested git repos
const originalFindFiles = vscode.workspace.findFiles
vscode.workspace.findFiles = async () => []
// Mock VS Code configuration
const originalGetConfiguration = vscode.workspace.getConfiguration
vscode.workspace.getConfiguration = () =>
({
get: (key: string) => (key === "enableCheckpoints" ? true : undefined),
}) as any
return {
tempDir,
globalStoragePath,
testFilePath,
originalDescriptor,
originalFindFiles,
originalGetConfiguration,
cleanup: async () => {
// Restore VS Code mocks
if (originalDescriptor) {
Object.defineProperty(vscode.workspace, "workspaceFolders", originalDescriptor)
}
vscode.workspace.getConfiguration = originalGetConfiguration
vscode.workspace.findFiles = originalFindFiles
// Clean up temp directories
await fs.rm(tempDir, { recursive: true, force: true })
await fs.rm(globalStoragePath, { recursive: true, force: true })
}
}
}
export async function createTestTracker(globalStoragePath?: string, taskId = "test-task-1") {
return await CheckpointTracker.create(taskId, globalStoragePath)
}
@@ -0,0 +1,155 @@
import { expect } from "chai"
import { describe, it, beforeEach, afterEach } from "mocha"
import fs from "fs/promises"
import path from "path"
import { createTestEnvironment, createTestTracker } from "./Checkpoint-test-utils"
describe("Checkpoint Commit Operations", () => {
let env: Awaited<ReturnType<typeof createTestEnvironment>>
beforeEach(async () => {
env = await createTestEnvironment()
})
afterEach(async () => {
await env.cleanup()
})
it("should create commit with single file changes", async () => {
const tracker = await createTestTracker(env.globalStoragePath)
if (!tracker) {throw new Error("Failed to create tracker")}
// Create initial file
await fs.writeFile(env.testFilePath, "initial content")
// Create first commit
const firstCommit = await tracker.commit()
expect(firstCommit).to.be.a("string").and.not.empty
// Modify file
await fs.writeFile(env.testFilePath, "modified content")
// Create second commit
const secondCommit = await tracker.commit()
expect(secondCommit).to.be.a("string").and.not.empty
expect(secondCommit).to.not.equal(firstCommit)
// Verify commits are different
const diffSet = await tracker.getDiffSet(firstCommit, secondCommit)
expect(diffSet).to.have.lengthOf(1)
expect(diffSet[0].before).to.equal("initial content")
expect(diffSet[0].after).to.equal("modified content")
})
it("should create commit with multiple file changes", async () => {
const tracker = await createTestTracker(env.globalStoragePath)
if (!tracker) {throw new Error("Failed to create tracker")}
// Create initial files with newlines
const testFile2Path = path.join(env.tempDir, "src", "test2.txt")
await fs.writeFile(env.testFilePath, "file1 initial\n")
await fs.writeFile(testFile2Path, "file2 initial\n")
// Create first commit
const firstCommit = await tracker.commit()
expect(firstCommit).to.be.a("string").and.not.empty
// Modify both files with newlines
await fs.writeFile(env.testFilePath, "file1 modified\n")
await fs.writeFile(testFile2Path, "file2 modified\n")
// Create second commit
const secondCommit = await tracker.commit()
expect(secondCommit).to.be.a("string").and.not.empty
expect(secondCommit).to.not.equal(firstCommit)
// Get diff between commits
const diffSet = await tracker.getDiffSet(firstCommit, secondCommit)
expect(diffSet).to.have.lengthOf(2)
// Sort diffSet by path for consistent ordering
const sortedDiffs = diffSet.sort((a, b) => a.relativePath.localeCompare(b.relativePath))
// Verify file paths
expect(sortedDiffs[0].relativePath).to.equal("src/test.txt")
expect(sortedDiffs[1].relativePath).to.equal("src/test2.txt")
// Verify file contents
expect(sortedDiffs[0].before).to.equal("file1 initial\n")
expect(sortedDiffs[0].after).to.equal("file1 modified\n")
expect(sortedDiffs[1].before).to.equal("file2 initial\n")
expect(sortedDiffs[1].after).to.equal("file2 modified\n")
})
it("should create commit when files are deleted", async () => {
const tracker = await createTestTracker(env.globalStoragePath)
if (!tracker) {throw new Error("Failed to create tracker")}
// Create and commit initial file
await fs.writeFile(env.testFilePath, "initial content")
const firstCommit = await tracker.commit()
expect(firstCommit).to.be.a("string").and.not.empty
// Delete file
await fs.unlink(env.testFilePath)
// Create second commit
const secondCommit = await tracker.commit()
expect(secondCommit).to.be.a("string").and.not.empty
expect(secondCommit).to.not.equal(firstCommit)
// Verify file deletion was committed
const diffSet = await tracker.getDiffSet(firstCommit, secondCommit)
expect(diffSet).to.have.lengthOf(1)
expect(diffSet[0].before).to.equal("initial content")
expect(diffSet[0].after).to.equal("")
})
it("should create empty commit when no changes", async () => {
const tracker = await createTestTracker(env.globalStoragePath)
if (!tracker) {throw new Error("Failed to create tracker")}
// Create and commit initial file
await fs.writeFile(env.testFilePath, "test content")
const firstCommit = await tracker.commit()
expect(firstCommit).to.be.a("string").and.not.empty
// Create commit without changes
const secondCommit = await tracker.commit()
expect(secondCommit).to.be.a("string").and.not.empty
expect(secondCommit).to.not.equal(firstCommit)
// Verify no changes between commits
const diffSet = await tracker.getDiffSet(firstCommit, secondCommit)
expect(diffSet).to.have.lengthOf(0)
})
it("should handle files in nested directories", async () => {
const tracker = await createTestTracker(env.globalStoragePath)
if (!tracker) {throw new Error("Failed to create tracker")}
// Create nested directory structure
const nestedDir = path.join(env.tempDir, "src", "deep", "nested")
await fs.mkdir(nestedDir, { recursive: true })
const nestedFilePath = path.join(nestedDir, "nested.txt")
// Create and commit file in nested directory
await fs.writeFile(nestedFilePath, "nested content")
const firstCommit = await tracker.commit()
expect(firstCommit).to.be.a("string").and.not.empty
// Modify nested file
await fs.writeFile(nestedFilePath, "modified nested content")
// Create second commit
const secondCommit = await tracker.commit()
expect(secondCommit).to.be.a("string").and.not.empty
// Verify changes were committed
const diffSet = await tracker.getDiffSet(firstCommit, secondCommit)
expect(diffSet).to.have.lengthOf(1)
expect(diffSet[0].relativePath).to.equal("src/deep/nested/nested.txt")
expect(diffSet[0].before).to.equal("nested content")
expect(diffSet[0].after).to.equal("modified nested content")
})
})
@@ -0,0 +1,35 @@
import { expect } from "chai"
import { describe, it, beforeEach, afterEach } from "mocha"
import { createTestEnvironment, createTestTracker } from "./Checkpoint-test-utils"
import CheckpointTracker from "./CheckpointTracker"
describe("Checkpoint Creation", () => {
let env: Awaited<ReturnType<typeof createTestEnvironment>>
beforeEach(async () => {
env = await createTestEnvironment()
})
afterEach(async () => {
await env.cleanup()
})
it("should create a new checkpoint tracker", async () => {
const tracker = await createTestTracker(env.globalStoragePath)
expect(tracker).to.not.be.undefined
expect(tracker).to.be.instanceOf(CheckpointTracker)
// Verify shadow git config
const configWorkTree = await tracker?.getShadowGitConfigWorkTree()
expect(configWorkTree).to.not.be.undefined
})
it("should throw error when globalStoragePath is missing", async () => {
try {
await createTestTracker(undefined)
expect.fail("Expected error was not thrown")
} catch (error: any) {
expect(error.message).to.equal("Global storage path is required to create a checkpoint tracker")
}
})
})
@@ -0,0 +1,68 @@
import { expect } from "chai"
import { describe, it, beforeEach, afterEach } from "mocha"
import fs from "fs/promises"
import { createTestEnvironment, createTestTracker } from "./Checkpoint-test-utils"
describe("Checkpoint Diff Operations", () => {
let env: Awaited<ReturnType<typeof createTestEnvironment>>
beforeEach(async () => {
env = await createTestEnvironment()
})
afterEach(async () => {
await env.cleanup()
})
it("should detect file changes between commits", async () => {
const tracker = await createTestTracker(env.globalStoragePath)
if (!tracker) {throw new Error("Failed to create tracker")}
// Create initial file
await fs.writeFile(env.testFilePath, "initial content")
// Create first checkpoint
const firstCommit = await tracker.commit()
expect(firstCommit).to.not.be.undefined
// Modify file
await fs.writeFile(env.testFilePath, "modified content")
// Create second checkpoint
const secondCommit = await tracker.commit()
expect(secondCommit).to.not.be.undefined
// Get diff between commits
const diffSet = await tracker.getDiffSet(firstCommit, secondCommit)
// Verify diff results
expect(diffSet).to.have.lengthOf(1)
expect(diffSet[0].relativePath).to.equal("src/test.txt")
expect(diffSet[0].before).to.equal("initial content")
expect(diffSet[0].after).to.equal("modified content")
})
it("should detect changes between commit and working directory", async () => {
const tracker = await createTestTracker(env.globalStoragePath)
if (!tracker) {throw new Error("Failed to create tracker")}
// Create initial file
await fs.writeFile(env.testFilePath, "initial content")
// Create checkpoint
const commit = await tracker.commit()
expect(commit).to.not.be.undefined
// Modify file without committing
await fs.writeFile(env.testFilePath, "working directory changes")
// Get diff between commit and working directory
const diffSet = await tracker.getDiffSet(commit)
// Verify diff results
expect(diffSet).to.have.lengthOf(1)
expect(diffSet[0].relativePath).to.equal("src/test.txt")
expect(diffSet[0].before).to.equal("initial content")
expect(diffSet[0].after).to.equal("working directory changes")
})
})
@@ -0,0 +1,94 @@
import { expect } from "chai"
import { describe, it, beforeEach, afterEach } from "mocha"
import fs from "fs/promises"
import * as vscode from "vscode"
import { createTestEnvironment, createTestTracker } from "./Checkpoint-test-utils"
describe("Checkpoint Disabled State", () => {
let env: Awaited<ReturnType<typeof createTestEnvironment>>
let originalGetConfiguration: typeof vscode.workspace.getConfiguration
beforeEach(async () => {
env = await createTestEnvironment()
originalGetConfiguration = vscode.workspace.getConfiguration
// Mock VS Code configuration to disable checkpoints
vscode.workspace.getConfiguration = () =>
({
get: (key: string) => (key === "enableCheckpoints" ? false : undefined),
}) as any
})
afterEach(async () => {
await env.cleanup()
// Restore original configuration
vscode.workspace.getConfiguration = originalGetConfiguration
})
it("should return undefined when creating tracker", async () => {
const tracker = await createTestTracker(env.globalStoragePath)
expect(tracker).to.be.undefined
})
it("should allow re-enabling checkpoints", async () => {
// First verify disabled state
const disabledTracker = await createTestTracker(env.globalStoragePath)
expect(disabledTracker).to.be.undefined
// Mock configuration to enable checkpoints
vscode.workspace.getConfiguration = () =>
({
get: (key: string) => (key === "enableCheckpoints" ? true : undefined),
}) as any
// Verify tracker can be created when enabled
const enabledTracker = await createTestTracker(env.globalStoragePath)
expect(enabledTracker).to.not.be.undefined
// Verify operations work
if (!enabledTracker) {throw new Error("Failed to create tracker")}
await fs.writeFile(env.testFilePath, "test content")
const commit = await enabledTracker.commit()
expect(commit).to.be.a("string").and.not.empty
})
it("should prevent operations when disabled mid-session", async () => {
// Start with checkpoints enabled
vscode.workspace.getConfiguration = () =>
({
get: (key: string) => (key === "enableCheckpoints" ? true : undefined),
}) as any
// Create tracker and initial commit
const tracker = await createTestTracker(env.globalStoragePath)
expect(tracker).to.not.be.undefined
if (!tracker) {throw new Error("Failed to create tracker")}
await fs.writeFile(env.testFilePath, "initial content")
const firstCommit = await tracker.commit()
expect(firstCommit).to.be.a("string").and.not.empty
// Disable checkpoints
vscode.workspace.getConfiguration = () =>
({
get: (key: string) => (key === "enableCheckpoints" ? false : undefined),
}) as any
// Verify new tracker cannot be created
const disabledTracker = await createTestTracker(env.globalStoragePath)
expect(disabledTracker).to.be.undefined
// Verify existing tracker still works
// This is expected behavior since the tracker was created when enabled
await fs.writeFile(env.testFilePath, "modified content")
const secondCommit = await tracker.commit()
expect(secondCommit).to.be.a("string").and.not.empty
expect(secondCommit).to.not.equal(firstCommit)
// Verify diffs still work on existing tracker
const diffSet = await tracker.getDiffSet(firstCommit, secondCommit)
expect(diffSet).to.have.lengthOf(1)
expect(diffSet[0].before).to.equal("initial content")
expect(diffSet[0].after).to.equal("modified content")
})
})
@@ -0,0 +1,95 @@
import { expect } from "chai"
import { describe, it, beforeEach, afterEach } from "mocha"
import fs from "fs/promises"
import path from "path"
import { createTestEnvironment, createTestTracker } from "./Checkpoint-test-utils"
describe("Checkpoint Revert Operations", () => {
let env: Awaited<ReturnType<typeof createTestEnvironment>>
beforeEach(async () => {
env = await createTestEnvironment()
})
afterEach(async () => {
await env.cleanup()
})
it("should revert working directory to a previous checkpoint state", async () => {
const tracker = await createTestTracker(env.globalStoragePath)
if (!tracker) {throw new Error("Failed to create tracker")}
// Create and commit initial state
await fs.writeFile(env.testFilePath, "initial content")
const firstCommit = await tracker.commit()
expect(firstCommit).to.not.be.undefined
// Create and commit changes
await fs.writeFile(env.testFilePath, "modified content")
const secondCommit = await tracker.commit()
expect(secondCommit).to.not.be.undefined
// Make more changes without committing
await fs.writeFile(env.testFilePath, "uncommitted changes")
// Revert to first commit
await tracker.resetHead(firstCommit!)
// Verify file content matches initial state
const resetContent = await fs.readFile(env.testFilePath, "utf8")
expect(resetContent).to.equal("initial content")
})
it("should handle reverting with multiple files", async () => {
const tracker = await createTestTracker(env.globalStoragePath)
if (!tracker) {throw new Error("Failed to create tracker")}
// Create and commit initial state with multiple files
const testFile2Path = path.join(env.tempDir, "src", "test2.txt")
await fs.writeFile(env.testFilePath, "file1 initial")
await fs.writeFile(testFile2Path, "file2 initial")
const firstCommit = await tracker.commit()
expect(firstCommit).to.not.be.undefined
// Modify both files and commit
await fs.writeFile(env.testFilePath, "file1 modified")
await fs.writeFile(testFile2Path, "file2 modified")
const secondCommit = await tracker.commit()
expect(secondCommit).to.not.be.undefined
// Make more changes
await fs.writeFile(env.testFilePath, "file1 uncommitted")
await fs.writeFile(testFile2Path, "file2 uncommitted")
// Reset to first commit
await tracker.resetHead(firstCommit!)
// Verify both files match initial state
const file1Content = await fs.readFile(env.testFilePath, "utf8")
const file2Content = await fs.readFile(testFile2Path, "utf8")
expect(file1Content).to.equal("file1 initial")
expect(file2Content).to.equal("file2 initial")
})
it("should handle reverting when files are deleted", async () => {
const tracker = await createTestTracker(env.globalStoragePath)
if (!tracker) {throw new Error("Failed to create tracker")}
// Create and commit initial state
await fs.writeFile(env.testFilePath, "initial content")
const firstCommit = await tracker.commit()
expect(firstCommit).to.not.be.undefined
// Delete file and commit
await fs.unlink(env.testFilePath)
const secondCommit = await tracker.commit()
expect(secondCommit).to.not.be.undefined
// Revert to first commit
await tracker.resetHead(firstCommit!)
// Verify file is restored with original content
const resetContent = await fs.readFile(env.testFilePath, "utf8")
expect(resetContent).to.equal("initial content")
})
})
@@ -0,0 +1,120 @@
import { expect } from "chai"
import { describe, it, beforeEach, afterEach } from "mocha"
import fs from "fs/promises"
import { createTestEnvironment, createTestTracker } from "./Checkpoint-test-utils"
import { HistoryItem } from "../../shared/HistoryItem"
import CheckpointTracker from "./CheckpointTracker"
describe("Checkpoint Task Switching", () => {
let env: Awaited<ReturnType<typeof createTestEnvironment>>
let taskId1: string
let taskId2: string
let tracker1: CheckpointTracker | undefined
let tracker2: CheckpointTracker | undefined
beforeEach(async () => {
env = await createTestEnvironment()
taskId1 = "task-1"
taskId2 = "task-2"
tracker1 = await createTestTracker(env.globalStoragePath, taskId1)
if (!tracker1) {throw new Error("Failed to create tracker1")}
})
afterEach(async () => {
await env.cleanup()
})
it("should maintain separate history for each task", async () => {
if (!tracker1) {throw new Error("Failed to create tracker1")}
// Create and commit file in first task
await fs.writeFile(env.testFilePath, "task1 initial")
const task1Commit1 = await tracker1.commit()
expect(task1Commit1).to.be.a("string").and.not.empty
// Modify and commit again in first task
await fs.writeFile(env.testFilePath, "task1 modified")
const task1Commit2 = await tracker1.commit()
expect(task1Commit2).to.be.a("string").and.not.empty
// Create second task tracker
tracker2 = await createTestTracker(env.globalStoragePath, taskId2)
if (!tracker2) {throw new Error("Failed to create tracker2")}
// Create and commit file in second task
await fs.writeFile(env.testFilePath, "task2 initial")
const task2Commit1 = await tracker2.commit()
expect(task2Commit1).to.be.a("string").and.not.empty
// Create another commit to establish history
await fs.writeFile(env.testFilePath, "task2 modified")
const task2Commit2 = await tracker2.commit()
expect(task2Commit2).to.be.a("string").and.not.empty
// Verify second task's history
const task2Diff = await tracker2.getDiffSet(task2Commit1, task2Commit2)
expect(task2Diff).to.have.lengthOf(1)
expect(task2Diff[0].before).to.equal("task2 initial")
expect(task2Diff[0].after).to.equal("task2 modified")
// Switch back to first task by creating new tracker
const tracker1Again = await createTestTracker(env.globalStoragePath, taskId1)
if (!tracker1Again) {throw new Error("Failed to create tracker1Again")}
// Verify first task's history is preserved
const task1Diff = await tracker1Again.getDiffSet(task1Commit1, task1Commit2)
expect(task1Diff[0].before).to.equal("task1 initial")
expect(task1Diff[0].after).to.equal("task1 modified")
// Reset first task to initial state
if (!task1Commit1) {throw new Error("Failed to create initial commit")}
await tracker1Again.resetHead(task1Commit1)
const resetContent = await fs.readFile(env.testFilePath, "utf8")
expect(resetContent).to.equal("task1 initial")
})
it("should handle task deletion and recreation", async () => {
if (!tracker1) {throw new Error("Failed to create tracker1")}
// Create and commit file in first task
await fs.writeFile(env.testFilePath, "task1 content")
const task1Commit = await tracker1.commit()
expect(task1Commit).to.be.a("string").and.not.empty
// Create second task
tracker2 = await createTestTracker(env.globalStoragePath, taskId2)
if (!tracker2) {throw new Error("Failed to create tracker2")}
await fs.writeFile(env.testFilePath, "task2 content")
const task2Commit = await tracker2.commit()
expect(task2Commit).to.be.a("string").and.not.empty
// Delete second task's checkpoints
const historyItem: HistoryItem = {
id: `test-${Date.now()}`,
ts: Date.now(),
task: taskId2,
shadowGitConfigWorkTree: env.tempDir,
tokensIn: 0,
tokensOut: 0,
totalCost: 0,
}
await CheckpointTracker.deleteCheckpoints(taskId2, historyItem, env.globalStoragePath)
// Recreate second task
const tracker2Again = await createTestTracker(env.globalStoragePath, taskId2)
if (!tracker2Again) {throw new Error("Failed to create tracker2Again")}
// Create new commit in recreated task
await fs.writeFile(env.testFilePath, "task2 new content")
const newCommit = await tracker2Again.commit()
expect(newCommit).to.be.a("string").and.not.empty
// Switch back to first task and verify its history is intact
const tracker1Again = await createTestTracker(env.globalStoragePath, taskId1)
if (!tracker1Again) {throw new Error("Failed to create tracker1Again")}
if (!task1Commit) {throw new Error("Failed to create initial commit")}
await tracker1Again.resetHead(task1Commit)
const resetContent = await fs.readFile(env.testFilePath, "utf8")
expect(resetContent).to.equal("task1 content")
})
})
@@ -2,7 +2,7 @@ import { mkdir, access, constants } from "fs/promises"
import * as path from "path"
import * as vscode from "vscode"
import os from "os"
import { getCwd, getDesktopDir } from "@/utils/path"
import { getCwd } from "@/utils/path"
/**
* Gets the path to the shadow Git repository in globalStorage.
@@ -61,7 +61,7 @@ export async function getWorkingDirectory(): Promise<string> {
}
const homedir = os.homedir()
const desktopPath = getDesktopDir()
const desktopPath = path.join(homedir, "Desktop")
const documentsPath = path.join(homedir, "Documents")
const downloadsPath = path.join(homedir, "Downloads")
+13 -42
View File
@@ -1,15 +1,16 @@
import { getCwd } from "@/utils/path"
import * as vscode from "vscode"
import type Anthropic from "@anthropic-ai/sdk"
import { execa } from "execa"
import readline from "readline"
import { ClaudeCodeMessage } from "./types"
import readline from "readline"
const cwd = vscode.workspace.workspaceFolders?.map((folder) => folder.uri.fsPath).at(0)
type ClaudeCodeOptions = {
systemPrompt: string
messages: Anthropic.Messages.MessageParam[]
path?: string
modelId?: string
thinkingBudgetTokens?: number
}
type ProcessState = {
@@ -20,7 +21,7 @@ type ProcessState = {
}
export async function* runClaudeCode(options: ClaudeCodeOptions): AsyncGenerator<ClaudeCodeMessage | string> {
const process = runProcess(options, await getCwd())
const process = runProcess(options)
const rl = readline.createInterface({
input: process.stdout,
@@ -75,20 +76,6 @@ export async function* runClaudeCode(options: ClaudeCodeOptions): AsyncGenerator
`Claude Code process exited with code ${exitCode}.${errorOutput ? ` Error output: ${errorOutput}` : ""}`,
)
}
} catch (err) {
// When the command fails, execa throws an error with the arguments, which include the whole system prompt.
// We want to log that, but not show it to the user.
console.error(`Error during Claude Code execution:`, err)
if (err instanceof Error) {
const startOfCommand = err.message.indexOf(": ")
if (startOfCommand !== -1) {
const messageWithoutCommand = err.message.slice(0, startOfCommand).trim()
throw new Error(messageWithoutCommand, { cause: err })
}
}
throw err
} finally {
rl.close()
if (!process.killed) {
@@ -119,11 +106,9 @@ const claudeCodeTools = [
].join(",")
const CLAUDE_CODE_TIMEOUT = 600000 // 10 minutes
// https://github.com/sindresorhus/execa/blob/main/docs/api.md#optionsmaxbuffer
const BUFFER_SIZE = 20_000_000 // 20 MB
function runProcess({ systemPrompt, messages, path, modelId, thinkingBudgetTokens }: ClaudeCodeOptions, cwd: string) {
const claudePath = path?.trim() || "claude"
function runProcess({ systemPrompt, messages, path, modelId }: ClaudeCodeOptions) {
const claudePath = path || "claude"
const args = [
"-p",
@@ -143,31 +128,17 @@ function runProcess({ systemPrompt, messages, path, modelId, thinkingBudgetToken
args.push("--model", modelId)
}
/**
* @see {@link https://docs.anthropic.com/en/docs/claude-code/settings#environment-variables}
*/
const env: NodeJS.ProcessEnv = {
...process.env,
// Respect the user's environment variables but set defaults.
// The default is 32000. However, I've gotten larger responses.
CLAUDE_CODE_MAX_OUTPUT_TOKENS: process.env.CLAUDE_CODE_MAX_OUTPUT_TOKENS || "64000",
// Disable telemetry, auto-updater and error reporting.
CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC: process.env.CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC || "1",
DISABLE_NON_ESSENTIAL_MODEL_CALLS: process.env.DISABLE_NON_ESSENTIAL_MODEL_CALLS || "1",
MAX_THINKING_TOKENS: (thinkingBudgetTokens || 0).toString(),
}
// We don't want to consume the user's ANTHROPIC_API_KEY,
// and will allow Claude Code to resolve auth by itself
delete env["ANTHROPIC_API_KEY"]
const claudeCodeProcess = execa(claudePath, args, {
stdin: "pipe",
stdout: "pipe",
stderr: "pipe",
env,
env: {
...process.env,
// The default is 32000. However, I've gotten larger responses, so we increase it unless the user specified it.
CLAUDE_CODE_MAX_OUTPUT_TOKENS: process.env.CLAUDE_CODE_MAX_OUTPUT_TOKENS || "64000",
},
cwd,
maxBuffer: BUFFER_SIZE,
maxBuffer: 1024 * 1024 * 1000,
timeout: CLAUDE_CODE_TIMEOUT,
})
+11 -33
View File
@@ -9,8 +9,6 @@ import * as diff from "diff"
import { diagnosticsToProblemsString, getNewDiagnostics } from "../diagnostics"
import { detectEncoding } from "../misc/extract-text"
import * as iconv from "iconv-lite"
import { getHostBridgeProvider } from "@/hosts/host-providers"
import { ShowTextDocumentRequest, ShowTextDocumentOptions, TextEditorInfo } from "@/shared/proto/host/window"
export const DIFF_VIEW_URI_SCHEME = "cline-diff"
@@ -238,15 +236,10 @@ export class DiffViewProvider {
// get text after save in case there is any auto-formatting done by the editor
const postSaveContent = updatedDocument.getText()
await getHostBridgeProvider().windowClient.showTextDocument(
ShowTextDocumentRequest.create({
path: absolutePath,
options: ShowTextDocumentOptions.create({
preview: false,
preserveFocus: true,
}),
}),
)
await vscode.window.showTextDocument(vscode.Uri.file(absolutePath), {
preview: false,
preserveFocus: true,
})
await this.closeAllDiffViews()
/*
@@ -344,15 +337,10 @@ export class DiffViewProvider {
await updatedDocument.save()
console.log(`File ${absolutePath} has been reverted to its original content.`)
if (this.documentWasOpen) {
await getHostBridgeProvider().windowClient.showTextDocument(
ShowTextDocumentRequest.create({
path: absolutePath,
options: ShowTextDocumentOptions.create({
preview: false,
preserveFocus: true,
}),
}),
)
await vscode.window.showTextDocument(vscode.Uri.file(absolutePath), {
preview: false,
preserveFocus: true,
})
}
await this.closeAllDiffViews()
}
@@ -388,19 +376,9 @@ export class DiffViewProvider {
arePathsEqual(tab.input.modified.fsPath, uri.fsPath),
)
if (diffTab && diffTab.input instanceof vscode.TabInputTextDiff) {
const editorInfo = await getHostBridgeProvider().windowClient.showTextDocument(
ShowTextDocumentRequest.create({
path: diffTab.input.modified.fsPath,
options: ShowTextDocumentOptions.create({
preserveFocus: true,
}),
}),
)
// Find the editor that matches the returned path
const editor = vscode.window.visibleTextEditors.find((e) => e.document.uri.fsPath === editorInfo.documentPath)
if (!editor) {
throw new Error("Failed to find opened text editor")
}
const editor = await vscode.window.showTextDocument(diffTab.input.modified, {
preserveFocus: true,
})
return editor
}
// Open new diff editor
@@ -1,8 +1,6 @@
import * as vscode from "vscode"
import { getWorkingState } from "@utils/git"
import { writeTextToClipboard } from "@utils/env"
import { getHostBridgeProvider } from "@/hosts/host-providers"
import { ShowTextDocumentRequest } from "@/shared/proto/host/window"
/**
* Formats the git diff into a prompt for the AI
@@ -132,10 +130,6 @@ async function editCommitMessage(message: string): Promise<void> {
language: "markdown",
})
await getHostBridgeProvider().windowClient.showTextDocument(
ShowTextDocumentRequest.create({
path: document.uri.fsPath,
}),
)
await vscode.window.showTextDocument(document)
vscode.window.showInformationMessage("Edit the commit message and copy when ready")
}
+1 -8
View File
@@ -2,8 +2,6 @@ import { Anthropic } from "@anthropic-ai/sdk"
import os from "os"
import * as path from "path"
import * as vscode from "vscode"
import { getHostBridgeProvider } from "@/hosts/host-providers"
import { ShowTextDocumentRequest, ShowTextDocumentOptions } from "@/shared/proto/host/window"
export async function downloadTask(dateTs: number, conversationHistory: Anthropic.MessageParam[]) {
// File name
@@ -40,12 +38,7 @@ export async function downloadTask(dateTs: number, conversationHistory: Anthropi
try {
// Write content to the selected location
await vscode.workspace.fs.writeFile(saveUri, new TextEncoder().encode(markdownContent))
await getHostBridgeProvider().windowClient.showTextDocument(
ShowTextDocumentRequest.create({
path: saveUri.fsPath,
options: ShowTextDocumentOptions.create({ preview: true }),
}),
)
vscode.window.showTextDocument(saveUri, { preview: true })
} catch (error) {
vscode.window.showErrorMessage(
`Failed to save markdown file: ${error instanceof Error ? error.message : String(error)}`,
+1 -8
View File
@@ -2,8 +2,6 @@ import * as path from "path"
import * as os from "os"
import * as vscode from "vscode"
import { arePathsEqual } from "@utils/path"
import { getHostBridgeProvider } from "@/hosts/host-providers"
import { ShowTextDocumentRequest, ShowTextDocumentOptions } from "@/shared/proto/host/window"
export async function openImage(dataUri: string) {
const matches = dataUri.match(/^data:image\/([a-zA-Z]+);base64,(.+)$/)
@@ -44,12 +42,7 @@ export async function openFile(absolutePath: string) {
} catch {} // not essential, sometimes tab operations fail
const document = await vscode.workspace.openTextDocument(uri)
await getHostBridgeProvider().windowClient.showTextDocument(
ShowTextDocumentRequest.create({
path: document.uri.fsPath,
options: ShowTextDocumentOptions.create({ preview: false }),
}),
)
await vscode.window.showTextDocument(document, { preview: false })
} catch (error) {
vscode.window.showErrorMessage(`Could not open file!`)
}
+8 -12
View File
@@ -2,8 +2,6 @@ import * as vscode from "vscode"
import fs from "fs/promises"
import * as path from "path"
import sizeOf from "image-size"
import { getHostBridgeProvider } from "@/hosts/host-providers"
import { ShowOpenDialogueRequest } from "@/shared/proto/host/window"
/**
* Supports processing of images and other file types
@@ -13,17 +11,15 @@ export async function selectFiles(imagesAllowed: boolean): Promise<{ images: str
const IMAGE_EXTENSIONS = ["png", "jpg", "jpeg", "webp"] // supported by anthropic and openrouter
const OTHER_FILE_EXTENSIONS = ["xml", "json", "txt", "log", "md", "docx", "ipynb", "pdf", "xlsx", "csv"]
const showDialogueResponse = await getHostBridgeProvider().windowClient.showOpenDialogue(
ShowOpenDialogueRequest.create({
canSelectMany: true,
openLabel: "Select",
filters: {
files: imagesAllowed ? [...IMAGE_EXTENSIONS, ...OTHER_FILE_EXTENSIONS] : OTHER_FILE_EXTENSIONS,
},
}),
)
const options: vscode.OpenDialogOptions = {
canSelectMany: true,
openLabel: "Select",
filters: {
Files: imagesAllowed ? [...IMAGE_EXTENSIONS, ...OTHER_FILE_EXTENSIONS] : OTHER_FILE_EXTENSIONS,
},
}
const fileUris = showDialogueResponse.paths.map((path) => vscode.Uri.file(path))
const fileUris = await vscode.window.showOpenDialog(options)
if (!fileUris || fileUris.length === 0) {
return { images: [], files: [] }
@@ -60,14 +60,7 @@ describe("TerminalProcess (Integration Tests)", () => {
const emitSpy = sandbox.spy(process, "emit")
// Run a simple command
const runPromise = process.run(terminal, "echo test")
// If terminal doesn't have shell integration, advance timer
if (!terminal.shellIntegration) {
await sandbox.clock.tickAsync(3000)
}
await runPromise
await process.run(terminal, "echo test")
// Verify that the continue event was emitted
;(emitSpy as sinon.SinonSpy).calledWith("continue").should.be.true()
@@ -83,14 +76,7 @@ describe("TerminalProcess (Integration Tests)", () => {
const emitSpy = sandbox.spy(process, "emit")
// Run a command that produces predictable output
const runPromise = process.run(terminal, "echo 'Line 1' && echo 'Line 2'")
// If terminal doesn't have shell integration, advance timer
if (!terminal.shellIntegration) {
await sandbox.clock.tickAsync(3000)
}
await runPromise
await process.run(terminal, "echo 'Line 1' && echo 'Line 2'")
// Check that the events were emitted
;(emitSpy as sinon.SinonSpy).calledWith("completed").should.be.true()
@@ -106,14 +92,7 @@ describe("TerminalProcess (Integration Tests)", () => {
const emitSpy = sandbox.spy(process, "emit")
// Run a command that lists files
const runPromise = process.run(terminal, "ls -la")
// If terminal doesn't have shell integration, advance timer
if (!terminal.shellIntegration) {
await sandbox.clock.tickAsync(3000)
}
await runPromise
await process.run(terminal, "ls -la")
// Verify that the continue event was emitted
;(emitSpy as sinon.SinonSpy).calledWith("continue").should.be.true()
@@ -151,14 +130,7 @@ describe("TerminalProcess (Integration Tests)", () => {
const emitSpy = sandbox.spy(process, "emit")
// Run a command that produces predictable output
const runPromise = process.run(terminal, "echo 'Line 1' 'Line 2'")
// If terminal doesn't have shell integration, advance timer
if (!terminal.shellIntegration) {
await sandbox.clock.tickAsync(3000)
}
await runPromise
await process.run(terminal, "echo 'Line 1' 'Line 2'")
// Check that the events were emitted
;(emitSpy as sinon.SinonSpy).calledWith("completed").should.be.true()
@@ -174,14 +146,7 @@ describe("TerminalProcess (Integration Tests)", () => {
const emitSpy = sandbox.spy(process, "emit")
// Run a command that produces predictable output
const runPromise = process.run(terminal, "echo \"Line 1\" && echo 'Line 2'")
// If terminal doesn't have shell integration, advance timer
if (!terminal.shellIntegration) {
await sandbox.clock.tickAsync(3000)
}
await runPromise
await process.run(terminal, "echo \"Line 1\" && echo 'Line 2'")
// Check that the events were emitted
;(emitSpy as sinon.SinonSpy).calledWith("completed").should.be.true()
@@ -204,14 +169,8 @@ describe("TerminalProcess (Integration Tests)", () => {
// Spy on the emit function to verify events
const emitSpy = sandbox.spy(process, "emit")
// Run the command - this returns a promise
const runPromise = process.run(terminal, "test-command")
// Advance the fake timer by 3 seconds to trigger the setTimeout
await sandbox.clock.tickAsync(3000)
// Now wait for the promise to resolve
await runPromise
// Run the command
await process.run(terminal, "test-command")
// Check that the correct methods were called and events emitted
sendTextStub.calledWith("test-command", true).should.be.true()
+2 -25
View File
@@ -2,7 +2,6 @@ import { EventEmitter } from "events"
import { stripAnsi } from "./ansiUtils"
import * as vscode from "vscode"
import { Logger } from "@services/logging/Logger"
import { getLatestTerminalOutput } from "./get-latest-output"
export interface TerminalProcessEvents {
line: [line: string]
@@ -32,19 +31,6 @@ export class TerminalProcess extends EventEmitter<TerminalProcessEvents> {
// super()
async run(terminal: vscode.Terminal, command: string) {
// When command does not produce any output, we can assume the shell integration API failed and as a fallback return the current terminal contents
const emitCurrentTerminalContents = async () => {
try {
const terminalSnapshot = await getLatestTerminalOutput()
if (terminalSnapshot && terminalSnapshot.trim()) {
const fallbackMessage = `The command's output could not be captured due to some technical issue, however it has been executed successfully. Here's the current terminal's content to help you get the command's output:\n\n${terminalSnapshot}`
this.emit("line", fallbackMessage)
}
} catch (error) {
console.error("Error capturing terminal output:", error)
}
}
// Clear any existing grace period timer from previous commands
if (this.gracePeriodTimer) {
clearTimeout(this.gracePeriodTimer)
@@ -263,8 +249,7 @@ export class TerminalProcess extends EventEmitter<TerminalProcessEvents> {
if (!didEmitEmptyLine) {
console.log(`[TerminalProcess] Emitting fallback empty line for no-output command`)
this.emit("line", "") // empty line to show proceed button
// this.emit("line", "[Command completed with no output]")
await emitCurrentTerminalContents()
this.emit("line", "[Command completed with no output]")
didEmitEmptyLine = true
}
}
@@ -310,8 +295,7 @@ export class TerminalProcess extends EventEmitter<TerminalProcessEvents> {
console.log(`[TerminalProcess] WARNING: Process completed but no output was captured`)
// Ensure we emit at least one line for UI feedback
if (!didEmitEmptyLine) {
// this.emit("line", "[Command completed silently]")
await emitCurrentTerminalContents()
this.emit("line", "[Command completed silently]")
}
}
@@ -330,14 +314,7 @@ export class TerminalProcess extends EventEmitter<TerminalProcessEvents> {
this.startGracePeriod()
}
} else {
// no shell integration detected, we'll fallback to running the command and capturing the terminal's output after some time
terminal.sendText(command, true)
// wait 3 seconds for the command to run
await new Promise((resolve) => setTimeout(resolve, 3000))
// For terminals without shell integration, also try to capture terminal content
await emitCurrentTerminalContents()
// For terminals without shell integration, we can't know when the command completes
// So we'll just emit the continue event after a delay
this.emit("completed")
@@ -0,0 +1,43 @@
import { getCwd } from "@/utils/path"
import * as vscode from "vscode"
/*
Used to get user's current python environment (unnecessary now that we use the IDE's terminal)
${await (async () => {
try {
const pythonEnvPath = await getPythonEnvPath()
if (pythonEnvPath) {
return `\nPython Environment: ${pythonEnvPath}`
}
} catch {}
return ""
})()}
*/
export async function getPythonEnvPath(): Promise<string | undefined> {
const pythonExtension = vscode.extensions.getExtension("ms-python.python")
if (!pythonExtension) {
return undefined
}
// Ensure the Python extension is activated
if (!pythonExtension.isActive) {
// if the python extension is not active, we can assume the project is not a python project
return undefined
}
// Access the Python extension API
const pythonApi = pythonExtension.exports
// Get the active environment path for the current workspace
const workspaceFolder = await getCwd()
if (!workspaceFolder) {
return undefined
}
// Get the active python environment path for the current workspace
const pythonEnv = await pythonApi?.environments?.getActiveEnvironmentPath(workspaceFolder)
if (pythonEnv && pythonEnv.path) {
return pythonEnv.path
} else {
return undefined
}
}
+6 -1
View File
@@ -4,9 +4,14 @@ import { ExtensionMessage } from "@shared/ExtensionMessage"
export class ClineAccountService {
private readonly baseUrl = "https://api.cline.bot/v1"
private postMessageToWebview: (message: ExtensionMessage) => Promise<void>
private getClineApiKey: () => Promise<string | undefined>
constructor(getClineApiKey: () => Promise<string | undefined>) {
constructor(
postMessageToWebview: (message: ExtensionMessage) => Promise<void>,
getClineApiKey: () => Promise<string | undefined>,
) {
this.postMessageToWebview = postMessageToWebview
this.getClineApiKey = getClineApiKey
}
+1
View File
@@ -139,6 +139,7 @@ export class McpHub {
console.log("[DEBUG] subscribing to mcp file changes")
const cancelSubscription = getHostBridgeProvider().watchServiceClient.subscribeToFile(
SubscribeToFileRequest.create({
metadata: Metadata.create({}),
path: settingsPath,
}),
{
@@ -202,23 +202,26 @@ class TelemetryService {
const propertiesWithVersion = this.addProperties(event.properties)
const capturedEvent = {
event: event.event,
properties: propertiesWithVersion,
}
if (collect && taskId) {
const existingTask = this.collectedTasks.find((task) => task.taskId === taskId)
if (existingTask) {
existingTask.collection.push(capturedEvent)
existingTask.collection.push({
event: event.event,
properties: propertiesWithVersion,
})
} else {
this.collectedTasks.push({
taskId,
collection: [capturedEvent],
collection: [
{
event: event.event,
properties: propertiesWithVersion,
},
],
})
}
} else {
this.client.capture({ ...capturedEvent, distinctId: this.distinctId })
this.client.capture({ distinctId: this.distinctId, event: event.event, properties: propertiesWithVersion })
}
}
@@ -285,8 +288,6 @@ class TelemetryService {
* @param provider The API provider (e.g., OpenAI, Anthropic)
* @param model The specific model used (e.g., GPT-4, Claude)
* @param source The source of the message ("user" | "model"). Used to track message patterns and identify when users need to correct the model's responses.
* @param collect If true, collect event instead of sending
* @param tokenUsage Optional token usage data
*/
public captureConversationTurnEvent(
taskId: string,
@@ -294,13 +295,6 @@ class TelemetryService {
model: string = "unknown",
source: "user" | "assistant",
collect: boolean = false,
tokenUsage: {
tokensIn?: number
tokensOut?: number
cacheWriteTokens?: number
cacheReadTokens?: number
totalCost?: number
} = {},
) {
// Ensure required parameters are provided
if (!taskId || !provider || !model || !source) {
@@ -314,7 +308,6 @@ class TelemetryService {
model,
source,
timestamp: new Date().toISOString(), // Add timestamp for message sequencing
...tokenUsage,
}
this.capture(
+1
View File
@@ -9,6 +9,7 @@ import * as path from "path"
import { Logger } from "../logging/Logger"
import { createTestServer, shutdownTestServer } from "./TestServer"
import { getHostBridgeProvider } from "@/hosts/host-providers"
import { GetWorkspacePathsRequest } from "@/shared/proto/index.host"
// State variable
let isTestMode = false
+1 -1
View File
@@ -273,7 +273,7 @@ export function createTestServer(webviewProvider?: WebviewProvider): http.Server
await updateApiConfiguration(visibleWebview.controller.context, updatedConfig)
// Update global state to use cline provider
await updateGlobalState(visibleWebview.controller.context, "apiProvider", "cline" as ApiProvider)
await updateWorkspaceState(visibleWebview.controller.context, "apiProvider", "cline" as ApiProvider)
// Post state to webview to reflect changes
await visibleWebview.controller.postStateToWebview()
-1
View File
@@ -60,7 +60,6 @@ export const DEFAULT_PLATFORM = "unknown"
export interface ExtensionState {
isNewUser: boolean
welcomeViewCompleted: boolean
apiConfiguration?: ApiConfiguration
autoApprovalSettings: AutoApprovalSettings
browserSettings: BrowserSettings
-36
View File
@@ -2374,42 +2374,6 @@ export const requestyDefaultModelInfo: ModelInfo = {
export type SapAiCoreModelId = keyof typeof sapAiCoreModels
export const sapAiCoreDefaultModelId: SapAiCoreModelId = "anthropic--claude-3.5-sonnet"
export const sapAiCoreModels = {
"gemini-2.5-pro": {
maxTokens: 65536,
contextWindow: 1_048_576,
supportsImages: true,
supportsPromptCache: true,
inputPrice: 2.5,
outputPrice: 15,
cacheReadsPrice: 0.625,
tiers: [
{
contextWindow: 200000,
inputPrice: 1.25,
outputPrice: 10,
cacheReadsPrice: 0.31,
},
{
contextWindow: Infinity,
inputPrice: 2.5,
outputPrice: 15,
cacheReadsPrice: 0.625,
},
],
},
"gemini-2.5-flash": {
maxTokens: 65536,
contextWindow: 1_048_576,
supportsImages: true,
supportsPromptCache: true,
inputPrice: 0.3,
outputPrice: 2.5,
cacheReadsPrice: 0.075,
thinkingConfig: {
maxBudget: 24576,
outputPrice: 3.5,
},
},
"anthropic--claude-4-sonnet": {
maxTokens: 8192,
contextWindow: 200_000,
@@ -4,14 +4,12 @@ import {
WatchServiceClientImpl,
WorkspaceServiceClientImpl,
EnvServiceClientImpl,
WindowServiceClientImpl,
} from "@generated/standalone/host-bridge-clients"
import {
UriServiceClientInterface,
WatchServiceClientInterface,
WorkspaceServiceClientInterface,
EnvServiceClientInterface,
WindowServiceClientInterface,
} from "@generated/hosts/host-bridge-client-types"
import { HostBridgeClientProvider } from "@/hosts/host-provider-types"
@@ -25,7 +23,6 @@ export class ExternalHostBridgeClientManager implements HostBridgeClientProvider
watchServiceClient: WatchServiceClientInterface
workspaceClient: WorkspaceServiceClientInterface
envClient: EnvServiceClientInterface
windowClient: WindowServiceClientInterface
constructor() {
const address = process.env.HOST_BRIDGE_ADDRESS || "localhost:50052"
@@ -35,7 +32,6 @@ export class ExternalHostBridgeClientManager implements HostBridgeClientProvider
this.watchServiceClient = new WatchServiceClientImpl(this.channel)
this.workspaceClient = new WorkspaceServiceClientImpl(this.channel)
this.envClient = new EnvServiceClientImpl(this.channel)
this.windowClient = new WindowServiceClientImpl(this.channel)
}
public close(): void {

Some files were not shown because too many files have changed in this diff Show More