Merge pull request #1 from RooVetGit/main

Syncing sbc-roo-code main branch
This commit is contained in:
shaybc 2025-02-26 13:41:01 +02:00 committed by GitHub
commit a8d1fbbbf0
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
109 changed files with 6503 additions and 4940 deletions

2
.github/CODEOWNERS vendored
View file

@ -1,2 +1,2 @@
# These owners will be the default owners for everything in the repo
* @stea9499 @ColemanRoo @mrubens @cte
* @mrubens @cte

View file

@ -33,7 +33,7 @@ body:
id: model
attributes:
label: Which Model are you using?
description: Please specify the model you're using (e.g. Claude 3.5 Sonnet)
description: Please specify the model you're using (e.g. Claude 3.7 Sonnet)
validations:
required: true
- type: textarea

View file

@ -28,7 +28,22 @@ jobs:
- name: Lint
run: npm run lint
unit-test:
knip:
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v4
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: '18'
cache: 'npm'
- name: Install dependencies
run: npm run install:all
- name: Run knip checks
run: npm run knip
test-extension:
runs-on: ubuntu-latest
steps:
- name: Checkout code
@ -41,7 +56,30 @@ jobs:
- name: Install dependencies
run: npm run install:all
- name: Run unit tests
run: npm test
run: npx jest --silent
test-webview:
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v4
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: '18'
cache: 'npm'
- name: Install dependencies
run: npm run install:all
- name: Run unit tests
working-directory: webview-ui
run: npx jest --silent
unit-test:
needs: [test-extension, test-webview]
runs-on: ubuntu-latest
steps:
- name: NO-OP
run: echo "All unit tests passed."
check-openrouter-api-key:
runs-on: ubuntu-latest

View file

@ -1,5 +1,49 @@
# Roo Code Changelog
## [3.7.5]
- Fix context window truncation math (see [#1173](https://github.com/RooVetGit/Roo-Code/issues/1173))
- Fix various issues with the model picker (thanks @System233!)
- Fix model input / output cost parsing (thanks @System233!)
- Add drag-and-drop for files
- Enable the "Thinking Budget" slider for Claude 3.7 Sonnet on OpenRouter
## [3.7.4]
- Fix a bug that prevented the "Thinking" setting from properly updating when switching profiles.
## [3.7.3]
- Support for ["Thinking"](https://docs.anthropic.com/en/docs/build-with-claude/extended-thinking) Sonnet 3.7 when using the Anthropic provider.
## [3.7.2]
- Fix computer use and prompt caching for OpenRouter's `anthropic/claude-3.7-sonnet:beta` (thanks @cte!)
- Fix sliding window calculations for Sonnet 3.7 that were causing a context window overflow (thanks @cte!)
- Encourage diff editing more strongly in the system prompt (thanks @hannesrudolph!)
## [3.7.1]
- Add AWS Bedrock support for Sonnet 3.7 and update some defaults to Sonnet 3.7 instead of 3.5
## [3.7.0]
- Introducing Roo Code 3.7, with support for the new Claude Sonnet 3.7. Because who cares about skipping version numbers anymore? Thanks @lupuletic and @cte for the PRs!
## [3.3.26]
- Adjust the default prompt for Debug mode to focus more on diagnosis and to require user confirmation before moving on to implementation
## [3.3.25]
- Add a "Debug" mode that specializes in debugging tricky problems (thanks [Ted Werbel](https://x.com/tedx_ai/status/1891514191179309457) and [Carlos E. Perez](https://x.com/IntuitMachine/status/1891516362486337739)!)
- Add an experimental "Power Steering" option to significantly improve adherence to role definitions and custom instructions
## [3.3.24]
- Fixed a bug with region selection preventing AWS Bedrock profiles from being saved (thanks @oprstchn!)
- Updated the price of gpt-4o (thanks @marvijo-code!)
## [3.3.23]
- Handle errors more gracefully when reading custom instructions from files (thanks @joemanley201!)

226
README.md
View file

@ -34,204 +34,78 @@ Check out the [CHANGELOG](CHANGELOG.md) for detailed updates and fixes.
---
## New in 3.3: Code Actions, More Powerful Modes, and a new Discord! 🚀
## New in 3.7: Claude 3.7 Sonnet Support 🚀
This release brings significant improvements to how you interact with Roo Code:
We're excited to announce support for Anthropic's latest model, Claude 3.7 Sonnet! The model shows notable improvements in:
### Code Actions
- Front-end development and full-stack updates
- Agentic workflows for multi-step processes
- More accurate math, coding, and instruction-following
Roo Code now integrates directly with VS Code's native code actions system, providing quick fixes and refactoring options right in your editor. Look for the lightbulb 💡 to access Roo Code's capabilities without switching context.
### Enhanced Mode Capabilities
- **Markdown Editing**: Addressing one of the most requested features, Ask and Architect modes can now create and edit markdown files!
- **Custom File Restrictions**: In general, custom modes can now be restricted to specific file patterns (for example, a technical writer who can only edit markdown files 👋). There's no UI for this yet, but who needs that when you can just ask Roo to set it up for you?
- **Self-Initiated Mode Switching**: Modes can intelligently request to switch between each other based on the task at hand. For instance, Code mode might request to switch to Test Engineer mode once it's ready to write tests.
### Join Our Discord!
We've launched a new Discord community! Join us at [https://roocode.com/discord](https://roocode.com/discord) to:
- Share your custom modes
- Get help and support
- Connect with other Roo Code users
- Stay updated on the latest features
## New in 3.2: Introducing Custom Modes, plus rebranding from Roo Cline → Roo Code! 🚀
### Introducing Roo Code
Our biggest update yet is here - we're officially changing our name from Roo Cline to Roo Code! After growing beyond 50,000 installations across VS Marketplace and Open VSX, we're ready to chart our own course. Our heartfelt thanks to everyone in the Cline community who helped us reach this milestone.
### Custom Modes
To mark this new chapter, we're introducing the power to shape Roo Code into any role you need. You can now create an entire team of agents with deeply customized prompts:
- QA Engineers who write thorough test cases and catch edge cases
- Product Managers who excel at user stories and feature prioritization
- UI/UX Designers who craft beautiful, accessible interfaces
- Code Reviewers who ensure quality and maintainability
The best part is that Roo can help you create these new modes! Just type "Create a new mode for <X>" in the chat to get started, and go into the Prompts tab or (carefully) edit the JSON representation to customize the prompt and allowed tools to your liking.
We can't wait to hear more about what you build and how we can continue to evolve the Roo Code platform to support you. Please join us in our new https://www.reddit.com/r/RooCode subreddit to share your custom modes and be part of our next chapter. 🚀
## New in 3.1: Chat Mode Prompt Customization & Prompt Enhancements
Hot off the heels of **v3.0** introducing Code, Architect, and Ask chat modes, one of the most requested features has arrived: **customizable prompts for each mode**! 🎉
You can now tailor the **role definition** and **custom instructions** for every chat mode to perfectly fit your workflow. Want to adjust Architect mode to focus more on system scalability? Or tweak Ask mode for deeper research queries? Done. Plus, you can define these via **mode-specific `.clinerules-[mode]` files**. Youll find all of this in the new **Prompts** tab in the top menu.
The second big feature in this release is a complete revamp of **prompt enhancements**. This feature helps you craft messages to get even better results from Cline. Heres whats new:
- Works with **any provider** and API configuration, not just OpenRouter.
- Fully customizable prompts to match your unique needs.
- Same simple workflow: just hit the ✨ **Enhance Prompt** button in the chat input to try it out.
Whether youre using GPT-4, other APIs, or switching configurations, this gives you total control over how your prompts are optimized.
As always, wed love to hear your thoughts and ideas! What features do you want to see in **v3.2**? Drop by https://www.reddit.com/r/roocline and join the discussion - we're building Roo Cline together. 🚀
## New in 3.0 - Chat Modes!
You can now choose between different prompts for Roo Cline to better suit your workflow. Heres whats available:
- **Code:** (existing behavior) The default mode where Cline helps you write code and execute tasks.
- **Architect:** "You are Cline, a software architecture expert..." Ideal for thinking through high-level technical design and system architecture. Cant write code or run commands.
- **Ask:** "You are Cline, a knowledgeable technical assistant..." Perfect for asking questions about the codebase or digging into concepts. Also cant write code or run commands.
**Switching Modes:**
Its super simple! Theres a dropdown in the bottom left of the chat input to switch modes. Right next to it, youll find a way to switch between the API configuration profiles associated with the current mode (configured on the settings screen).
**Why Add This?**
- It keeps Cline from being overly eager to jump into solving problems when you just want to think or ask questions.
- Each mode remembers the API configuration you last used with it. For example, you can use more thoughtful models like OpenAI o1 for Architect and Ask, while sticking with Sonnet or DeepSeek for coding tasks.
- It builds on research suggesting better results when separating "thinking" from "coding," explained well in this very thoughtful [article](https://aider.chat/2024/09/26/architect.html) from aider.
Right now, switching modes is a manual process. In the future, wed love to give Cline the ability to suggest mode switches based on context. For now, wed really appreciate your feedback on this feature.
Try it today in your provider of choice!
---
## What Can Roo Code Do?
- 🚀 **Generate Code** from natural language descriptions
- 🔧 **Refactor & Debug** existing code
- 📝 **Write & Update** documentation
- 🤔 **Answer Questions** about your codebase
- 🔄 **Automate** repetitive tasks
- 🏗️ **Create** new files and projects
## Quick Start
1. [Install Roo Code](https://docs.roocode.com/getting-started/installing)
2. [Connect Your AI Provider](https://docs.roocode.com/getting-started/connecting-api-provider)
3. [Try Your First Task](https://docs.roocode.com/getting-started/your-first-task)
## Key Features
### Adaptive Autonomy
### Multiple Modes
Roo Code communicates in **natural language** and proposes actions—file edits, terminal commands, browser tests, etc. You choose how it behaves:
Roo Code adapts to your needs with specialized [modes](https://docs.roocode.com/basic-usage/modes):
- **Manual Approval**: Review and approve every step to keep total control.
- **Autonomous/Auto-Approve**: Grant Roo Code the ability to run tasks without interruption, speeding up routine workflows.
- **Hybrid**: Auto-approve specific actions (e.g., file writes) but require confirmation for riskier tasks (like deploying code).
- **Code Mode:** For general-purpose coding tasks
- **Architect Mode:** For planning and technical leadership
- **Ask Mode:** For answering questions and providing information
- **Debug Mode:** For systematic problem diagnosis
- **[Custom Modes](https://docs.roocode.com/advanced-usage/custom-modes):** Create unlimited specialized personas for security auditing, performance optimization, documentation, or any other task
No matter your preference, you always have the final say on what Roo Code does.
### Smart Tools
---
Roo Code comes with powerful [tools](https://docs.roocode.com/basic-usage/using-tools) that can:
### Supports Any API or Model
- Read and write files in your project
- Execute commands in your VS Code terminal
- Control a web browser
- Use external tools via [MCP (Model Context Protocol)](https://docs.roocode.com/advanced-usage/mcp)
Use Roo Code with:
MCP extends Roo Code's capabilities by allowing you to add unlimited custom tools. Integrate with external APIs, connect to databases, or create specialized development tools - MCP provides the framework to expand Roo Code's functionality to meet your specific needs.
- **OpenRouter**, Anthropic, Glama, OpenAI, Google Gemini, AWS Bedrock, Azure, GCP Vertex, or local models (LM Studio/Ollama)—anything **OpenAI-compatible**.
- Different models per mode. For instance, an advanced model for architecture vs. a cheaper model for daily coding tasks.
- **Usage Tracking**: Roo Code monitors token and cost usage for each session.
### Customization
---
Make Roo Code work your way with:
### Custom Modes
- [Custom Instructions](https://docs.roocode.com/advanced-usage/custom-instructions) for personalized behavior
- [Custom Modes](https://docs.roocode.com/advanced-usage/custom-modes) for specialized tasks
- [Local Models](https://docs.roocode.com/advanced-usage/local-models) for offline use
- [Auto-Approval Settings](https://docs.roocode.com/advanced-usage/auto-approving-actions) for faster workflows
**Custom Modes** let you shape Roo Codes persona, instructions, and permissions:
## Resources
- **Built-in**:
- **Code** Default, multi-purpose coding assistant
- **Architect** High-level system and design insights
- **Ask** Research and Q&A for deeper exploration
- **User-Created**: Type `Create a new mode for <X>` and Roo Code generates a brand-new persona for that role—complete with tailored prompts and optional tool restrictions.
### Documentation
Modes can each have unique instructions and skill sets. Manage them in the **Prompts** tab.
- [Basic Usage Guide](https://docs.roocode.com/basic-usage/the-chat-interface)
- [Advanced Features](https://docs.roocode.com/advanced-usage/auto-approving-actions)
- [Frequently Asked Questions](https://docs.roocode.com/faq)
**Advanced Mode Features:**
### Community
- **File Restrictions**: Modes can be restricted to specific file types (e.g., Ask and Architect modes can edit markdown files)
- **Custom File Rules**: Define your own file access patterns (e.g., `.test.ts` for test files only)
- **Direct Mode Switching**: Modes can request to switch to other modes when needed (e.g., switching to Code mode for implementation)
- **Self-Creation**: Roo Code can help create new modes, complete with role definitions and file restrictions
---
### File & Editor Operations
Roo Code can:
- **Create and edit** files in your project (showing you diffs).
- **React** to linting or compile-time errors automatically (missing imports, syntax errors, etc.).
- **Track changes** via your editors timeline so you can review or revert if needed.
---
### Command Line Integration
Easily run commands in your terminal—Roo Code:
- Installs packages, runs builds, or executes tests.
- Monitors output and adapts if it detects errors.
- Lets you keep dev servers running in the background while continuing to work.
You approve or decline each command, or set auto-approval for routine operations.
---
### Browser Automation
Roo Code can also open a **browser** session to:
- Launch your local or remote web app.
- Click, type, scroll, and capture screenshots.
- Collect console logs to debug runtime or UI/UX issues.
Ideal for **end-to-end testing** or visually verifying changes without constant copy-pasting.
---
### Adding Tools with MCP
Extend Roo Code with the **Model Context Protocol (MCP)**:
- “Add a tool that manages AWS EC2 resources.”
- “Add a tool that queries the company Jira.”
- “Add a tool that pulls the latest PagerDuty incidents.”
Roo Code can build and configure new tools autonomously (with your approval) to expand its capabilities instantly.
---
### Context Mentions
When you need to provide extra context:
- **@file** Embed a files contents in the conversation.
- **@folder** Include entire folder structures.
- **@problems** Pull in workspace errors/warnings for Roo Code to fix.
- **@url** Fetch docs from a URL, converting them to markdown.
- **@git** Supply a list of Git commits or diffs for Roo Code to analyze code history.
Help Roo Code focus on the most relevant details without blowing the token budget.
---
## Installation
Roo Code is available on:
- **[VSCode Marketplace](https://marketplace.visualstudio.com/items?itemName=RooVeterinaryInc.roo-cline)**
- **[Open-VSX](https://open-vsx.org/extension/RooVeterinaryInc/roo-cline)**
1. **Search “Roo Code”** in your editors Extensions panel to install directly.
2. Or grab the `.vsix` file from Marketplace / Open-VSX and **drag-and-drop** into your editor.
3. **Open** Roo Code from the Activity Bar or Command Palette to start chatting.
> **Tip**: Use `Cmd/Ctrl + Shift + P` → “Roo Code: Open in New Tab” to dock the AI assistant alongside your file explorer.
- **Discord:** [Join our Discord server](https://discord.gg/roocode) for real-time help and discussions
- **Reddit:** [Visit our subreddit](https://www.reddit.com/r/RooCode) to share experiences and tips
- **GitHub:** Report [issues](https://github.com/RooVetGit/Roo-Code/issues) or request [features](https://github.com/RooVetGit/Roo-Code/discussions/categories/feature-requests?discussions_q=is%3Aopen+category%3A%22Feature+Requests%22+sort%3Atop)
---

View file

@ -37,5 +37,5 @@ module.exports = {
roots: ["<rootDir>/src", "<rootDir>/webview-ui/src"],
modulePathIgnorePatterns: [".vscode-test"],
reporters: [["jest-simple-dot-reporter", {}]],
setupFiles: [],
setupFiles: ["<rootDir>/src/__mocks__/jest.setup.ts"],
}

27
knip.json Normal file
View file

@ -0,0 +1,27 @@
{
"$schema": "https://unpkg.com/knip@latest/schema.json",
"entry": ["src/extension.ts", "src/activate/index.ts", "webview-ui/src/index.tsx"],
"project": ["src/**/*.ts", "webview-ui/src/**/*.{ts,tsx}"],
"ignore": [
"**/__mocks__/**",
"**/__tests__/**",
"**/test/**",
"**/*.test.ts",
"**/*.test.tsx",
"**/stories/**",
"coverage/**",
"dist/**",
"out/**",
"bin/**",
"src/activate/**",
"src/exports/**",
"src/extension.ts",
".vscode-test.mjs"
],
"workspaces": {
"webview-ui": {
"entry": ["src/index.tsx"],
"project": ["src/**/*.{ts,tsx}"]
}
}
}

340
package-lock.json generated
View file

@ -1,15 +1,15 @@
{
"name": "roo-cline",
"version": "3.3.23",
"version": "3.7.5",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "roo-cline",
"version": "3.3.23",
"version": "3.7.5",
"dependencies": {
"@anthropic-ai/bedrock-sdk": "^0.10.2",
"@anthropic-ai/sdk": "^0.26.0",
"@anthropic-ai/sdk": "^0.37.0",
"@anthropic-ai/vertex-sdk": "^0.4.1",
"@aws-sdk/client-bedrock-runtime": "^3.706.0",
"@google/generative-ai": "^0.18.0",
@ -76,6 +76,7 @@
"husky": "^9.1.7",
"jest": "^29.7.0",
"jest-simple-dot-reporter": "^1.0.5",
"knip": "^5.44.4",
"lint-staged": "^15.2.11",
"mkdirp": "^3.0.1",
"mocha": "^11.1.0",
@ -121,9 +122,10 @@
}
},
"node_modules/@anthropic-ai/sdk": {
"version": "0.26.1",
"resolved": "https://registry.npmjs.org/@anthropic-ai/sdk/-/sdk-0.26.1.tgz",
"integrity": "sha512-HeMJP1bDFfQPQS3XTJAmfXkFBdZ88wvfkE05+vsoA9zGn5dHqEaHOPsqkazf/i0gXYg2XlLxxZrf6rUAarSqzw==",
"version": "0.37.0",
"resolved": "https://registry.npmjs.org/@anthropic-ai/sdk/-/sdk-0.37.0.tgz",
"integrity": "sha512-tHjX2YbkUBwEgg0JZU3EFSSAQPoK4qQR/NFYa8Vtzd5UAyXzZksCw2In69Rml4R/TyHPBfRYaLK35XiOe33pjw==",
"license": "MIT",
"dependencies": {
"@types/node": "^18.11.18",
"@types/node-fetch": "^2.6.4",
@ -5854,6 +5856,47 @@
"resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz",
"integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w=="
},
"node_modules/@snyk/github-codeowners": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/@snyk/github-codeowners/-/github-codeowners-1.1.0.tgz",
"integrity": "sha512-lGFf08pbkEac0NYgVf4hdANpAgApRjNByLXB+WBip3qj1iendOIyAwP2GKkKbQMNVy2r1xxDf0ssfWscoiC+Vw==",
"dev": true,
"dependencies": {
"commander": "^4.1.1",
"ignore": "^5.1.8",
"p-map": "^4.0.0"
},
"bin": {
"github-codeowners": "dist/cli.js"
},
"engines": {
"node": ">=8.10"
}
},
"node_modules/@snyk/github-codeowners/node_modules/commander": {
"version": "4.1.1",
"resolved": "https://registry.npmjs.org/commander/-/commander-4.1.1.tgz",
"integrity": "sha512-NOKm8xhkzAjzFx8B2v5OAHT+u5pRQc2UCa2Vq9jYL/31o2wi9mxBA7LIFs3sV5VSC49z6pEhfbMULvShKj26WA==",
"dev": true,
"engines": {
"node": ">= 6"
}
},
"node_modules/@snyk/github-codeowners/node_modules/p-map": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/p-map/-/p-map-4.0.0.tgz",
"integrity": "sha512-/bjOqmgETBYB5BoEeGVea8dmvHb2m9GLy1E9W43yeyfP6QQCZGFNa+XRceJEuDB6zqr+gKpIAmlLebMpykw/MQ==",
"dev": true,
"dependencies": {
"aggregate-error": "^3.0.0"
},
"engines": {
"node": ">=10"
},
"funding": {
"url": "https://github.com/sponsors/sindresorhus"
}
},
"node_modules/@tootallnate/quickjs-emscripten": {
"version": "0.23.0",
"resolved": "https://registry.npmjs.org/@tootallnate/quickjs-emscripten/-/quickjs-emscripten-0.23.0.tgz",
@ -6696,6 +6739,19 @@
"node": ">= 8.0.0"
}
},
"node_modules/aggregate-error": {
"version": "3.1.0",
"resolved": "https://registry.npmjs.org/aggregate-error/-/aggregate-error-3.1.0.tgz",
"integrity": "sha512-4I7Td01quW/RpocfNayFdFVk1qSuoh0E7JrbRJ16nH01HhKFQ88INq9Sd+nd72zqRySlr9BmDA8xlEJ6vJMrYA==",
"dev": true,
"dependencies": {
"clean-stack": "^2.0.0",
"indent-string": "^4.0.0"
},
"engines": {
"node": ">=8"
}
},
"node_modules/ajv": {
"version": "6.12.6",
"resolved": "https://registry.npmjs.org/ajv/-/ajv-6.12.6.tgz",
@ -7530,6 +7586,15 @@
"integrity": "sha512-cuSVIHi9/9E/+821Qjdvngor+xpnlwnuwIyZOaLmHBVdXL+gP+I6QQB9VkO7RI77YIcTV+S1W9AreJ5eN63JBA==",
"dev": true
},
"node_modules/clean-stack": {
"version": "2.2.0",
"resolved": "https://registry.npmjs.org/clean-stack/-/clean-stack-2.2.0.tgz",
"integrity": "sha512-4diC9HaTE+KRAMWhDhrGOECgWZxoevMc5TlkObMqNSsVU62PYzXZ/SMTjzyGAFF1YusgxGcSWTEXBhp0CPwQ1A==",
"dev": true,
"engines": {
"node": ">=6"
}
},
"node_modules/cli-cursor": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/cli-cursor/-/cli-cursor-4.0.0.tgz",
@ -7662,6 +7727,16 @@
"url": "https://github.com/chalk/wrap-ansi?sponsor=1"
}
},
"node_modules/clone": {
"version": "1.0.4",
"resolved": "https://registry.npmjs.org/clone/-/clone-1.0.4.tgz",
"integrity": "sha512-JQHZ2QMW6l3aH/j6xCqQThY/9OH4D/9ls34cgkUBiEeocRTU04tHfKPBsUK1PqZCUQM7GiA0IIXJSuXHI64Kbg==",
"dev": true,
"optional": true,
"engines": {
"node": ">=0.8"
}
},
"node_modules/clone-deep": {
"version": "4.0.1",
"resolved": "https://registry.npmjs.org/clone-deep/-/clone-deep-4.0.1.tgz",
@ -7957,6 +8032,19 @@
"url": "https://github.com/sponsors/sindresorhus"
}
},
"node_modules/defaults": {
"version": "1.0.4",
"resolved": "https://registry.npmjs.org/defaults/-/defaults-1.0.4.tgz",
"integrity": "sha512-eFuaLoy/Rxalv2kr+lqMlUnrDWV+3j4pljOIJgLIhI058IQfWJ7vXhyEIHu+HtC738klGALYxOKDO0bQP3tg8A==",
"dev": true,
"optional": true,
"dependencies": {
"clone": "^1.0.2"
},
"funding": {
"url": "https://github.com/sponsors/sindresorhus"
}
},
"node_modules/define-data-property": {
"version": "1.1.4",
"resolved": "https://registry.npmjs.org/define-data-property/-/define-data-property-1.1.4.tgz",
@ -8207,6 +8295,27 @@
"integrity": "sha512-I88TYZWc9XiYHRQ4/3c5rjjfgkjhLyW2luGIheGERbNQ6OY7yTybanSpDXZa8y7VUP9YmDcYa+eyq4ca7iLqWA==",
"dev": true
},
"node_modules/easy-table": {
"version": "1.2.0",
"resolved": "https://registry.npmjs.org/easy-table/-/easy-table-1.2.0.tgz",
"integrity": "sha512-OFzVOv03YpvtcWGe5AayU5G2hgybsg3iqA6drU8UaoZyB9jLGMTrz9+asnLp/E+6qPh88yEI1gvyZFZ41dmgww==",
"dev": true,
"dependencies": {
"ansi-regex": "^5.0.1"
},
"optionalDependencies": {
"wcwidth": "^1.0.1"
}
},
"node_modules/easy-table/node_modules/ansi-regex": {
"version": "5.0.1",
"resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz",
"integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==",
"dev": true,
"engines": {
"node": ">=8"
}
},
"node_modules/ecdsa-sig-formatter": {
"version": "1.0.11",
"resolved": "https://registry.npmjs.org/ecdsa-sig-formatter/-/ecdsa-sig-formatter-1.0.11.tgz",
@ -8299,9 +8408,9 @@
}
},
"node_modules/enhanced-resolve": {
"version": "5.17.1",
"resolved": "https://registry.npmjs.org/enhanced-resolve/-/enhanced-resolve-5.17.1.tgz",
"integrity": "sha512-LMHl3dXhTcfv8gM4kEzIUeTQ+7fpdA0l2tUf34BddXPkz2A5xJ5L/Pchd5BL6rdccM9QGvu0sWZzK1Z1t4wwyg==",
"version": "5.18.1",
"resolved": "https://registry.npmjs.org/enhanced-resolve/-/enhanced-resolve-5.18.1.tgz",
"integrity": "sha512-ZSW3ma5GkcQBIpwZTSRAI8N71Uuwgs93IezB7mf7R60tC8ZbJideoDNKjHn2O9KIlx6rkGTTEk1xUCK2E1Y2Yg==",
"dev": true,
"dependencies": {
"graceful-fs": "^4.2.4",
@ -8947,15 +9056,15 @@
"integrity": "sha512-/d9sfos4yxzpwkDkuN7k2SqFKtYNmCTzgfEpz82x34IM9/zc8KGxQoXg1liNC/izpRM/MBdt44Nmx41ZWqk+FQ=="
},
"node_modules/fast-glob": {
"version": "3.3.2",
"resolved": "https://registry.npmjs.org/fast-glob/-/fast-glob-3.3.2.tgz",
"integrity": "sha512-oX2ruAFQwf/Orj8m737Y5adxDQO0LAB7/S5MnxCdTNDd4p6BsyIVsv9JQsATbTSq8KHRpLwIHbVlUNatxd+1Ow==",
"version": "3.3.3",
"resolved": "https://registry.npmjs.org/fast-glob/-/fast-glob-3.3.3.tgz",
"integrity": "sha512-7MptL8U0cqcFdzIzwOTHoilX9x5BrNqye7Z/LuC7kCMRio1EMSyqRK3BEAUD7sXRq4iT4AzTVuZdhgQ2TCvYLg==",
"dependencies": {
"@nodelib/fs.stat": "^2.0.2",
"@nodelib/fs.walk": "^1.2.3",
"glob-parent": "^5.1.2",
"merge2": "^1.3.0",
"micromatch": "^4.0.4"
"micromatch": "^4.0.8"
},
"engines": {
"node": ">=8.6.0"
@ -9957,6 +10066,15 @@
"node": ">=0.8.19"
}
},
"node_modules/indent-string": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/indent-string/-/indent-string-4.0.0.tgz",
"integrity": "sha512-EdDDZu4A2OyIK7Lr/2zG+w5jmbuk1DVBnEwREQvBzspBJkCEbRa8GxU1lghYcaGJCnRWibjDXlq779X1/y5xwg==",
"dev": true,
"engines": {
"node": ">=8"
}
},
"node_modules/inflight": {
"version": "1.0.6",
"resolved": "https://registry.npmjs.org/inflight/-/inflight-1.0.6.tgz",
@ -11195,7 +11313,8 @@
"version": "1.0.5",
"resolved": "https://registry.npmjs.org/jest-simple-dot-reporter/-/jest-simple-dot-reporter-1.0.5.tgz",
"integrity": "sha512-cZLFG/C7k0+WYoIGGuGXKm0vmJiXlWG/m3uCZ4RaMPYxt8lxjdXMLHYkxXaQ7gVWaSPe7uAPCEUcRxthC5xskg==",
"dev": true
"dev": true,
"license": "MIT"
},
"node_modules/jest-snapshot": {
"version": "29.7.0",
@ -11323,6 +11442,15 @@
"url": "https://github.com/chalk/supports-color?sponsor=1"
}
},
"node_modules/jiti": {
"version": "2.4.2",
"resolved": "https://registry.npmjs.org/jiti/-/jiti-2.4.2.tgz",
"integrity": "sha512-rg9zJN+G4n2nfJl5MW3BMygZX56zKPNVEYYqq7adpmMh4Jn2QNEwhvQlFy6jPVdcod7txZtKHWnyZiA3a0zP7A==",
"dev": true,
"bin": {
"jiti": "lib/jiti-cli.mjs"
}
},
"node_modules/js-tokens": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz",
@ -11472,6 +11600,114 @@
"node": ">=6"
}
},
"node_modules/knip": {
"version": "5.44.4",
"resolved": "https://registry.npmjs.org/knip/-/knip-5.44.4.tgz",
"integrity": "sha512-Ryn8LwWHLId8jSK1DgtT0hmg5DbzkqAtH+Gg3vZJpmSMgGHMspej9Ag+qKTm8wsPLDjVetuEz/lIsobo0XCMvQ==",
"dev": true,
"funding": [
{
"type": "github",
"url": "https://github.com/sponsors/webpro"
},
{
"type": "opencollective",
"url": "https://opencollective.com/knip"
},
{
"type": "polar",
"url": "https://polar.sh/webpro-nl"
}
],
"dependencies": {
"@nodelib/fs.walk": "3.0.1",
"@snyk/github-codeowners": "1.1.0",
"easy-table": "1.2.0",
"enhanced-resolve": "^5.18.0",
"fast-glob": "^3.3.3",
"jiti": "^2.4.2",
"js-yaml": "^4.1.0",
"minimist": "^1.2.8",
"picocolors": "^1.1.0",
"picomatch": "^4.0.1",
"pretty-ms": "^9.0.0",
"smol-toml": "^1.3.1",
"strip-json-comments": "5.0.1",
"summary": "2.1.0",
"zod": "^3.22.4",
"zod-validation-error": "^3.0.3"
},
"bin": {
"knip": "bin/knip.js",
"knip-bun": "bin/knip-bun.js"
},
"engines": {
"node": ">=18.18.0"
},
"peerDependencies": {
"@types/node": ">=18",
"typescript": ">=5.0.4"
}
},
"node_modules/knip/node_modules/@nodelib/fs.scandir": {
"version": "4.0.1",
"resolved": "https://registry.npmjs.org/@nodelib/fs.scandir/-/fs.scandir-4.0.1.tgz",
"integrity": "sha512-vAkI715yhnmiPupY+dq+xenu5Tdf2TBQ66jLvBIcCddtz+5Q8LbMKaf9CIJJreez8fQ8fgaY+RaywQx8RJIWpw==",
"dev": true,
"dependencies": {
"@nodelib/fs.stat": "4.0.0",
"run-parallel": "^1.2.0"
},
"engines": {
"node": ">=18.18.0"
}
},
"node_modules/knip/node_modules/@nodelib/fs.stat": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/@nodelib/fs.stat/-/fs.stat-4.0.0.tgz",
"integrity": "sha512-ctr6bByzksKRCV0bavi8WoQevU6plSp2IkllIsEqaiKe2mwNNnaluhnRhcsgGZHrrHk57B3lf95MkLMO3STYcg==",
"dev": true,
"engines": {
"node": ">=18.18.0"
}
},
"node_modules/knip/node_modules/@nodelib/fs.walk": {
"version": "3.0.1",
"resolved": "https://registry.npmjs.org/@nodelib/fs.walk/-/fs.walk-3.0.1.tgz",
"integrity": "sha512-nIh/M6Kh3ZtOmlY00DaUYB4xeeV6F3/ts1l29iwl3/cfyY/OuCfUx+v08zgx8TKPTifXRcjjqVQ4KB2zOYSbyw==",
"dev": true,
"dependencies": {
"@nodelib/fs.scandir": "4.0.1",
"fastq": "^1.15.0"
},
"engines": {
"node": ">=18.18.0"
}
},
"node_modules/knip/node_modules/picomatch": {
"version": "4.0.2",
"resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.2.tgz",
"integrity": "sha512-M7BAV6Rlcy5u+m6oPhAPFgJTzAioX/6B0DxyvDlo9l8+T3nLKbrczg2WLUyzd45L8RqfUMyGPzekbMvX2Ldkwg==",
"dev": true,
"engines": {
"node": ">=12"
},
"funding": {
"url": "https://github.com/sponsors/jonschlinkert"
}
},
"node_modules/knip/node_modules/strip-json-comments": {
"version": "5.0.1",
"resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-5.0.1.tgz",
"integrity": "sha512-0fk9zBqO67Nq5M/m45qHCJxylV/DhBlIOVExqgOMiCCrzrhU6tCibRXNqE3jwJLftzE9SNuZtYbpzcO+i9FiKw==",
"dev": true,
"engines": {
"node": ">=14.16"
},
"funding": {
"url": "https://github.com/sponsors/sindresorhus"
}
},
"node_modules/leven": {
"version": "3.1.0",
"resolved": "https://registry.npmjs.org/leven/-/leven-3.1.0.tgz",
@ -12205,6 +12441,15 @@
"url": "https://github.com/sponsors/isaacs"
}
},
"node_modules/minimist": {
"version": "1.2.8",
"resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.8.tgz",
"integrity": "sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA==",
"dev": true,
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/minipass": {
"version": "7.1.2",
"resolved": "https://registry.npmjs.org/minipass/-/minipass-7.1.2.tgz",
@ -13170,6 +13415,18 @@
"url": "https://github.com/sponsors/sindresorhus"
}
},
"node_modules/parse-ms": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/parse-ms/-/parse-ms-4.0.0.tgz",
"integrity": "sha512-TXfryirbmq34y8QBwgqCVLi+8oA3oWx2eAnSn62ITyEhEYaWRlVZ2DvMM9eZbMs/RfxPu/PK/aBLyGj4IrqMHw==",
"dev": true,
"engines": {
"node": ">=18"
},
"funding": {
"url": "https://github.com/sponsors/sindresorhus"
}
},
"node_modules/parse5": {
"version": "7.2.1",
"resolved": "https://registry.npmjs.org/parse5/-/parse5-7.2.1.tgz",
@ -13480,6 +13737,21 @@
"url": "https://github.com/chalk/ansi-styles?sponsor=1"
}
},
"node_modules/pretty-ms": {
"version": "9.2.0",
"resolved": "https://registry.npmjs.org/pretty-ms/-/pretty-ms-9.2.0.tgz",
"integrity": "sha512-4yf0QO/sllf/1zbZWYnvWw3NxCQwLXKzIj0G849LSufP15BXKM0rbD2Z3wVnkMfjdn/CB0Dpp444gYAACdsplg==",
"dev": true,
"dependencies": {
"parse-ms": "^4.0.0"
},
"engines": {
"node": ">=18"
},
"funding": {
"url": "https://github.com/sponsors/sindresorhus"
}
},
"node_modules/process-nextick-args": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/process-nextick-args/-/process-nextick-args-2.0.1.tgz",
@ -14340,6 +14612,18 @@
"npm": ">= 3.0.0"
}
},
"node_modules/smol-toml": {
"version": "1.3.1",
"resolved": "https://registry.npmjs.org/smol-toml/-/smol-toml-1.3.1.tgz",
"integrity": "sha512-tEYNll18pPKHroYSmLLrksq233j021G0giwW7P3D24jC54pQ5W5BXMsQ/Mvw1OJCmEYDgY+lrzT+3nNUtoNfXQ==",
"dev": true,
"engines": {
"node": ">= 18"
},
"funding": {
"url": "https://github.com/sponsors/cyyynthia"
}
},
"node_modules/socks": {
"version": "2.8.3",
"resolved": "https://registry.npmjs.org/socks/-/socks-2.8.3.tgz",
@ -14761,6 +15045,12 @@
"resolved": "https://registry.npmjs.org/strnum/-/strnum-1.0.5.tgz",
"integrity": "sha512-J8bbNyKKXl5qYcR36TIO8W3mVGVHrmmxsd5PAItGkmyzwJvybiw2IVq5nqd0i4LSNSkB/sx9VHllbfFdr9k1JA=="
},
"node_modules/summary": {
"version": "2.1.0",
"resolved": "https://registry.npmjs.org/summary/-/summary-2.1.0.tgz",
"integrity": "sha512-nMIjMrd5Z2nuB2RZCKJfFMjgS3fygbeyGk9PxPPaJR1RIcyN9yn4A63Isovzm3ZtQuEkLBVgMdPup8UeLH7aQw==",
"dev": true
},
"node_modules/supports-color": {
"version": "9.4.0",
"resolved": "https://registry.npmjs.org/supports-color/-/supports-color-9.4.0.tgz",
@ -15336,6 +15626,16 @@
"makeerror": "1.0.12"
}
},
"node_modules/wcwidth": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/wcwidth/-/wcwidth-1.0.1.tgz",
"integrity": "sha512-XHPEwS0q6TaxcvG85+8EYkbiCux2XtWG2mkc47Ng2A77BQu9+DqIOJldST4HgPkuea7dvKSj5VgX3P1d4rW8Tg==",
"dev": true,
"optional": true,
"dependencies": {
"defaults": "^1.0.3"
}
},
"node_modules/web-streams-polyfill": {
"version": "4.0.0-beta.3",
"resolved": "https://registry.npmjs.org/web-streams-polyfill/-/web-streams-polyfill-4.0.0-beta.3.tgz",
@ -15962,6 +16262,18 @@
"funding": {
"url": "https://github.com/sponsors/colinhacks"
}
},
"node_modules/zod-validation-error": {
"version": "3.4.0",
"resolved": "https://registry.npmjs.org/zod-validation-error/-/zod-validation-error-3.4.0.tgz",
"integrity": "sha512-ZOPR9SVY6Pb2qqO5XHt+MkkTRxGXb4EVtnjc9JpXUOtUB1T9Ru7mZOT361AN3MsetVe7R0a1KZshJDZdgp9miQ==",
"dev": true,
"engines": {
"node": ">=18.0.0"
},
"peerDependencies": {
"zod": "^3.18.0"
}
}
}
}

View file

@ -1,9 +1,9 @@
{
"name": "roo-cline",
"displayName": "Roo Code (prev. Roo Cline)",
"description": "An AI-powered autonomous coding agent that lives in your editor.",
"description": "A whole dev team of AI agents in your editor.",
"publisher": "RooVeterinaryInc",
"version": "3.3.23",
"version": "3.7.5",
"icon": "assets/icons/rocket.png",
"galleryBanner": {
"color": "#617A91",
@ -277,10 +277,11 @@
"build": "npm run build:webview && npm run vsix",
"build:webview": "cd webview-ui && npm run build",
"changeset": "changeset",
"check-types": "tsc --noEmit",
"check-types": "tsc --noEmit && cd webview-ui && npm run check-types",
"compile": "tsc -p . --outDir out && node esbuild.js",
"compile:integration": "tsc -p tsconfig.integration.json",
"install:all": "npm install && cd webview-ui && npm install",
"knip": "knip --include files",
"lint": "eslint src --ext ts && npm run lint --prefix webview-ui",
"lint-local": "eslint -c .eslintrc.local.json src --ext ts && npm run lint --prefix webview-ui",
"lint-fix": "eslint src --ext ts --fix && npm run lint-fix --prefix webview-ui",
@ -288,8 +289,7 @@
"package": "npm run build:webview && npm run check-types && npm run lint && node esbuild.js --production",
"pretest": "npm run compile && npm run compile:integration",
"dev": "cd webview-ui && npm run dev",
"test": "jest && npm run test:webview",
"test:webview": "cd webview-ui && npm run test",
"test": "jest && cd webview-ui && npm run test",
"test:integration": "npm run build && npm run compile:integration && npx dotenvx run -f .env.integration -- node ./out-integration/test/runTest.js",
"prepare": "husky",
"publish:marketplace": "vsce publish && ovsx publish",
@ -304,7 +304,7 @@
},
"dependencies": {
"@anthropic-ai/bedrock-sdk": "^0.10.2",
"@anthropic-ai/sdk": "^0.26.0",
"@anthropic-ai/sdk": "^0.37.0",
"@anthropic-ai/vertex-sdk": "^0.4.1",
"@aws-sdk/client-bedrock-runtime": "^3.706.0",
"@google/generative-ai": "^0.18.0",
@ -371,6 +371,7 @@
"husky": "^9.1.7",
"jest": "^29.7.0",
"jest-simple-dot-reporter": "^1.0.5",
"knip": "^5.44.4",
"lint-staged": "^15.2.11",
"mkdirp": "^3.0.1",
"mocha": "^11.1.0",

View file

@ -0,0 +1,17 @@
// Mock the logger globally for all tests
jest.mock("../utils/logging", () => ({
logger: {
debug: jest.fn(),
info: jest.fn(),
warn: jest.fn(),
error: jest.fn(),
fatal: jest.fn(),
child: jest.fn().mockReturnValue({
debug: jest.fn(),
info: jest.fn(),
warn: jest.fn(),
error: jest.fn(),
fatal: jest.fn(),
}),
},
}))

View file

@ -1,50 +1,13 @@
// npx jest src/api/providers/__tests__/anthropic.test.ts
import { AnthropicHandler } from "../anthropic"
import { ApiHandlerOptions } from "../../../shared/api"
import { ApiStream } from "../../transform/stream"
import { Anthropic } from "@anthropic-ai/sdk"
// Mock Anthropic client
const mockBetaCreate = jest.fn()
const mockCreate = jest.fn()
jest.mock("@anthropic-ai/sdk", () => {
return {
Anthropic: jest.fn().mockImplementation(() => ({
beta: {
promptCaching: {
messages: {
create: mockBetaCreate.mockImplementation(async () => ({
async *[Symbol.asyncIterator]() {
yield {
type: "message_start",
message: {
usage: {
input_tokens: 100,
output_tokens: 50,
cache_creation_input_tokens: 20,
cache_read_input_tokens: 10,
},
},
}
yield {
type: "content_block_start",
index: 0,
content_block: {
type: "text",
text: "Hello",
},
}
yield {
type: "content_block_delta",
delta: {
type: "text_delta",
text: " world",
},
}
},
})),
},
},
},
messages: {
create: mockCreate.mockImplementation(async (options) => {
if (!options.stream) {
@ -65,16 +28,26 @@ jest.mock("@anthropic-ai/sdk", () => {
type: "message_start",
message: {
usage: {
input_tokens: 10,
output_tokens: 5,
input_tokens: 100,
output_tokens: 50,
cache_creation_input_tokens: 20,
cache_read_input_tokens: 10,
},
},
}
yield {
type: "content_block_start",
index: 0,
content_block: {
type: "text",
text: "Test response",
text: "Hello",
},
}
yield {
type: "content_block_delta",
delta: {
type: "text_delta",
text: " world",
},
}
},
@ -95,7 +68,6 @@ describe("AnthropicHandler", () => {
apiModelId: "claude-3-5-sonnet-20241022",
}
handler = new AnthropicHandler(mockOptions)
mockBetaCreate.mockClear()
mockCreate.mockClear()
})
@ -126,17 +98,6 @@ describe("AnthropicHandler", () => {
describe("createMessage", () => {
const systemPrompt = "You are a helpful assistant."
const messages: Anthropic.Messages.MessageParam[] = [
{
role: "user",
content: [
{
type: "text" as const,
text: "Hello!",
},
],
},
]
it("should handle prompt caching for supported models", async () => {
const stream = handler.createMessage(systemPrompt, [
@ -173,9 +134,8 @@ describe("AnthropicHandler", () => {
expect(textChunks[0].text).toBe("Hello")
expect(textChunks[1].text).toBe(" world")
// Verify beta API was used
expect(mockBetaCreate).toHaveBeenCalled()
expect(mockCreate).not.toHaveBeenCalled()
// Verify API
expect(mockCreate).toHaveBeenCalled()
})
})

View file

@ -1,9 +1,11 @@
import { GlamaHandler } from "../glama"
import { ApiHandlerOptions } from "../../../shared/api"
import OpenAI from "openai"
// npx jest src/api/providers/__tests__/glama.test.ts
import { Anthropic } from "@anthropic-ai/sdk"
import axios from "axios"
import { GlamaHandler } from "../glama"
import { ApiHandlerOptions } from "../../../shared/api"
// Mock OpenAI client
const mockCreate = jest.fn()
const mockWithResponse = jest.fn()
@ -71,8 +73,8 @@ describe("GlamaHandler", () => {
beforeEach(() => {
mockOptions = {
apiModelId: "anthropic/claude-3-5-sonnet",
glamaModelId: "anthropic/claude-3-5-sonnet",
apiModelId: "anthropic/claude-3-7-sonnet",
glamaModelId: "anthropic/claude-3-7-sonnet",
glamaApiKey: "test-api-key",
}
handler = new GlamaHandler(mockOptions)

View file

@ -1,3 +1,5 @@
// npx jest src/api/providers/__tests__/openrouter.test.ts
import { OpenRouterHandler } from "../openrouter"
import { ApiHandlerOptions, ModelInfo } from "../../../shared/api"
import OpenAI from "openai"
@ -55,7 +57,7 @@ describe("OpenRouterHandler", () => {
const handler = new OpenRouterHandler({})
const result = handler.getModel()
expect(result.id).toBe("anthropic/claude-3.5-sonnet:beta")
expect(result.id).toBe("anthropic/claude-3.7-sonnet")
expect(result.info.supportsPromptCache).toBe(true)
})

View file

@ -1,7 +1,10 @@
import { VertexHandler } from "../vertex"
// npx jest src/api/providers/__tests__/vertex.test.ts
import { Anthropic } from "@anthropic-ai/sdk"
import { AnthropicVertex } from "@anthropic-ai/vertex-sdk"
import { VertexHandler } from "../vertex"
// Mock Vertex SDK
jest.mock("@anthropic-ai/vertex-sdk", () => ({
AnthropicVertex: jest.fn().mockImplementation(() => ({
@ -289,7 +292,7 @@ describe("VertexHandler", () => {
vertexRegion: "us-central1",
})
const modelInfo = invalidHandler.getModel()
expect(modelInfo.id).toBe("claude-3-5-sonnet-v2@20241022") // Default model
expect(modelInfo.id).toBe("claude-3-7-sonnet@20250219") // Default model
})
})
})

View file

@ -1,5 +1,7 @@
import { Anthropic } from "@anthropic-ai/sdk"
import { Stream as AnthropicStream } from "@anthropic-ai/sdk/streaming"
import { CacheControlEphemeral } from "@anthropic-ai/sdk/resources"
import { BetaThinkingConfigParam } from "@anthropic-ai/sdk/resources/beta"
import {
anthropicDefaultModelId,
AnthropicModelId,
@ -18,6 +20,7 @@ export class AnthropicHandler implements ApiHandler, SingleCompletionHandler {
constructor(options: ApiHandlerOptions) {
this.options = options
this.client = new Anthropic({
apiKey: this.options.apiKey,
baseURL: this.options.anthropicBaseUrl || undefined,
@ -25,45 +28,60 @@ export class AnthropicHandler implements ApiHandler, SingleCompletionHandler {
}
async *createMessage(systemPrompt: string, messages: Anthropic.Messages.MessageParam[]): ApiStream {
let stream: AnthropicStream<Anthropic.Beta.PromptCaching.Messages.RawPromptCachingBetaMessageStreamEvent>
const modelId = this.getModel().id
let stream: AnthropicStream<Anthropic.Messages.RawMessageStreamEvent>
const cacheControl: CacheControlEphemeral = { type: "ephemeral" }
let { id: modelId, info: modelInfo } = this.getModel()
const maxTokens = modelInfo.maxTokens || 8192
let temperature = this.options.modelTemperature ?? ANTHROPIC_DEFAULT_TEMPERATURE
let thinking: BetaThinkingConfigParam | undefined = undefined
// Anthropic "Thinking" models require a temperature of 1.0.
if (modelId === "claude-3-7-sonnet-20250219:thinking") {
// The `:thinking` variant is a virtual identifier for the
// `claude-3-7-sonnet-20250219` model with a thinking budget.
// We can handle this more elegantly in the future.
modelId = "claude-3-7-sonnet-20250219"
const budgetTokens = this.options.anthropicThinking ?? Math.max(maxTokens * 0.8, 1024)
thinking = { type: "enabled", budget_tokens: budgetTokens }
temperature = 1.0
}
switch (modelId) {
// 'latest' alias does not support cache_control
case "claude-3-7-sonnet-20250219":
case "claude-3-5-sonnet-20241022":
case "claude-3-5-haiku-20241022":
case "claude-3-opus-20240229":
case "claude-3-haiku-20240307": {
/*
The latest message will be the new user message, one before will be the assistant message from a previous request, and the user message before that will be a previously cached user message. So we need to mark the latest user message as ephemeral to cache it for the next request, and mark the second to last user message as ephemeral to let the server know the last message to retrieve from the cache for the current request..
*/
/**
* The latest message will be the new user message, one before will
* be the assistant message from a previous request, and the user message before that will be a previously cached user message. So we need to mark the latest user message as ephemeral to cache it for the next request, and mark the second to last user message as ephemeral to let the server know the last message to retrieve from the cache for the current request..
*/
const userMsgIndices = messages.reduce(
(acc, msg, index) => (msg.role === "user" ? [...acc, index] : acc),
[] as number[],
)
const lastUserMsgIndex = userMsgIndices[userMsgIndices.length - 1] ?? -1
const secondLastMsgUserIndex = userMsgIndices[userMsgIndices.length - 2] ?? -1
stream = await this.client.beta.promptCaching.messages.create(
stream = await this.client.messages.create(
{
model: modelId,
max_tokens: this.getModel().info.maxTokens || 8192,
temperature: this.options.modelTemperature ?? ANTHROPIC_DEFAULT_TEMPERATURE,
system: [{ text: systemPrompt, type: "text", cache_control: { type: "ephemeral" } }], // setting cache breakpoint for system prompt so new tasks can reuse it
max_tokens: maxTokens,
temperature,
thinking,
// Setting cache breakpoint for system prompt so new tasks can reuse it.
system: [{ text: systemPrompt, type: "text", cache_control: cacheControl }],
messages: messages.map((message, index) => {
if (index === lastUserMsgIndex || index === secondLastMsgUserIndex) {
return {
...message,
content:
typeof message.content === "string"
? [
{
type: "text",
text: message.content,
cache_control: { type: "ephemeral" },
},
]
? [{ type: "text", text: message.content, cache_control: cacheControl }]
: message.content.map((content, contentIndex) =>
contentIndex === message.content.length - 1
? { ...content, cache_control: { type: "ephemeral" } }
? { ...content, cache_control: cacheControl }
: content,
),
}
@ -97,8 +115,8 @@ export class AnthropicHandler implements ApiHandler, SingleCompletionHandler {
default: {
stream = (await this.client.messages.create({
model: modelId,
max_tokens: this.getModel().info.maxTokens || 8192,
temperature: this.options.modelTemperature ?? ANTHROPIC_DEFAULT_TEMPERATURE,
max_tokens: maxTokens,
temperature,
system: [{ text: systemPrompt, type: "text" }],
messages,
// tools,
@ -112,8 +130,9 @@ export class AnthropicHandler implements ApiHandler, SingleCompletionHandler {
for await (const chunk of stream) {
switch (chunk.type) {
case "message_start":
// tells us cache reads/writes/input/output
// Tells us cache reads/writes/input/output.
const usage = chunk.message.usage
yield {
type: "usage",
inputTokens: usage.input_tokens || 0,
@ -121,45 +140,53 @@ export class AnthropicHandler implements ApiHandler, SingleCompletionHandler {
cacheWriteTokens: usage.cache_creation_input_tokens || undefined,
cacheReadTokens: usage.cache_read_input_tokens || undefined,
}
break
case "message_delta":
// tells us stop_reason, stop_sequence, and output tokens along the way and at the end of the message
// Tells us stop_reason, stop_sequence, and output tokens
// along the way and at the end of the message.
yield {
type: "usage",
inputTokens: 0,
outputTokens: chunk.usage.output_tokens || 0,
}
break
case "message_stop":
// no usage data, just an indicator that the message is done
// No usage data, just an indicator that the message is done.
break
case "content_block_start":
switch (chunk.content_block.type) {
case "text":
// we may receive multiple text blocks, in which case just insert a line break between them
case "thinking":
// We may receive multiple text blocks, in which
// case just insert a line break between them.
if (chunk.index > 0) {
yield {
type: "text",
text: "\n",
}
yield { type: "reasoning", text: "\n" }
}
yield {
type: "text",
text: chunk.content_block.text,
yield { type: "reasoning", text: chunk.content_block.thinking }
break
case "text":
// We may receive multiple text blocks, in which
// case just insert a line break between them.
if (chunk.index > 0) {
yield { type: "text", text: "\n" }
}
yield { type: "text", text: chunk.content_block.text }
break
}
break
case "content_block_delta":
switch (chunk.delta.type) {
case "thinking_delta":
yield { type: "reasoning", text: chunk.delta.thinking }
break
case "text_delta":
yield {
type: "text",
text: chunk.delta.text,
}
yield { type: "text", text: chunk.delta.text }
break
}
break
case "content_block_stop":
break
@ -169,10 +196,12 @@ export class AnthropicHandler implements ApiHandler, SingleCompletionHandler {
getModel(): { id: AnthropicModelId; info: ModelInfo } {
const modelId = this.options.apiModelId
if (modelId && modelId in anthropicModels) {
const id = modelId as AnthropicModelId
return { id, info: anthropicModels[id] }
}
return { id: anthropicDefaultModelId, info: anthropicModels[anthropicDefaultModelId] }
}
@ -187,14 +216,17 @@ export class AnthropicHandler implements ApiHandler, SingleCompletionHandler {
})
const content = response.content[0]
if (content.type === "text") {
return content.text
}
return ""
} catch (error) {
if (error instanceof Error) {
throw new Error(`Anthropic completion error: ${error.message}`)
}
throw error
}
}

View file

@ -9,7 +9,7 @@ import { Anthropic } from "@anthropic-ai/sdk"
import { ApiHandler, SingleCompletionHandler } from "../"
import { ApiHandlerOptions, BedrockModelId, ModelInfo, bedrockDefaultModelId, bedrockModels } from "../../shared/api"
import { ApiStream } from "../transform/stream"
import { convertToBedrockConverseMessages, convertToAnthropicMessage } from "../transform/bedrock-converse-format"
import { convertToBedrockConverseMessages } from "../transform/bedrock-converse-format"
const BEDROCK_DEFAULT_TEMPERATURE = 0.3

View file

@ -1,10 +1,12 @@
import { Anthropic } from "@anthropic-ai/sdk"
import axios from "axios"
import OpenAI from "openai"
import { ApiHandler, SingleCompletionHandler } from "../"
import { ApiHandlerOptions, ModelInfo, glamaDefaultModelId, glamaDefaultModelInfo } from "../../shared/api"
import { parseApiPrice } from "../../utils/cost"
import { convertToOpenAiMessages } from "../transform/openai-format"
import { ApiStream } from "../transform/stream"
import { ApiHandler, SingleCompletionHandler } from "../"
const GLAMA_DEFAULT_TEMPERATURE = 0
@ -69,7 +71,7 @@ export class GlamaHandler implements ApiHandler, SingleCompletionHandler {
let maxTokens: number | undefined
if (this.getModel().id.startsWith("anthropic/")) {
maxTokens = 8_192
maxTokens = this.getModel().info.maxTokens
}
const requestOptions: OpenAI.Chat.ChatCompletionCreateParams = {
@ -177,7 +179,7 @@ export class GlamaHandler implements ApiHandler, SingleCompletionHandler {
}
if (this.getModel().id.startsWith("anthropic/")) {
requestOptions.max_tokens = 8192
requestOptions.max_tokens = this.getModel().info.maxTokens
}
const response = await this.client.chat.completions.create(requestOptions)
@ -190,3 +192,44 @@ export class GlamaHandler implements ApiHandler, SingleCompletionHandler {
}
}
}
export async function getGlamaModels() {
const models: Record<string, ModelInfo> = {}
try {
const response = await axios.get("https://glama.ai/api/gateway/v1/models")
const rawModels = response.data
for (const rawModel of rawModels) {
const modelInfo: ModelInfo = {
maxTokens: rawModel.maxTokensOutput,
contextWindow: rawModel.maxTokensInput,
supportsImages: rawModel.capabilities?.includes("input:image"),
supportsComputerUse: rawModel.capabilities?.includes("computer_use"),
supportsPromptCache: rawModel.capabilities?.includes("caching"),
inputPrice: parseApiPrice(rawModel.pricePerToken?.input),
outputPrice: parseApiPrice(rawModel.pricePerToken?.output),
description: undefined,
cacheWritesPrice: parseApiPrice(rawModel.pricePerToken?.cacheWrite),
cacheReadsPrice: parseApiPrice(rawModel.pricePerToken?.cacheRead),
}
switch (rawModel.id) {
case rawModel.id.startsWith("anthropic/claude-3-7-sonnet"):
modelInfo.maxTokens = 16384
break
case rawModel.id.startsWith("anthropic/"):
modelInfo.maxTokens = 8192
break
default:
break
}
models[rawModel.id] = modelInfo
}
} catch (error) {
console.error(`Error fetching Glama models: ${JSON.stringify(error, Object.getOwnPropertyNames(error), 2)}`)
}
return models
}

View file

@ -1,5 +1,7 @@
import { Anthropic } from "@anthropic-ai/sdk"
import OpenAI from "openai"
import axios from "axios"
import { ApiHandler, SingleCompletionHandler } from "../"
import { ApiHandlerOptions, ModelInfo, openAiModelInfoSaneDefaults } from "../../shared/api"
import { convertToOpenAiMessages } from "../transform/openai-format"
@ -72,3 +74,17 @@ export class LmStudioHandler implements ApiHandler, SingleCompletionHandler {
}
}
}
export async function getLmStudioModels(baseUrl = "http://localhost:1234") {
try {
if (!URL.canParse(baseUrl)) {
return []
}
const response = await axios.get(`${baseUrl}/v1/models`)
const modelsArray = response.data?.data?.map((model: any) => model.id) || []
return [...new Set<string>(modelsArray)]
} catch (error) {
return []
}
}

View file

@ -1,5 +1,7 @@
import { Anthropic } from "@anthropic-ai/sdk"
import OpenAI from "openai"
import axios from "axios"
import { ApiHandler, SingleCompletionHandler } from "../"
import { ApiHandlerOptions, ModelInfo, openAiModelInfoSaneDefaults } from "../../shared/api"
import { convertToOpenAiMessages } from "../transform/openai-format"
@ -88,3 +90,17 @@ export class OllamaHandler implements ApiHandler, SingleCompletionHandler {
}
}
}
export async function getOllamaModels(baseUrl = "http://localhost:11434") {
try {
if (!URL.canParse(baseUrl)) {
return []
}
const response = await axios.get(`${baseUrl}/api/tags`)
const modelsArray = response.data?.models?.map((model: any) => model.name) || []
return [...new Set<string>(modelsArray)]
} catch (error) {
return []
}
}

View file

@ -1,5 +1,6 @@
import { Anthropic } from "@anthropic-ai/sdk"
import OpenAI, { AzureOpenAI } from "openai"
import axios from "axios"
import {
ApiHandlerOptions,
@ -166,3 +167,27 @@ export class OpenAiHandler implements ApiHandler, SingleCompletionHandler {
}
}
}
export async function getOpenAiModels(baseUrl?: string, apiKey?: string) {
try {
if (!baseUrl) {
return []
}
if (!URL.canParse(baseUrl)) {
return []
}
const config: Record<string, any> = {}
if (apiKey) {
config["headers"] = { Authorization: `Bearer ${apiKey}` }
}
const response = await axios.get(`${baseUrl}/models`, config)
const modelsArray = response.data?.data?.map((model: any) => model.id) || []
return [...new Set<string>(modelsArray)]
} catch (error) {
return []
}
}

View file

@ -1,29 +1,31 @@
import { Anthropic } from "@anthropic-ai/sdk"
import { BetaThinkingConfigParam } from "@anthropic-ai/sdk/resources/beta"
import axios from "axios"
import OpenAI from "openai"
import { ApiHandler } from "../"
import delay from "delay"
import { ApiHandlerOptions, ModelInfo, openRouterDefaultModelId, openRouterDefaultModelInfo } from "../../shared/api"
import { parseApiPrice } from "../../utils/cost"
import { convertToOpenAiMessages } from "../transform/openai-format"
import { ApiStreamChunk, ApiStreamUsageChunk } from "../transform/stream"
import delay from "delay"
import { convertToR1Format } from "../transform/r1-format"
import { DEEP_SEEK_DEFAULT_TEMPERATURE } from "./openai"
import { ApiHandler, SingleCompletionHandler } from ".."
const OPENROUTER_DEFAULT_TEMPERATURE = 0
// Add custom interface for OpenRouter params
// Add custom interface for OpenRouter params.
type OpenRouterChatCompletionParams = OpenAI.Chat.ChatCompletionCreateParams & {
transforms?: string[]
include_reasoning?: boolean
thinking?: BetaThinkingConfigParam
}
// Add custom interface for OpenRouter usage chunk
// Add custom interface for OpenRouter usage chunk.
interface OpenRouterApiStreamUsageChunk extends ApiStreamUsageChunk {
fullResponseText: string
}
import { SingleCompletionHandler } from ".."
import { convertToR1Format } from "../transform/r1-format"
export class OpenRouterHandler implements ApiHandler, SingleCompletionHandler {
private options: ApiHandlerOptions
private client: OpenAI
@ -52,21 +54,12 @@ export class OpenRouterHandler implements ApiHandler, SingleCompletionHandler {
...convertToOpenAiMessages(messages),
]
const { id: modelId, info: modelInfo } = this.getModel()
// prompt caching: https://openrouter.ai/docs/prompt-caching
// this is specifically for claude models (some models may 'support prompt caching' automatically without this)
switch (this.getModel().id) {
case "anthropic/claude-3.5-sonnet":
case "anthropic/claude-3.5-sonnet:beta":
case "anthropic/claude-3.5-sonnet-20240620":
case "anthropic/claude-3.5-sonnet-20240620:beta":
case "anthropic/claude-3-5-haiku":
case "anthropic/claude-3-5-haiku:beta":
case "anthropic/claude-3-5-haiku-20241022":
case "anthropic/claude-3-5-haiku-20241022:beta":
case "anthropic/claude-3-haiku":
case "anthropic/claude-3-haiku:beta":
case "anthropic/claude-3-opus":
case "anthropic/claude-3-opus:beta":
switch (true) {
case modelId.startsWith("anthropic/"):
openAiMessages[0] = {
role: "system",
content: [
@ -102,30 +95,11 @@ export class OpenRouterHandler implements ApiHandler, SingleCompletionHandler {
break
}
// Not sure how openrouter defaults max tokens when no value is provided, but the anthropic api requires this value and since they offer both 4096 and 8192 variants, we should ensure 8192.
// (models usually default to max tokens allowed)
let maxTokens: number | undefined
switch (this.getModel().id) {
case "anthropic/claude-3.5-sonnet":
case "anthropic/claude-3.5-sonnet:beta":
case "anthropic/claude-3.5-sonnet-20240620":
case "anthropic/claude-3.5-sonnet-20240620:beta":
case "anthropic/claude-3-5-haiku":
case "anthropic/claude-3-5-haiku:beta":
case "anthropic/claude-3-5-haiku-20241022":
case "anthropic/claude-3-5-haiku-20241022:beta":
maxTokens = 8_192
break
}
let defaultTemperature = OPENROUTER_DEFAULT_TEMPERATURE
let topP: number | undefined = undefined
// Handle models based on deepseek-r1
if (
this.getModel().id.startsWith("deepseek/deepseek-r1") ||
this.getModel().id === "perplexity/sonar-reasoning"
) {
if (modelId.startsWith("deepseek/deepseek-r1") || modelId === "perplexity/sonar-reasoning") {
// Recommended temperature for DeepSeek reasoning models
defaultTemperature = DEEP_SEEK_DEFAULT_TEMPERATURE
// DeepSeek highly recommends using user instead of system role
@ -134,24 +108,38 @@ export class OpenRouterHandler implements ApiHandler, SingleCompletionHandler {
topP = 0.95
}
let temperature = this.options.modelTemperature ?? defaultTemperature
let thinking: BetaThinkingConfigParam | undefined = undefined
if (modelInfo.thinking) {
const maxTokens = modelInfo.maxTokens || 8192
const budgetTokens = this.options.anthropicThinking ?? Math.max(maxTokens * 0.8, 1024)
thinking = { type: "enabled", budget_tokens: budgetTokens }
temperature = 1.0
}
// https://openrouter.ai/docs/transforms
let fullResponseText = ""
const stream = await this.client.chat.completions.create({
model: this.getModel().id,
max_tokens: maxTokens,
temperature: this.options.modelTemperature ?? defaultTemperature,
const completionParams: OpenRouterChatCompletionParams = {
model: modelId,
max_tokens: modelInfo.maxTokens,
temperature,
thinking, // OpenRouter is temporarily supporting this.
top_p: topP,
messages: openAiMessages,
stream: true,
include_reasoning: true,
// This way, the transforms field will only be included in the parameters when openRouterUseMiddleOutTransform is true.
...(this.options.openRouterUseMiddleOutTransform && { transforms: ["middle-out"] }),
} as OpenRouterChatCompletionParams)
}
const stream = await this.client.chat.completions.create(completionParams)
let genId: string | undefined
for await (const chunk of stream as unknown as AsyncIterable<OpenAI.Chat.Completions.ChatCompletionChunk>) {
// openrouter returns an error object instead of the openai sdk throwing an error
// OpenRouter returns an error object instead of the OpenAI SDK throwing an error.
if ("error" in chunk) {
const error = chunk.error as { message?: string; code?: number }
console.error(`OpenRouter API Error: ${error?.code} - ${error?.message}`)
@ -163,12 +151,14 @@ export class OpenRouterHandler implements ApiHandler, SingleCompletionHandler {
}
const delta = chunk.choices[0]?.delta
if ("reasoning" in delta && delta.reasoning) {
yield {
type: "reasoning",
text: delta.reasoning,
} as ApiStreamChunk
}
if (delta?.content) {
fullResponseText += delta.content
yield {
@ -176,6 +166,7 @@ export class OpenRouterHandler implements ApiHandler, SingleCompletionHandler {
text: delta.content,
} as ApiStreamChunk
}
// if (chunk.usage) {
// yield {
// type: "usage",
@ -185,10 +176,12 @@ export class OpenRouterHandler implements ApiHandler, SingleCompletionHandler {
// }
}
// retry fetching generation details
// Retry fetching generation details.
let attempt = 0
while (attempt++ < 10) {
await delay(200) // FIXME: necessary delay to ensure generation endpoint is ready
try {
const response = await axios.get(`https://openrouter.ai/api/v1/generation?id=${genId}`, {
headers: {
@ -198,7 +191,7 @@ export class OpenRouterHandler implements ApiHandler, SingleCompletionHandler {
})
const generation = response.data?.data
console.log("OpenRouter generation details:", response.data)
yield {
type: "usage",
// cacheWriteTokens: 0,
@ -209,6 +202,7 @@ export class OpenRouterHandler implements ApiHandler, SingleCompletionHandler {
totalCost: generation?.total_cost || 0,
fullResponseText,
} as OpenRouterApiStreamUsageChunk
return
} catch (error) {
// ignore if fails
@ -216,13 +210,13 @@ export class OpenRouterHandler implements ApiHandler, SingleCompletionHandler {
}
}
}
getModel(): { id: string; info: ModelInfo } {
getModel() {
const modelId = this.options.openRouterModelId
const modelInfo = this.options.openRouterModelInfo
if (modelId && modelInfo) {
return { id: modelId, info: modelInfo }
}
return { id: openRouterDefaultModelId, info: openRouterDefaultModelInfo }
return modelId && modelInfo
? { id: modelId, info: modelInfo }
: { id: openRouterDefaultModelId, info: openRouterDefaultModelInfo }
}
async completePrompt(prompt: string): Promise<string> {
@ -245,7 +239,81 @@ export class OpenRouterHandler implements ApiHandler, SingleCompletionHandler {
if (error instanceof Error) {
throw new Error(`OpenRouter completion error: ${error.message}`)
}
throw error
}
}
}
export async function getOpenRouterModels() {
const models: Record<string, ModelInfo> = {}
try {
const response = await axios.get("https://openrouter.ai/api/v1/models")
const rawModels = response.data.data
for (const rawModel of rawModels) {
const modelInfo: ModelInfo = {
maxTokens: rawModel.top_provider?.max_completion_tokens,
contextWindow: rawModel.context_length,
supportsImages: rawModel.architecture?.modality?.includes("image"),
supportsPromptCache: false,
inputPrice: parseApiPrice(rawModel.pricing?.prompt),
outputPrice: parseApiPrice(rawModel.pricing?.completion),
description: rawModel.description,
thinking: rawModel.id === "anthropic/claude-3.7-sonnet:thinking",
}
// NOTE: this needs to be synced with api.ts/openrouter default model info.
switch (true) {
case rawModel.id.startsWith("anthropic/claude-3.7-sonnet"):
modelInfo.supportsComputerUse = true
modelInfo.supportsPromptCache = true
modelInfo.cacheWritesPrice = 3.75
modelInfo.cacheReadsPrice = 0.3
modelInfo.maxTokens = 16384
break
case rawModel.id.startsWith("anthropic/claude-3.5-sonnet-20240620"):
modelInfo.supportsPromptCache = true
modelInfo.cacheWritesPrice = 3.75
modelInfo.cacheReadsPrice = 0.3
modelInfo.maxTokens = 8192
break
case rawModel.id.startsWith("anthropic/claude-3.5-sonnet"):
modelInfo.supportsComputerUse = true
modelInfo.supportsPromptCache = true
modelInfo.cacheWritesPrice = 3.75
modelInfo.cacheReadsPrice = 0.3
modelInfo.maxTokens = 8192
break
case rawModel.id.startsWith("anthropic/claude-3-5-haiku"):
modelInfo.supportsPromptCache = true
modelInfo.cacheWritesPrice = 1.25
modelInfo.cacheReadsPrice = 0.1
modelInfo.maxTokens = 8192
break
case rawModel.id.startsWith("anthropic/claude-3-opus"):
modelInfo.supportsPromptCache = true
modelInfo.cacheWritesPrice = 18.75
modelInfo.cacheReadsPrice = 1.5
modelInfo.maxTokens = 8192
break
case rawModel.id.startsWith("anthropic/claude-3-haiku"):
default:
modelInfo.supportsPromptCache = true
modelInfo.cacheWritesPrice = 0.3
modelInfo.cacheReadsPrice = 0.03
modelInfo.maxTokens = 8192
break
}
models[rawModel.id] = modelInfo
}
} catch (error) {
console.error(
`Error fetching OpenRouter models: ${JSON.stringify(error, Object.getOwnPropertyNames(error), 2)}`,
)
}
return models
}

View file

@ -1,6 +1,9 @@
import { OpenAiHandler, OpenAiHandlerOptions } from "./openai"
import axios from "axios"
import { ModelInfo, requestyModelInfoSaneDefaults, requestyDefaultModelId } from "../../shared/api"
import { ApiStream, ApiStreamUsageChunk } from "../transform/stream"
import { parseApiPrice } from "../../utils/cost"
import { ApiStreamUsageChunk } from "../transform/stream"
import { OpenAiHandler, OpenAiHandlerOptions } from "./openai"
export class RequestyHandler extends OpenAiHandler {
constructor(options: OpenAiHandlerOptions) {
@ -38,3 +41,65 @@ export class RequestyHandler extends OpenAiHandler {
}
}
}
export async function getRequestyModels() {
const models: Record<string, ModelInfo> = {}
try {
const response = await axios.get("https://router.requesty.ai/v1/models")
const rawModels = response.data.data
for (const rawModel of rawModels) {
// {
// id: "anthropic/claude-3-5-sonnet-20240620",
// object: "model",
// created: 1740552655,
// owned_by: "system",
// input_price: 0.0000028,
// caching_price: 0.00000375,
// cached_price: 3e-7,
// output_price: 0.000015,
// max_output_tokens: 8192,
// context_window: 200000,
// supports_caching: true,
// description:
// "Anthropic's previous most intelligent model. High level of intelligence and capability. Excells in coding.",
// }
const modelInfo: ModelInfo = {
maxTokens: rawModel.max_output_tokens,
contextWindow: rawModel.context_window,
supportsPromptCache: rawModel.supports_caching,
inputPrice: parseApiPrice(rawModel.input_price),
outputPrice: parseApiPrice(rawModel.output_price),
description: rawModel.description,
cacheWritesPrice: parseApiPrice(rawModel.caching_price),
cacheReadsPrice: parseApiPrice(rawModel.cached_price),
}
switch (rawModel.id) {
case rawModel.id.startsWith("anthropic/claude-3-7-sonnet"):
modelInfo.supportsComputerUse = true
modelInfo.supportsImages = true
modelInfo.maxTokens = 16384
break
case rawModel.id.startsWith("anthropic/claude-3-5-sonnet-20241022"):
modelInfo.supportsComputerUse = true
modelInfo.supportsImages = true
modelInfo.maxTokens = 8192
break
case rawModel.id.startsWith("anthropic/"):
modelInfo.maxTokens = 8192
break
default:
break
}
models[rawModel.id] = modelInfo
}
} catch (error) {
console.error(`Error fetching Requesty models: ${JSON.stringify(error, Object.getOwnPropertyNames(error), 2)}`)
}
return models
}

View file

@ -1,9 +1,11 @@
import { Anthropic } from "@anthropic-ai/sdk"
import axios from "axios"
import OpenAI from "openai"
import { ApiHandler, SingleCompletionHandler } from "../"
import { ApiHandlerOptions, ModelInfo, unboundDefaultModelId, unboundDefaultModelInfo } from "../../shared/api"
import { convertToOpenAiMessages } from "../transform/openai-format"
import { ApiStream, ApiStreamUsageChunk } from "../transform/stream"
import { ApiHandler, SingleCompletionHandler } from "../"
interface UnboundUsage extends OpenAI.CompletionUsage {
cache_creation_input_tokens?: number
@ -71,7 +73,7 @@ export class UnboundHandler implements ApiHandler, SingleCompletionHandler {
let maxTokens: number | undefined
if (this.getModel().id.startsWith("anthropic/")) {
maxTokens = 8_192
maxTokens = this.getModel().info.maxTokens
}
const { data: completion, response } = await this.client.chat.completions
@ -150,7 +152,7 @@ export class UnboundHandler implements ApiHandler, SingleCompletionHandler {
}
if (this.getModel().id.startsWith("anthropic/")) {
requestOptions.max_tokens = 8192
requestOptions.max_tokens = this.getModel().info.maxTokens
}
const response = await this.client.chat.completions.create(requestOptions)
@ -163,3 +165,46 @@ export class UnboundHandler implements ApiHandler, SingleCompletionHandler {
}
}
}
export async function getUnboundModels() {
const models: Record<string, ModelInfo> = {}
try {
const response = await axios.get("https://api.getunbound.ai/models")
if (response.data) {
const rawModels: Record<string, any> = response.data
for (const [modelId, model] of Object.entries(rawModels)) {
const modelInfo: ModelInfo = {
maxTokens: model?.maxTokens ? parseInt(model.maxTokens) : undefined,
contextWindow: model?.contextWindow ? parseInt(model.contextWindow) : 0,
supportsImages: model?.supportsImages ?? false,
supportsPromptCache: model?.supportsPromptCaching ?? false,
supportsComputerUse: model?.supportsComputerUse ?? false,
inputPrice: model?.inputTokenPrice ? parseFloat(model.inputTokenPrice) : undefined,
outputPrice: model?.outputTokenPrice ? parseFloat(model.outputTokenPrice) : undefined,
cacheWritesPrice: model?.cacheWritePrice ? parseFloat(model.cacheWritePrice) : undefined,
cacheReadsPrice: model?.cacheReadPrice ? parseFloat(model.cacheReadPrice) : undefined,
}
switch (true) {
case modelId.startsWith("anthropic/claude-3-7-sonnet"):
modelInfo.maxTokens = 16384
break
case modelId.startsWith("anthropic/"):
modelInfo.maxTokens = 8192
break
default:
break
}
models[modelId] = modelInfo
}
}
} catch (error) {
console.error(`Error fetching Unbound models: ${JSON.stringify(error, Object.getOwnPropertyNames(error), 2)}`)
}
return models
}

View file

@ -1,5 +1,6 @@
import { Anthropic } from "@anthropic-ai/sdk"
import * as vscode from "vscode"
import { ApiHandler, SingleCompletionHandler } from "../"
import { calculateApiCost } from "../../utils/cost"
import { ApiStream } from "../transform/stream"
@ -545,3 +546,15 @@ export class VsCodeLmHandler implements ApiHandler, SingleCompletionHandler {
}
}
}
export async function getVsCodeLmModels() {
try {
const models = await vscode.lm.selectChatModels({})
return models || []
} catch (error) {
console.error(
`Error fetching VS Code LM models: ${JSON.stringify(error, Object.getOwnPropertyNames(error), 2)}`,
)
return []
}
}

View file

@ -1,250 +1,167 @@
import { convertToBedrockConverseMessages, convertToAnthropicMessage } from "../bedrock-converse-format"
// npx jest src/api/transform/__tests__/bedrock-converse-format.test.ts
import { convertToBedrockConverseMessages } from "../bedrock-converse-format"
import { Anthropic } from "@anthropic-ai/sdk"
import { ContentBlock, ToolResultContentBlock } from "@aws-sdk/client-bedrock-runtime"
import { StreamEvent } from "../../providers/bedrock"
describe("bedrock-converse-format", () => {
describe("convertToBedrockConverseMessages", () => {
test("converts simple text messages correctly", () => {
const messages: Anthropic.Messages.MessageParam[] = [
{ role: "user", content: "Hello" },
{ role: "assistant", content: "Hi there" },
]
describe("convertToBedrockConverseMessages", () => {
test("converts simple text messages correctly", () => {
const messages: Anthropic.Messages.MessageParam[] = [
{ role: "user", content: "Hello" },
{ role: "assistant", content: "Hi there" },
]
const result = convertToBedrockConverseMessages(messages)
const result = convertToBedrockConverseMessages(messages)
expect(result).toEqual([
{
role: "user",
content: [{ text: "Hello" }],
},
{
role: "assistant",
content: [{ text: "Hi there" }],
},
])
})
test("converts messages with images correctly", () => {
const messages: Anthropic.Messages.MessageParam[] = [
{
role: "user",
content: [
{
type: "text",
text: "Look at this image:",
},
{
type: "image",
source: {
type: "base64",
data: "SGVsbG8=", // "Hello" in base64
media_type: "image/jpeg" as const,
},
},
],
},
]
const result = convertToBedrockConverseMessages(messages)
if (!result[0] || !result[0].content) {
fail("Expected result to have content")
return
}
expect(result[0].role).toBe("user")
expect(result[0].content).toHaveLength(2)
expect(result[0].content[0]).toEqual({ text: "Look at this image:" })
const imageBlock = result[0].content[1] as ContentBlock
if ("image" in imageBlock && imageBlock.image && imageBlock.image.source) {
expect(imageBlock.image.format).toBe("jpeg")
expect(imageBlock.image.source).toBeDefined()
expect(imageBlock.image.source.bytes).toBeDefined()
} else {
fail("Expected image block not found")
}
})
test("converts tool use messages correctly", () => {
const messages: Anthropic.Messages.MessageParam[] = [
{
role: "assistant",
content: [
{
type: "tool_use",
id: "test-id",
name: "read_file",
input: {
path: "test.txt",
},
},
],
},
]
const result = convertToBedrockConverseMessages(messages)
if (!result[0] || !result[0].content) {
fail("Expected result to have content")
return
}
expect(result[0].role).toBe("assistant")
const toolBlock = result[0].content[0] as ContentBlock
if ("toolUse" in toolBlock && toolBlock.toolUse) {
expect(toolBlock.toolUse).toEqual({
toolUseId: "test-id",
name: "read_file",
input: "<read_file>\n<path>\ntest.txt\n</path>\n</read_file>",
})
} else {
fail("Expected tool use block not found")
}
})
test("converts tool result messages correctly", () => {
const messages: Anthropic.Messages.MessageParam[] = [
{
role: "assistant",
content: [
{
type: "tool_result",
tool_use_id: "test-id",
content: [{ type: "text", text: "File contents here" }],
},
],
},
]
const result = convertToBedrockConverseMessages(messages)
if (!result[0] || !result[0].content) {
fail("Expected result to have content")
return
}
expect(result[0].role).toBe("assistant")
const resultBlock = result[0].content[0] as ContentBlock
if ("toolResult" in resultBlock && resultBlock.toolResult) {
const expectedContent: ToolResultContentBlock[] = [{ text: "File contents here" }]
expect(resultBlock.toolResult).toEqual({
toolUseId: "test-id",
content: expectedContent,
status: "success",
})
} else {
fail("Expected tool result block not found")
}
})
test("handles text content correctly", () => {
const messages: Anthropic.Messages.MessageParam[] = [
{
role: "user",
content: [
{
type: "text",
text: "Hello world",
},
],
},
]
const result = convertToBedrockConverseMessages(messages)
if (!result[0] || !result[0].content) {
fail("Expected result to have content")
return
}
expect(result[0].role).toBe("user")
expect(result[0].content).toHaveLength(1)
const textBlock = result[0].content[0] as ContentBlock
expect(textBlock).toEqual({ text: "Hello world" })
})
expect(result).toEqual([
{
role: "user",
content: [{ text: "Hello" }],
},
{
role: "assistant",
content: [{ text: "Hi there" }],
},
])
})
describe("convertToAnthropicMessage", () => {
test("converts metadata events correctly", () => {
const event: StreamEvent = {
metadata: {
usage: {
inputTokens: 10,
outputTokens: 20,
test("converts messages with images correctly", () => {
const messages: Anthropic.Messages.MessageParam[] = [
{
role: "user",
content: [
{
type: "text",
text: "Look at this image:",
},
},
}
const result = convertToAnthropicMessage(event, "test-model")
expect(result).toEqual({
id: "",
type: "message",
role: "assistant",
model: "test-model",
usage: {
input_tokens: 10,
output_tokens: 20,
},
})
})
test("converts content block start events correctly", () => {
const event: StreamEvent = {
contentBlockStart: {
start: {
text: "Hello",
{
type: "image",
source: {
type: "base64",
data: "SGVsbG8=", // "Hello" in base64
media_type: "image/jpeg" as const,
},
},
},
}
],
},
]
const result = convertToAnthropicMessage(event, "test-model")
const result = convertToBedrockConverseMessages(messages)
expect(result).toEqual({
type: "message",
if (!result[0] || !result[0].content) {
fail("Expected result to have content")
return
}
expect(result[0].role).toBe("user")
expect(result[0].content).toHaveLength(2)
expect(result[0].content[0]).toEqual({ text: "Look at this image:" })
const imageBlock = result[0].content[1] as ContentBlock
if ("image" in imageBlock && imageBlock.image && imageBlock.image.source) {
expect(imageBlock.image.format).toBe("jpeg")
expect(imageBlock.image.source).toBeDefined()
expect(imageBlock.image.source.bytes).toBeDefined()
} else {
fail("Expected image block not found")
}
})
test("converts tool use messages correctly", () => {
const messages: Anthropic.Messages.MessageParam[] = [
{
role: "assistant",
content: [{ type: "text", text: "Hello" }],
model: "test-model",
})
})
test("converts content block delta events correctly", () => {
const event: StreamEvent = {
contentBlockDelta: {
delta: {
text: " world",
content: [
{
type: "tool_use",
id: "test-id",
name: "read_file",
input: {
path: "test.txt",
},
},
},
}
],
},
]
const result = convertToAnthropicMessage(event, "test-model")
const result = convertToBedrockConverseMessages(messages)
expect(result).toEqual({
type: "message",
role: "assistant",
content: [{ type: "text", text: " world" }],
model: "test-model",
if (!result[0] || !result[0].content) {
fail("Expected result to have content")
return
}
expect(result[0].role).toBe("assistant")
const toolBlock = result[0].content[0] as ContentBlock
if ("toolUse" in toolBlock && toolBlock.toolUse) {
expect(toolBlock.toolUse).toEqual({
toolUseId: "test-id",
name: "read_file",
input: "<read_file>\n<path>\ntest.txt\n</path>\n</read_file>",
})
})
} else {
fail("Expected tool use block not found")
}
})
test("converts message stop events correctly", () => {
const event: StreamEvent = {
messageStop: {
stopReason: "end_turn" as const,
},
}
const result = convertToAnthropicMessage(event, "test-model")
expect(result).toEqual({
type: "message",
test("converts tool result messages correctly", () => {
const messages: Anthropic.Messages.MessageParam[] = [
{
role: "assistant",
stop_reason: "end_turn",
stop_sequence: null,
model: "test-model",
content: [
{
type: "tool_result",
tool_use_id: "test-id",
content: [{ type: "text", text: "File contents here" }],
},
],
},
]
const result = convertToBedrockConverseMessages(messages)
if (!result[0] || !result[0].content) {
fail("Expected result to have content")
return
}
expect(result[0].role).toBe("assistant")
const resultBlock = result[0].content[0] as ContentBlock
if ("toolResult" in resultBlock && resultBlock.toolResult) {
const expectedContent: ToolResultContentBlock[] = [{ text: "File contents here" }]
expect(resultBlock.toolResult).toEqual({
toolUseId: "test-id",
content: expectedContent,
status: "success",
})
})
} else {
fail("Expected tool result block not found")
}
})
test("handles text content correctly", () => {
const messages: Anthropic.Messages.MessageParam[] = [
{
role: "user",
content: [
{
type: "text",
text: "Hello world",
},
],
},
]
const result = convertToBedrockConverseMessages(messages)
if (!result[0] || !result[0].content) {
fail("Expected result to have content")
return
}
expect(result[0].role).toBe("user")
expect(result[0].content).toHaveLength(1)
const textBlock = result[0].content[0] as ContentBlock
expect(textBlock).toEqual({ text: "Hello world" })
})
})

View file

@ -0,0 +1,338 @@
// npx jest src/api/transform/__tests__/gemini-format.test.ts
import { Anthropic } from "@anthropic-ai/sdk"
import { convertAnthropicMessageToGemini } from "../gemini-format"
describe("convertAnthropicMessageToGemini", () => {
it("should convert a simple text message", () => {
const anthropicMessage: Anthropic.Messages.MessageParam = {
role: "user",
content: "Hello, world!",
}
const result = convertAnthropicMessageToGemini(anthropicMessage)
expect(result).toEqual({
role: "user",
parts: [{ text: "Hello, world!" }],
})
})
it("should convert assistant role to model role", () => {
const anthropicMessage: Anthropic.Messages.MessageParam = {
role: "assistant",
content: "I'm an assistant",
}
const result = convertAnthropicMessageToGemini(anthropicMessage)
expect(result).toEqual({
role: "model",
parts: [{ text: "I'm an assistant" }],
})
})
it("should convert a message with text blocks", () => {
const anthropicMessage: Anthropic.Messages.MessageParam = {
role: "user",
content: [
{ type: "text", text: "First paragraph" },
{ type: "text", text: "Second paragraph" },
],
}
const result = convertAnthropicMessageToGemini(anthropicMessage)
expect(result).toEqual({
role: "user",
parts: [{ text: "First paragraph" }, { text: "Second paragraph" }],
})
})
it("should convert a message with an image", () => {
const anthropicMessage: Anthropic.Messages.MessageParam = {
role: "user",
content: [
{ type: "text", text: "Check out this image:" },
{
type: "image",
source: {
type: "base64",
media_type: "image/jpeg",
data: "base64encodeddata",
},
},
],
}
const result = convertAnthropicMessageToGemini(anthropicMessage)
expect(result).toEqual({
role: "user",
parts: [
{ text: "Check out this image:" },
{
inlineData: {
data: "base64encodeddata",
mimeType: "image/jpeg",
},
},
],
})
})
it("should throw an error for unsupported image source type", () => {
const anthropicMessage: Anthropic.Messages.MessageParam = {
role: "user",
content: [
{
type: "image",
source: {
type: "url", // Not supported
url: "https://example.com/image.jpg",
} as any,
},
],
}
expect(() => convertAnthropicMessageToGemini(anthropicMessage)).toThrow("Unsupported image source type")
})
it("should convert a message with tool use", () => {
const anthropicMessage: Anthropic.Messages.MessageParam = {
role: "assistant",
content: [
{ type: "text", text: "Let me calculate that for you." },
{
type: "tool_use",
id: "calc-123",
name: "calculator",
input: { operation: "add", numbers: [2, 3] },
},
],
}
const result = convertAnthropicMessageToGemini(anthropicMessage)
expect(result).toEqual({
role: "model",
parts: [
{ text: "Let me calculate that for you." },
{
functionCall: {
name: "calculator",
args: { operation: "add", numbers: [2, 3] },
},
},
],
})
})
it("should convert a message with tool result as string", () => {
const anthropicMessage: Anthropic.Messages.MessageParam = {
role: "user",
content: [
{ type: "text", text: "Here's the result:" },
{
type: "tool_result",
tool_use_id: "calculator-123",
content: "The result is 5",
},
],
}
const result = convertAnthropicMessageToGemini(anthropicMessage)
expect(result).toEqual({
role: "user",
parts: [
{ text: "Here's the result:" },
{
functionResponse: {
name: "calculator",
response: {
name: "calculator",
content: "The result is 5",
},
},
},
],
})
})
it("should handle empty tool result content", () => {
const anthropicMessage: Anthropic.Messages.MessageParam = {
role: "user",
content: [
{
type: "tool_result",
tool_use_id: "calculator-123",
content: null as any, // Empty content
},
],
}
const result = convertAnthropicMessageToGemini(anthropicMessage)
// Should skip the empty tool result
expect(result).toEqual({
role: "user",
parts: [],
})
})
it("should convert a message with tool result as array with text only", () => {
const anthropicMessage: Anthropic.Messages.MessageParam = {
role: "user",
content: [
{
type: "tool_result",
tool_use_id: "search-123",
content: [
{ type: "text", text: "First result" },
{ type: "text", text: "Second result" },
],
},
],
}
const result = convertAnthropicMessageToGemini(anthropicMessage)
expect(result).toEqual({
role: "user",
parts: [
{
functionResponse: {
name: "search",
response: {
name: "search",
content: "First result\n\nSecond result",
},
},
},
],
})
})
it("should convert a message with tool result as array with text and images", () => {
const anthropicMessage: Anthropic.Messages.MessageParam = {
role: "user",
content: [
{
type: "tool_result",
tool_use_id: "search-123",
content: [
{ type: "text", text: "Search results:" },
{
type: "image",
source: {
type: "base64",
media_type: "image/png",
data: "image1data",
},
},
{
type: "image",
source: {
type: "base64",
media_type: "image/jpeg",
data: "image2data",
},
},
],
},
],
}
const result = convertAnthropicMessageToGemini(anthropicMessage)
expect(result).toEqual({
role: "user",
parts: [
{
functionResponse: {
name: "search",
response: {
name: "search",
content: "Search results:\n\n(See next part for image)",
},
},
},
{
inlineData: {
data: "image1data",
mimeType: "image/png",
},
},
{
inlineData: {
data: "image2data",
mimeType: "image/jpeg",
},
},
],
})
})
it("should convert a message with tool result containing only images", () => {
const anthropicMessage: Anthropic.Messages.MessageParam = {
role: "user",
content: [
{
type: "tool_result",
tool_use_id: "imagesearch-123",
content: [
{
type: "image",
source: {
type: "base64",
media_type: "image/png",
data: "onlyimagedata",
},
},
],
},
],
}
const result = convertAnthropicMessageToGemini(anthropicMessage)
expect(result).toEqual({
role: "user",
parts: [
{
functionResponse: {
name: "imagesearch",
response: {
name: "imagesearch",
content: "\n\n(See next part for image)",
},
},
},
{
inlineData: {
data: "onlyimagedata",
mimeType: "image/png",
},
},
],
})
})
it("should throw an error for unsupported content block type", () => {
const anthropicMessage: Anthropic.Messages.MessageParam = {
role: "user",
content: [
{
type: "unknown_type", // Unsupported type
data: "some data",
} as any,
],
}
expect(() => convertAnthropicMessageToGemini(anthropicMessage)).toThrow(
"Unsupported content block type: unknown_type",
)
})
})

View file

@ -0,0 +1,301 @@
// npx jest src/api/transform/__tests__/mistral-format.test.ts
import { Anthropic } from "@anthropic-ai/sdk"
import { convertToMistralMessages } from "../mistral-format"
describe("convertToMistralMessages", () => {
it("should convert simple text messages for user and assistant roles", () => {
const anthropicMessages: Anthropic.Messages.MessageParam[] = [
{
role: "user",
content: "Hello",
},
{
role: "assistant",
content: "Hi there!",
},
]
const mistralMessages = convertToMistralMessages(anthropicMessages)
expect(mistralMessages).toHaveLength(2)
expect(mistralMessages[0]).toEqual({
role: "user",
content: "Hello",
})
expect(mistralMessages[1]).toEqual({
role: "assistant",
content: "Hi there!",
})
})
it("should handle user messages with image content", () => {
const anthropicMessages: Anthropic.Messages.MessageParam[] = [
{
role: "user",
content: [
{
type: "text",
text: "What is in this image?",
},
{
type: "image",
source: {
type: "base64",
media_type: "image/jpeg",
data: "base64data",
},
},
],
},
]
const mistralMessages = convertToMistralMessages(anthropicMessages)
expect(mistralMessages).toHaveLength(1)
expect(mistralMessages[0].role).toBe("user")
const content = mistralMessages[0].content as Array<{
type: string
text?: string
imageUrl?: { url: string }
}>
expect(Array.isArray(content)).toBe(true)
expect(content).toHaveLength(2)
expect(content[0]).toEqual({ type: "text", text: "What is in this image?" })
expect(content[1]).toEqual({
type: "image_url",
imageUrl: { url: "data:image/jpeg;base64,base64data" },
})
})
it("should handle user messages with only tool results", () => {
const anthropicMessages: Anthropic.Messages.MessageParam[] = [
{
role: "user",
content: [
{
type: "tool_result",
tool_use_id: "weather-123",
content: "Current temperature in London: 20°C",
},
],
},
]
// Based on the implementation, tool results without accompanying text/image
// don't generate any messages
const mistralMessages = convertToMistralMessages(anthropicMessages)
expect(mistralMessages).toHaveLength(0)
})
it("should handle user messages with mixed content (text, image, and tool results)", () => {
const anthropicMessages: Anthropic.Messages.MessageParam[] = [
{
role: "user",
content: [
{
type: "text",
text: "Here's the weather data and an image:",
},
{
type: "image",
source: {
type: "base64",
media_type: "image/png",
data: "imagedata123",
},
},
{
type: "tool_result",
tool_use_id: "weather-123",
content: "Current temperature in London: 20°C",
},
],
},
]
const mistralMessages = convertToMistralMessages(anthropicMessages)
// Based on the implementation, only the text and image content is included
// Tool results are not converted to separate messages
expect(mistralMessages).toHaveLength(1)
// Message should be the user message with text and image
expect(mistralMessages[0].role).toBe("user")
const userContent = mistralMessages[0].content as Array<{
type: string
text?: string
imageUrl?: { url: string }
}>
expect(Array.isArray(userContent)).toBe(true)
expect(userContent).toHaveLength(2)
expect(userContent[0]).toEqual({ type: "text", text: "Here's the weather data and an image:" })
expect(userContent[1]).toEqual({
type: "image_url",
imageUrl: { url: "data:image/png;base64,imagedata123" },
})
})
it("should handle assistant messages with text content", () => {
const anthropicMessages: Anthropic.Messages.MessageParam[] = [
{
role: "assistant",
content: [
{
type: "text",
text: "I'll help you with that question.",
},
],
},
]
const mistralMessages = convertToMistralMessages(anthropicMessages)
expect(mistralMessages).toHaveLength(1)
expect(mistralMessages[0].role).toBe("assistant")
expect(mistralMessages[0].content).toBe("I'll help you with that question.")
})
it("should handle assistant messages with tool use", () => {
const anthropicMessages: Anthropic.Messages.MessageParam[] = [
{
role: "assistant",
content: [
{
type: "text",
text: "Let me check the weather for you.",
},
{
type: "tool_use",
id: "weather-123",
name: "get_weather",
input: { city: "London" },
},
],
},
]
const mistralMessages = convertToMistralMessages(anthropicMessages)
expect(mistralMessages).toHaveLength(1)
expect(mistralMessages[0].role).toBe("assistant")
expect(mistralMessages[0].content).toBe("Let me check the weather for you.")
})
it("should handle multiple text blocks in assistant messages", () => {
const anthropicMessages: Anthropic.Messages.MessageParam[] = [
{
role: "assistant",
content: [
{
type: "text",
text: "First paragraph of information.",
},
{
type: "text",
text: "Second paragraph with more details.",
},
],
},
]
const mistralMessages = convertToMistralMessages(anthropicMessages)
expect(mistralMessages).toHaveLength(1)
expect(mistralMessages[0].role).toBe("assistant")
expect(mistralMessages[0].content).toBe("First paragraph of information.\nSecond paragraph with more details.")
})
it("should handle a conversation with mixed message types", () => {
const anthropicMessages: Anthropic.Messages.MessageParam[] = [
{
role: "user",
content: [
{
type: "text",
text: "What's in this image?",
},
{
type: "image",
source: {
type: "base64",
media_type: "image/jpeg",
data: "imagedata",
},
},
],
},
{
role: "assistant",
content: [
{
type: "text",
text: "This image shows a landscape with mountains.",
},
{
type: "tool_use",
id: "search-123",
name: "search_info",
input: { query: "mountain types" },
},
],
},
{
role: "user",
content: [
{
type: "tool_result",
tool_use_id: "search-123",
content: "Found information about different mountain types.",
},
],
},
{
role: "assistant",
content: "Based on the search results, I can tell you more about the mountains in the image.",
},
]
const mistralMessages = convertToMistralMessages(anthropicMessages)
// Based on the implementation, user messages with only tool results don't generate messages
expect(mistralMessages).toHaveLength(3)
// User message with image
expect(mistralMessages[0].role).toBe("user")
const userContent = mistralMessages[0].content as Array<{
type: string
text?: string
imageUrl?: { url: string }
}>
expect(Array.isArray(userContent)).toBe(true)
expect(userContent).toHaveLength(2)
// Assistant message with text (tool_use is not included in Mistral format)
expect(mistralMessages[1].role).toBe("assistant")
expect(mistralMessages[1].content).toBe("This image shows a landscape with mountains.")
// Final assistant message
expect(mistralMessages[2]).toEqual({
role: "assistant",
content: "Based on the search results, I can tell you more about the mountains in the image.",
})
})
it("should handle empty content in assistant messages", () => {
const anthropicMessages: Anthropic.Messages.MessageParam[] = [
{
role: "assistant",
content: [
{
type: "tool_use",
id: "search-123",
name: "search_info",
input: { query: "test query" },
},
],
},
]
const mistralMessages = convertToMistralMessages(anthropicMessages)
expect(mistralMessages).toHaveLength(1)
expect(mistralMessages[0].role).toBe("assistant")
expect(mistralMessages[0].content).toBeUndefined()
})
})

View file

@ -1,275 +1,131 @@
import { convertToOpenAiMessages, convertToAnthropicMessage } from "../openai-format"
// npx jest src/api/transform/__tests__/openai-format.test.ts
import { Anthropic } from "@anthropic-ai/sdk"
import OpenAI from "openai"
type PartialChatCompletion = Omit<OpenAI.Chat.Completions.ChatCompletion, "choices"> & {
choices: Array<
Partial<OpenAI.Chat.Completions.ChatCompletion.Choice> & {
message: OpenAI.Chat.Completions.ChatCompletion.Choice["message"]
finish_reason: string
index: number
}
>
}
import { convertToOpenAiMessages } from "../openai-format"
describe("OpenAI Format Transformations", () => {
describe("convertToOpenAiMessages", () => {
it("should convert simple text messages", () => {
const anthropicMessages: Anthropic.Messages.MessageParam[] = [
{
role: "user",
content: "Hello",
},
{
role: "assistant",
content: "Hi there!",
},
]
const openAiMessages = convertToOpenAiMessages(anthropicMessages)
expect(openAiMessages).toHaveLength(2)
expect(openAiMessages[0]).toEqual({
describe("convertToOpenAiMessages", () => {
it("should convert simple text messages", () => {
const anthropicMessages: Anthropic.Messages.MessageParam[] = [
{
role: "user",
content: "Hello",
})
expect(openAiMessages[1]).toEqual({
},
{
role: "assistant",
content: "Hi there!",
})
},
]
const openAiMessages = convertToOpenAiMessages(anthropicMessages)
expect(openAiMessages).toHaveLength(2)
expect(openAiMessages[0]).toEqual({
role: "user",
content: "Hello",
})
it("should handle messages with image content", () => {
const anthropicMessages: Anthropic.Messages.MessageParam[] = [
{
role: "user",
content: [
{
type: "text",
text: "What is in this image?",
},
{
type: "image",
source: {
type: "base64",
media_type: "image/jpeg",
data: "base64data",
},
},
],
},
]
const openAiMessages = convertToOpenAiMessages(anthropicMessages)
expect(openAiMessages).toHaveLength(1)
expect(openAiMessages[0].role).toBe("user")
const content = openAiMessages[0].content as Array<{
type: string
text?: string
image_url?: { url: string }
}>
expect(Array.isArray(content)).toBe(true)
expect(content).toHaveLength(2)
expect(content[0]).toEqual({ type: "text", text: "What is in this image?" })
expect(content[1]).toEqual({
type: "image_url",
image_url: { url: "data:image/jpeg;base64,base64data" },
})
})
it("should handle assistant messages with tool use", () => {
const anthropicMessages: Anthropic.Messages.MessageParam[] = [
{
role: "assistant",
content: [
{
type: "text",
text: "Let me check the weather.",
},
{
type: "tool_use",
id: "weather-123",
name: "get_weather",
input: { city: "London" },
},
],
},
]
const openAiMessages = convertToOpenAiMessages(anthropicMessages)
expect(openAiMessages).toHaveLength(1)
const assistantMessage = openAiMessages[0] as OpenAI.Chat.ChatCompletionAssistantMessageParam
expect(assistantMessage.role).toBe("assistant")
expect(assistantMessage.content).toBe("Let me check the weather.")
expect(assistantMessage.tool_calls).toHaveLength(1)
expect(assistantMessage.tool_calls![0]).toEqual({
id: "weather-123",
type: "function",
function: {
name: "get_weather",
arguments: JSON.stringify({ city: "London" }),
},
})
})
it("should handle user messages with tool results", () => {
const anthropicMessages: Anthropic.Messages.MessageParam[] = [
{
role: "user",
content: [
{
type: "tool_result",
tool_use_id: "weather-123",
content: "Current temperature in London: 20°C",
},
],
},
]
const openAiMessages = convertToOpenAiMessages(anthropicMessages)
expect(openAiMessages).toHaveLength(1)
const toolMessage = openAiMessages[0] as OpenAI.Chat.ChatCompletionToolMessageParam
expect(toolMessage.role).toBe("tool")
expect(toolMessage.tool_call_id).toBe("weather-123")
expect(toolMessage.content).toBe("Current temperature in London: 20°C")
expect(openAiMessages[1]).toEqual({
role: "assistant",
content: "Hi there!",
})
})
describe("convertToAnthropicMessage", () => {
it("should convert simple completion", () => {
const openAiCompletion: PartialChatCompletion = {
id: "completion-123",
model: "gpt-4",
choices: [
it("should handle messages with image content", () => {
const anthropicMessages: Anthropic.Messages.MessageParam[] = [
{
role: "user",
content: [
{
message: {
role: "assistant",
content: "Hello there!",
refusal: null,
type: "text",
text: "What is in this image?",
},
{
type: "image",
source: {
type: "base64",
media_type: "image/jpeg",
data: "base64data",
},
finish_reason: "stop",
index: 0,
},
],
usage: {
prompt_tokens: 10,
completion_tokens: 5,
total_tokens: 15,
},
created: 123456789,
object: "chat.completion",
}
},
]
const anthropicMessage = convertToAnthropicMessage(
openAiCompletion as OpenAI.Chat.Completions.ChatCompletion,
)
expect(anthropicMessage.id).toBe("completion-123")
expect(anthropicMessage.role).toBe("assistant")
expect(anthropicMessage.content).toHaveLength(1)
expect(anthropicMessage.content[0]).toEqual({
type: "text",
text: "Hello there!",
})
expect(anthropicMessage.stop_reason).toBe("end_turn")
expect(anthropicMessage.usage).toEqual({
input_tokens: 10,
output_tokens: 5,
})
const openAiMessages = convertToOpenAiMessages(anthropicMessages)
expect(openAiMessages).toHaveLength(1)
expect(openAiMessages[0].role).toBe("user")
const content = openAiMessages[0].content as Array<{
type: string
text?: string
image_url?: { url: string }
}>
expect(Array.isArray(content)).toBe(true)
expect(content).toHaveLength(2)
expect(content[0]).toEqual({ type: "text", text: "What is in this image?" })
expect(content[1]).toEqual({
type: "image_url",
image_url: { url: "data:image/jpeg;base64,base64data" },
})
})
it("should handle tool calls in completion", () => {
const openAiCompletion: PartialChatCompletion = {
id: "completion-123",
model: "gpt-4",
choices: [
it("should handle assistant messages with tool use", () => {
const anthropicMessages: Anthropic.Messages.MessageParam[] = [
{
role: "assistant",
content: [
{
message: {
role: "assistant",
content: "Let me check the weather.",
tool_calls: [
{
id: "weather-123",
type: "function",
function: {
name: "get_weather",
arguments: '{"city":"London"}',
},
},
],
refusal: null,
},
finish_reason: "tool_calls",
index: 0,
type: "text",
text: "Let me check the weather.",
},
{
type: "tool_use",
id: "weather-123",
name: "get_weather",
input: { city: "London" },
},
],
usage: {
prompt_tokens: 15,
completion_tokens: 8,
total_tokens: 23,
},
created: 123456789,
object: "chat.completion",
}
},
]
const anthropicMessage = convertToAnthropicMessage(
openAiCompletion as OpenAI.Chat.Completions.ChatCompletion,
)
expect(anthropicMessage.content).toHaveLength(2)
expect(anthropicMessage.content[0]).toEqual({
type: "text",
text: "Let me check the weather.",
})
expect(anthropicMessage.content[1]).toEqual({
type: "tool_use",
id: "weather-123",
const openAiMessages = convertToOpenAiMessages(anthropicMessages)
expect(openAiMessages).toHaveLength(1)
const assistantMessage = openAiMessages[0] as OpenAI.Chat.ChatCompletionAssistantMessageParam
expect(assistantMessage.role).toBe("assistant")
expect(assistantMessage.content).toBe("Let me check the weather.")
expect(assistantMessage.tool_calls).toHaveLength(1)
expect(assistantMessage.tool_calls![0]).toEqual({
id: "weather-123",
type: "function",
function: {
name: "get_weather",
input: { city: "London" },
})
expect(anthropicMessage.stop_reason).toBe("tool_use")
arguments: JSON.stringify({ city: "London" }),
},
})
})
it("should handle invalid tool call arguments", () => {
const openAiCompletion: PartialChatCompletion = {
id: "completion-123",
model: "gpt-4",
choices: [
it("should handle user messages with tool results", () => {
const anthropicMessages: Anthropic.Messages.MessageParam[] = [
{
role: "user",
content: [
{
message: {
role: "assistant",
content: "Testing invalid arguments",
tool_calls: [
{
id: "test-123",
type: "function",
function: {
name: "test_function",
arguments: "invalid json",
},
},
],
refusal: null,
},
finish_reason: "tool_calls",
index: 0,
type: "tool_result",
tool_use_id: "weather-123",
content: "Current temperature in London: 20°C",
},
],
created: 123456789,
object: "chat.completion",
}
},
]
const anthropicMessage = convertToAnthropicMessage(
openAiCompletion as OpenAI.Chat.Completions.ChatCompletion,
)
expect(anthropicMessage.content).toHaveLength(2)
expect(anthropicMessage.content[1]).toEqual({
type: "tool_use",
id: "test-123",
name: "test_function",
input: {}, // Should default to empty object for invalid JSON
})
})
const openAiMessages = convertToOpenAiMessages(anthropicMessages)
expect(openAiMessages).toHaveLength(1)
const toolMessage = openAiMessages[0] as OpenAI.Chat.ChatCompletionToolMessageParam
expect(toolMessage.role).toBe("tool")
expect(toolMessage.tool_call_id).toBe("weather-123")
expect(toolMessage.content).toBe("Current temperature in London: 20°C")
})
})

View file

@ -1,6 +1,8 @@
// npx jest src/api/transform/__tests__/vscode-lm-format.test.ts
import { Anthropic } from "@anthropic-ai/sdk"
import * as vscode from "vscode"
import { convertToVsCodeLmMessages, convertToAnthropicRole, convertToAnthropicMessage } from "../vscode-lm-format"
import { convertToVsCodeLmMessages, convertToAnthropicRole } from "../vscode-lm-format"
// Mock crypto
const mockCrypto = {
@ -27,14 +29,6 @@ interface MockLanguageModelToolResultPart {
parts: MockLanguageModelTextPart[]
}
type MockMessageContent = MockLanguageModelTextPart | MockLanguageModelToolCallPart | MockLanguageModelToolResultPart
interface MockLanguageModelChatMessage {
role: string
name?: string
content: MockMessageContent[]
}
// Mock vscode namespace
jest.mock("vscode", () => {
const LanguageModelChatMessageRole = {
@ -84,173 +78,115 @@ jest.mock("vscode", () => {
}
})
describe("vscode-lm-format", () => {
describe("convertToVsCodeLmMessages", () => {
it("should convert simple string messages", () => {
const messages: Anthropic.Messages.MessageParam[] = [
{ role: "user", content: "Hello" },
{ role: "assistant", content: "Hi there" },
]
describe("convertToVsCodeLmMessages", () => {
it("should convert simple string messages", () => {
const messages: Anthropic.Messages.MessageParam[] = [
{ role: "user", content: "Hello" },
{ role: "assistant", content: "Hi there" },
]
const result = convertToVsCodeLmMessages(messages)
const result = convertToVsCodeLmMessages(messages)
expect(result).toHaveLength(2)
expect(result[0].role).toBe("user")
expect((result[0].content[0] as MockLanguageModelTextPart).value).toBe("Hello")
expect(result[1].role).toBe("assistant")
expect((result[1].content[0] as MockLanguageModelTextPart).value).toBe("Hi there")
})
it("should handle complex user messages with tool results", () => {
const messages: Anthropic.Messages.MessageParam[] = [
{
role: "user",
content: [
{ type: "text", text: "Here is the result:" },
{
type: "tool_result",
tool_use_id: "tool-1",
content: "Tool output",
},
],
},
]
const result = convertToVsCodeLmMessages(messages)
expect(result).toHaveLength(1)
expect(result[0].role).toBe("user")
expect(result[0].content).toHaveLength(2)
const [toolResult, textContent] = result[0].content as [
MockLanguageModelToolResultPart,
MockLanguageModelTextPart,
]
expect(toolResult.type).toBe("tool_result")
expect(textContent.type).toBe("text")
})
it("should handle complex assistant messages with tool calls", () => {
const messages: Anthropic.Messages.MessageParam[] = [
{
role: "assistant",
content: [
{ type: "text", text: "Let me help you with that." },
{
type: "tool_use",
id: "tool-1",
name: "calculator",
input: { operation: "add", numbers: [2, 2] },
},
],
},
]
const result = convertToVsCodeLmMessages(messages)
expect(result).toHaveLength(1)
expect(result[0].role).toBe("assistant")
expect(result[0].content).toHaveLength(2)
const [toolCall, textContent] = result[0].content as [
MockLanguageModelToolCallPart,
MockLanguageModelTextPart,
]
expect(toolCall.type).toBe("tool_call")
expect(textContent.type).toBe("text")
})
it("should handle image blocks with appropriate placeholders", () => {
const messages: Anthropic.Messages.MessageParam[] = [
{
role: "user",
content: [
{ type: "text", text: "Look at this:" },
{
type: "image",
source: {
type: "base64",
media_type: "image/png",
data: "base64data",
},
},
],
},
]
const result = convertToVsCodeLmMessages(messages)
expect(result).toHaveLength(1)
const imagePlaceholder = result[0].content[1] as MockLanguageModelTextPart
expect(imagePlaceholder.value).toContain("[Image (base64): image/png not supported by VSCode LM API]")
})
expect(result).toHaveLength(2)
expect(result[0].role).toBe("user")
expect((result[0].content[0] as MockLanguageModelTextPart).value).toBe("Hello")
expect(result[1].role).toBe("assistant")
expect((result[1].content[0] as MockLanguageModelTextPart).value).toBe("Hi there")
})
describe("convertToAnthropicRole", () => {
it("should convert assistant role correctly", () => {
const result = convertToAnthropicRole("assistant" as any)
expect(result).toBe("assistant")
})
it("should convert user role correctly", () => {
const result = convertToAnthropicRole("user" as any)
expect(result).toBe("user")
})
it("should return null for unknown roles", () => {
const result = convertToAnthropicRole("unknown" as any)
expect(result).toBeNull()
})
})
describe("convertToAnthropicMessage", () => {
it("should convert assistant message with text content", async () => {
const vsCodeMessage = {
role: "assistant",
name: "assistant",
content: [new vscode.LanguageModelTextPart("Hello")],
}
const result = await convertToAnthropicMessage(vsCodeMessage as any)
expect(result.role).toBe("assistant")
expect(result.content).toHaveLength(1)
expect(result.content[0]).toEqual({
type: "text",
text: "Hello",
})
expect(result.id).toBe("test-uuid")
})
it("should convert assistant message with tool calls", async () => {
const vsCodeMessage = {
role: "assistant",
name: "assistant",
content: [
new vscode.LanguageModelToolCallPart("call-1", "calculator", { operation: "add", numbers: [2, 2] }),
],
}
const result = await convertToAnthropicMessage(vsCodeMessage as any)
expect(result.content).toHaveLength(1)
expect(result.content[0]).toEqual({
type: "tool_use",
id: "call-1",
name: "calculator",
input: { operation: "add", numbers: [2, 2] },
})
expect(result.id).toBe("test-uuid")
})
it("should throw error for non-assistant messages", async () => {
const vsCodeMessage = {
it("should handle complex user messages with tool results", () => {
const messages: Anthropic.Messages.MessageParam[] = [
{
role: "user",
name: "user",
content: [new vscode.LanguageModelTextPart("Hello")],
}
content: [
{ type: "text", text: "Here is the result:" },
{
type: "tool_result",
tool_use_id: "tool-1",
content: "Tool output",
},
],
},
]
await expect(convertToAnthropicMessage(vsCodeMessage as any)).rejects.toThrow(
"Roo Code <Language Model API>: Only assistant messages are supported.",
)
})
const result = convertToVsCodeLmMessages(messages)
expect(result).toHaveLength(1)
expect(result[0].role).toBe("user")
expect(result[0].content).toHaveLength(2)
const [toolResult, textContent] = result[0].content as [
MockLanguageModelToolResultPart,
MockLanguageModelTextPart,
]
expect(toolResult.type).toBe("tool_result")
expect(textContent.type).toBe("text")
})
it("should handle complex assistant messages with tool calls", () => {
const messages: Anthropic.Messages.MessageParam[] = [
{
role: "assistant",
content: [
{ type: "text", text: "Let me help you with that." },
{
type: "tool_use",
id: "tool-1",
name: "calculator",
input: { operation: "add", numbers: [2, 2] },
},
],
},
]
const result = convertToVsCodeLmMessages(messages)
expect(result).toHaveLength(1)
expect(result[0].role).toBe("assistant")
expect(result[0].content).toHaveLength(2)
const [toolCall, textContent] = result[0].content as [MockLanguageModelToolCallPart, MockLanguageModelTextPart]
expect(toolCall.type).toBe("tool_call")
expect(textContent.type).toBe("text")
})
it("should handle image blocks with appropriate placeholders", () => {
const messages: Anthropic.Messages.MessageParam[] = [
{
role: "user",
content: [
{ type: "text", text: "Look at this:" },
{
type: "image",
source: {
type: "base64",
media_type: "image/png",
data: "base64data",
},
},
],
},
]
const result = convertToVsCodeLmMessages(messages)
expect(result).toHaveLength(1)
const imagePlaceholder = result[0].content[1] as MockLanguageModelTextPart
expect(imagePlaceholder.value).toContain("[Image (base64): image/png not supported by VSCode LM API]")
})
})
describe("convertToAnthropicRole", () => {
it("should convert assistant role correctly", () => {
const result = convertToAnthropicRole("assistant" as any)
expect(result).toBe("assistant")
})
it("should convert user role correctly", () => {
const result = convertToAnthropicRole("user" as any)
expect(result).toBe("user")
})
it("should return null for unknown roles", () => {
const result = convertToAnthropicRole("unknown" as any)
expect(result).toBeNull()
})
})

View file

@ -1,9 +1,7 @@
import { Anthropic } from "@anthropic-ai/sdk"
import { MessageContent } from "../../shared/api"
import { ConversationRole, Message, ContentBlock } from "@aws-sdk/client-bedrock-runtime"
// Import StreamEvent type from bedrock.ts
import { StreamEvent } from "../providers/bedrock"
import { MessageContent } from "../../shared/api"
/**
* Convert Anthropic messages to Bedrock Converse format
@ -175,49 +173,3 @@ export function convertToBedrockConverseMessages(anthropicMessages: Anthropic.Me
}
})
}
/**
* Convert Bedrock Converse stream events to Anthropic message format
*/
export function convertToAnthropicMessage(
streamEvent: StreamEvent,
modelId: string,
): Partial<Anthropic.Messages.Message> {
// Handle metadata events
if (streamEvent.metadata?.usage) {
return {
id: "", // Bedrock doesn't provide message IDs
type: "message",
role: "assistant",
model: modelId,
usage: {
input_tokens: streamEvent.metadata.usage.inputTokens || 0,
output_tokens: streamEvent.metadata.usage.outputTokens || 0,
},
}
}
// Handle content blocks
const text = streamEvent.contentBlockStart?.start?.text || streamEvent.contentBlockDelta?.delta?.text
if (text !== undefined) {
return {
type: "message",
role: "assistant",
content: [{ type: "text", text: text }],
model: modelId,
}
}
// Handle message stop
if (streamEvent.messageStop) {
return {
type: "message",
role: "assistant",
stop_reason: streamEvent.messageStop.stopReason || null,
stop_sequence: null,
model: modelId,
}
}
return {}
}

View file

@ -1,29 +1,11 @@
import { Anthropic } from "@anthropic-ai/sdk"
import {
Content,
EnhancedGenerateContentResponse,
FunctionCallPart,
FunctionDeclaration,
FunctionResponsePart,
InlineDataPart,
Part,
SchemaType,
TextPart,
} from "@google/generative-ai"
import { Content, FunctionCallPart, FunctionResponsePart, InlineDataPart, Part, TextPart } from "@google/generative-ai"
export function convertAnthropicContentToGemini(
content:
| string
| Array<
| Anthropic.Messages.TextBlockParam
| Anthropic.Messages.ImageBlockParam
| Anthropic.Messages.ToolUseBlockParam
| Anthropic.Messages.ToolResultBlockParam
>,
): Part[] {
function convertAnthropicContentToGemini(content: Anthropic.Messages.MessageParam["content"]): Part[] {
if (typeof content === "string") {
return [{ text: content } as TextPart]
}
return content.flatMap((block) => {
switch (block.type) {
case "text":
@ -99,97 +81,3 @@ export function convertAnthropicMessageToGemini(message: Anthropic.Messages.Mess
parts: convertAnthropicContentToGemini(message.content),
}
}
export function convertAnthropicToolToGemini(tool: Anthropic.Messages.Tool): FunctionDeclaration {
return {
name: tool.name,
description: tool.description || "",
parameters: {
type: SchemaType.OBJECT,
properties: Object.fromEntries(
Object.entries(tool.input_schema.properties || {}).map(([key, value]) => [
key,
{
type: (value as any).type.toUpperCase(),
description: (value as any).description || "",
},
]),
),
required: (tool.input_schema.required as string[]) || [],
},
}
}
/*
It looks like gemini likes to double escape certain characters when writing file contents: https://discuss.ai.google.dev/t/function-call-string-property-is-double-escaped/37867
*/
export function unescapeGeminiContent(content: string) {
return content
.replace(/\\n/g, "\n")
.replace(/\\'/g, "'")
.replace(/\\"/g, '"')
.replace(/\\r/g, "\r")
.replace(/\\t/g, "\t")
}
export function convertGeminiResponseToAnthropic(
response: EnhancedGenerateContentResponse,
): Anthropic.Messages.Message {
const content: Anthropic.Messages.ContentBlock[] = []
// Add the main text response
const text = response.text()
if (text) {
content.push({ type: "text", text })
}
// Add function calls as tool_use blocks
const functionCalls = response.functionCalls()
if (functionCalls) {
functionCalls.forEach((call, index) => {
if ("content" in call.args && typeof call.args.content === "string") {
call.args.content = unescapeGeminiContent(call.args.content)
}
content.push({
type: "tool_use",
id: `${call.name}-${index}-${Date.now()}`,
name: call.name,
input: call.args,
})
})
}
// Determine stop reason
let stop_reason: Anthropic.Messages.Message["stop_reason"] = null
const finishReason = response.candidates?.[0]?.finishReason
if (finishReason) {
switch (finishReason) {
case "STOP":
stop_reason = "end_turn"
break
case "MAX_TOKENS":
stop_reason = "max_tokens"
break
case "SAFETY":
case "RECITATION":
case "OTHER":
stop_reason = "stop_sequence"
break
// Add more cases if needed
}
}
return {
id: `msg_${Date.now()}`, // Generate a unique ID
type: "message",
role: "assistant",
content,
model: "",
stop_reason,
stop_sequence: null, // Gemini doesn't provide this information
usage: {
input_tokens: response.usageMetadata?.promptTokenCount ?? 0,
output_tokens: response.usageMetadata?.candidatesTokenCount ?? 0,
},
}
}

View file

@ -1,5 +1,4 @@
import { Anthropic } from "@anthropic-ai/sdk"
import { Mistral } from "@mistralai/mistralai"
import { AssistantMessage } from "@mistralai/mistralai/models/components/assistantmessage"
import { SystemMessage } from "@mistralai/mistralai/models/components/systemmessage"
import { ToolMessage } from "@mistralai/mistralai/models/components/toolmessage"
@ -13,6 +12,7 @@ export type MistralMessage =
export function convertToMistralMessages(anthropicMessages: Anthropic.Messages.MessageParam[]): MistralMessage[] {
const mistralMessages: MistralMessage[] = []
for (const anthropicMessage of anthropicMessages) {
if (typeof anthropicMessage.content === "string") {
mistralMessages.push({

View file

@ -1,429 +0,0 @@
import { Anthropic } from "@anthropic-ai/sdk"
import OpenAI from "openai"
const o1SystemPrompt = (systemPrompt: string) => `
# System Prompt
${systemPrompt}
# Instructions for Formulating Your Response
You must respond to the user's request by using at least one tool call. When formulating your response, follow these guidelines:
1. Begin your response with normal text, explaining your thoughts, analysis, or plan of action.
2. If you need to use any tools, place ALL tool calls at the END of your message, after your normal text explanation.
3. You can use multiple tool calls if needed, but they should all be grouped together at the end of your message.
4. After placing the tool calls, do not add any additional normal text. The tool calls should be the final content in your message.
Here's the general structure your responses should follow:
\`\`\`
[Your normal text response explaining your thoughts and actions]
[Tool Call 1]
[Tool Call 2 if needed]
[Tool Call 3 if needed]
...
\`\`\`
Remember:
- Choose the most appropriate tool(s) based on the task and the tool descriptions provided.
- Formulate your tool calls using the XML format specified for each tool.
- Provide clear explanations in your normal text about what actions you're taking and why you're using particular tools.
- Act as if the tool calls will be executed immediately after your message, and your next response will have access to their results.
# Tool Descriptions and XML Formats
1. execute_command:
<execute_command>
<command>Your command here</command>
</execute_command>
Description: Execute a CLI command on the system. Use this when you need to perform system operations or run specific commands to accomplish any step in the user's task. You must tailor your command to the user's system and provide a clear explanation of what the command does. Prefer to execute complex CLI commands over creating executable scripts, as they are more flexible and easier to run. Commands will be executed in the current working directory.
2. list_files:
<list_files>
<path>Directory path here</path>
<recursive>true or false (optional)</recursive>
</list_files>
Description: List files and directories within the specified directory. If recursive is true, it will list all files and directories recursively. If recursive is false or not provided, it will only list the top-level contents.
3. list_code_definition_names:
<list_code_definition_names>
<path>Directory path here</path>
</list_code_definition_names>
Description: Lists definition names (classes, functions, methods, etc.) used in source code files at the top level of the specified directory. This tool provides insights into the codebase structure and important constructs, encapsulating high-level concepts and relationships that are crucial for understanding the overall architecture.
4. search_files:
<search_files>
<path>Directory path here</path>
<regex>Your regex pattern here</regex>
<filePattern>Optional file pattern here</filePattern>
</search_files>
Description: Perform a regex search across files in a specified directory, providing context-rich results. This tool searches for patterns or specific content across multiple files, displaying each match with encapsulating context.
5. read_file:
<read_file>
<path>File path here</path>
</read_file>
Description: Read the contents of a file at the specified path. Use this when you need to examine the contents of an existing file, for example to analyze code, review text files, or extract information from configuration files. Automatically extracts raw text from PDF and DOCX files. May not be suitable for other types of binary files, as it returns the raw content as a string.
6. write_to_file:
<write_to_file>
<path>File path here</path>
<content>
Your file content here
</content>
</write_to_file>
Description: Write content to a file at the specified path. If the file exists, it will be overwritten with the provided content. If the file doesn't exist, it will be created. Always provide the full intended content of the file, without any truncation. This tool will automatically create any directories needed to write the file.
7. ask_followup_question:
<ask_followup_question>
<question>Your question here</question>
</ask_followup_question>
Description: Ask the user a question to gather additional information needed to complete the task. This tool should be used when you encounter ambiguities, need clarification, or require more details to proceed effectively. It allows for interactive problem-solving by enabling direct communication with the user. Use this tool judiciously to maintain a balance between gathering necessary information and avoiding excessive back-and-forth.
8. attempt_completion:
<attempt_completion>
<command>Optional command to demonstrate result</command>
<result>
Your final result description here
</result>
</attempt_completion>
Description: Once you've completed the task, use this tool to present the result to the user. They may respond with feedback if they are not satisfied with the result, which you can use to make improvements and try again.
# Examples
Here are some examples of how to structure your responses with tool calls:
Example 1: Using a single tool
Let's run the test suite for our project. This will help us ensure that all our components are functioning correctly.
<execute_command>
<command>npm test</command>
</execute_command>
Example 2: Using multiple tools
Let's create two new configuration files for the web application: one for the frontend and one for the backend.
<write_to_file>
<path>./frontend-config.json</path>
<content>
{
"apiEndpoint": "https://api.example.com",
"theme": {
"primaryColor": "#007bff",
"secondaryColor": "#6c757d",
"fontFamily": "Arial, sans-serif"
},
"features": {
"darkMode": true,
"notifications": true,
"analytics": false
},
"version": "1.0.0"
}
</content>
</write_to_file>
<write_to_file>
<path>./backend-config.yaml</path>
<content>
database:
host: localhost
port: 5432
name: myapp_db
user: admin
server:
port: 3000
environment: development
logLevel: debug
security:
jwtSecret: your-secret-key-here
passwordSaltRounds: 10
caching:
enabled: true
provider: redis
ttl: 3600
externalServices:
emailProvider: sendgrid
storageProvider: aws-s3
</content>
</write_to_file>
Example 3: Asking a follow-up question
I've analyzed the project structure, but I need more information to proceed. Let me ask the user for clarification.
<ask_followup_question>
<question>Which specific feature would you like me to implement in the example.py file?</question>
</ask_followup_question>
`
export function convertToO1Messages(
openAiMessages: OpenAI.Chat.ChatCompletionMessageParam[],
systemPrompt: string,
): OpenAI.Chat.ChatCompletionMessageParam[] {
const toolsReplaced = openAiMessages.reduce((acc, message) => {
if (message.role === "tool") {
// Convert tool messages to user messages
acc.push({
role: "user",
content: message.content || "",
})
} else if (message.role === "assistant" && message.tool_calls) {
// Convert tool calls to content and remove tool_calls
let content = message.content || ""
message.tool_calls.forEach((toolCall) => {
if (toolCall.type === "function") {
content += `\nTool Call: ${toolCall.function.name}\nArguments: ${toolCall.function.arguments}`
}
})
acc.push({
role: "assistant",
content: content,
tool_calls: undefined,
})
} else {
// Keep other messages as they are
acc.push(message)
}
return acc
}, [] as OpenAI.Chat.ChatCompletionMessageParam[])
// Find the index of the last assistant message
// const lastAssistantIndex = findLastIndex(toolsReplaced, (message) => message.role === "assistant")
// Create a new array to hold the modified messages
const messagesWithSystemPrompt = [
{
role: "user",
content: o1SystemPrompt(systemPrompt),
} as OpenAI.Chat.ChatCompletionUserMessageParam,
...toolsReplaced,
]
// If there's an assistant message, insert the system prompt after it
// if (lastAssistantIndex !== -1) {
// const insertIndex = lastAssistantIndex + 1
// if (insertIndex < messagesWithSystemPrompt.length && messagesWithSystemPrompt[insertIndex].role === "user") {
// messagesWithSystemPrompt.splice(insertIndex, 0, {
// role: "user",
// content: o1SystemPrompt(systemPrompt),
// })
// }
// } else {
// // If there were no assistant messages, prepend the system prompt
// messagesWithSystemPrompt.unshift({
// role: "user",
// content: o1SystemPrompt(systemPrompt),
// })
// }
return messagesWithSystemPrompt
}
interface ToolCall {
tool: string
tool_input: Record<string, string>
}
const toolNames = [
"execute_command",
"list_files",
"list_code_definition_names",
"search_files",
"read_file",
"write_to_file",
"ask_followup_question",
"attempt_completion",
]
function parseAIResponse(response: string): { normalText: string; toolCalls: ToolCall[] } {
// Create a regex pattern to match any tool call opening tag
const toolCallPattern = new RegExp(`<(${toolNames.join("|")})`, "i")
const match = response.match(toolCallPattern)
if (!match) {
// No tool calls found
return { normalText: response.trim(), toolCalls: [] }
}
const toolCallStart = match.index!
const normalText = response.slice(0, toolCallStart).trim()
const toolCallsText = response.slice(toolCallStart)
const toolCalls = parseToolCalls(toolCallsText)
return { normalText, toolCalls }
}
function parseToolCalls(toolCallsText: string): ToolCall[] {
const toolCalls: ToolCall[] = []
let remainingText = toolCallsText
while (remainingText.length > 0) {
const toolMatch = toolNames.find((tool) => new RegExp(`<${tool}`, "i").test(remainingText))
if (!toolMatch) {
break // No more tool calls found
}
const startTag = `<${toolMatch}`
const endTag = `</${toolMatch}>`
const startIndex = remainingText.indexOf(startTag)
const endIndex = remainingText.indexOf(endTag, startIndex)
if (endIndex === -1) {
break // Malformed XML, no closing tag found
}
const toolCallContent = remainingText.slice(startIndex, endIndex + endTag.length)
remainingText = remainingText.slice(endIndex + endTag.length).trim()
const toolCall = parseToolCall(toolMatch, toolCallContent)
if (toolCall) {
toolCalls.push(toolCall)
}
}
return toolCalls
}
function parseToolCall(toolName: string, content: string): ToolCall | null {
const tool_input: Record<string, string> = {}
// Remove the outer tool tags
const innerContent = content.replace(new RegExp(`^<${toolName}>|</${toolName}>$`, "g"), "").trim()
// Parse nested XML elements
const paramRegex = /<(\w+)>([\s\S]*?)<\/\1>/gs
let match
while ((match = paramRegex.exec(innerContent)) !== null) {
const [, paramName, paramValue] = match
// Preserve newlines and trim only leading/trailing whitespace
tool_input[paramName] = paramValue.replace(/^\s+|\s+$/g, "")
}
// Validate required parameters
if (!validateToolInput(toolName, tool_input)) {
console.error(`Invalid tool call for ${toolName}:`, content)
return null
}
return { tool: toolName, tool_input }
}
function validateToolInput(toolName: string, tool_input: Record<string, string>): boolean {
switch (toolName) {
case "execute_command":
return "command" in tool_input
case "read_file":
case "list_code_definition_names":
case "list_files":
return "path" in tool_input
case "search_files":
return "path" in tool_input && "regex" in tool_input
case "write_to_file":
return "path" in tool_input && "content" in tool_input
case "ask_followup_question":
return "question" in tool_input
case "attempt_completion":
return "result" in tool_input
default:
return false
}
}
// Example usage:
// const aiResponse = `Here's my analysis of the situation...
// <execute_command>
// <command>ls -la</command>
// </execute_command>
// <write_to_file>
// <path>./example.txt</path>
// <content>Hello, World!</content>
// </write_to_file>`;
//
// const { normalText, toolCalls } = parseAIResponse(aiResponse);
// console.log(normalText);
// console.log(toolCalls);
// Convert OpenAI response to Anthropic format
export function convertO1ResponseToAnthropicMessage(
completion: OpenAI.Chat.Completions.ChatCompletion,
): Anthropic.Messages.Message {
const openAiMessage = completion.choices[0].message
const { normalText, toolCalls } = parseAIResponse(openAiMessage.content || "")
const anthropicMessage: Anthropic.Messages.Message = {
id: completion.id,
type: "message",
role: openAiMessage.role, // always "assistant"
content: [
{
type: "text",
text: normalText,
},
],
model: completion.model,
stop_reason: (() => {
switch (completion.choices[0].finish_reason) {
case "stop":
return "end_turn"
case "length":
return "max_tokens"
case "tool_calls":
return "tool_use"
case "content_filter": // Anthropic doesn't have an exact equivalent
default:
return null
}
})(),
stop_sequence: null, // which custom stop_sequence was generated, if any (not applicable if you don't use stop_sequence)
usage: {
input_tokens: completion.usage?.prompt_tokens || 0,
output_tokens: completion.usage?.completion_tokens || 0,
},
}
if (toolCalls.length > 0) {
anthropicMessage.content.push(
...toolCalls.map((toolCall: ToolCall, index: number): Anthropic.ToolUseBlock => {
return {
type: "tool_use",
id: `call_${index}_${Date.now()}`, // Generate a unique ID for each tool call
name: toolCall.tool,
input: toolCall.tool_input,
}
}),
)
}
return anthropicMessage
}
// Example usage:
// const openAICompletion = {
// id: "cmpl-123",
// choices: [{
// message: {
// role: "assistant",
// content: "Here's my analysis...\n\n<execute_command>\n <command>ls -la</command>\n</execute_command>"
// },
// finish_reason: "stop"
// }],
// model: "gpt-3.5-turbo",
// usage: { prompt_tokens: 50, completion_tokens: 100 }
// };
// const anthropicMessage = convertO1ResponseToAnthropicMessage(openAICompletion);
// console.log(anthropicMessage);

View file

@ -144,60 +144,3 @@ export function convertToOpenAiMessages(
return openAiMessages
}
// Convert OpenAI response to Anthropic format
export function convertToAnthropicMessage(
completion: OpenAI.Chat.Completions.ChatCompletion,
): Anthropic.Messages.Message {
const openAiMessage = completion.choices[0].message
const anthropicMessage: Anthropic.Messages.Message = {
id: completion.id,
type: "message",
role: openAiMessage.role, // always "assistant"
content: [
{
type: "text",
text: openAiMessage.content || "",
},
],
model: completion.model,
stop_reason: (() => {
switch (completion.choices[0].finish_reason) {
case "stop":
return "end_turn"
case "length":
return "max_tokens"
case "tool_calls":
return "tool_use"
case "content_filter": // Anthropic doesn't have an exact equivalent
default:
return null
}
})(),
stop_sequence: null, // which custom stop_sequence was generated, if any (not applicable if you don't use stop_sequence)
usage: {
input_tokens: completion.usage?.prompt_tokens || 0,
output_tokens: completion.usage?.completion_tokens || 0,
},
}
if (openAiMessage.tool_calls && openAiMessage.tool_calls.length > 0) {
anthropicMessage.content.push(
...openAiMessage.tool_calls.map((toolCall): Anthropic.ToolUseBlock => {
let parsedInput = {}
try {
parsedInput = JSON.parse(toolCall.function.arguments || "{}")
} catch (error) {
console.error("Failed to parse tool arguments:", error)
}
return {
type: "tool_use",
id: toolCall.id,
name: toolCall.function.name,
input: parsedInput,
}
}),
)
}
return anthropicMessage
}

View file

@ -3,16 +3,7 @@ import { Anthropic } from "@anthropic-ai/sdk"
/**
* Convert complex content blocks to simple string content
*/
export function convertToSimpleContent(
content:
| string
| Array<
| Anthropic.Messages.TextBlockParam
| Anthropic.Messages.ImageBlockParam
| Anthropic.Messages.ToolUseBlockParam
| Anthropic.Messages.ToolResultBlockParam
>,
): string {
export function convertToSimpleContent(content: Anthropic.Messages.MessageParam["content"]): string {
if (typeof content === "string") {
return content
}

View file

@ -155,46 +155,3 @@ export function convertToAnthropicRole(vsCodeLmMessageRole: vscode.LanguageModel
return null
}
}
export async function convertToAnthropicMessage(
vsCodeLmMessage: vscode.LanguageModelChatMessage,
): Promise<Anthropic.Messages.Message> {
const anthropicRole: string | null = convertToAnthropicRole(vsCodeLmMessage.role)
if (anthropicRole !== "assistant") {
throw new Error("Roo Code <Language Model API>: Only assistant messages are supported.")
}
return {
id: crypto.randomUUID(),
type: "message",
model: "vscode-lm",
role: anthropicRole,
content: vsCodeLmMessage.content
.map((part): Anthropic.ContentBlock | null => {
if (part instanceof vscode.LanguageModelTextPart) {
return {
type: "text",
text: part.value,
}
}
if (part instanceof vscode.LanguageModelToolCallPart) {
return {
type: "tool_use",
id: part.callId || crypto.randomUUID(),
name: part.name,
input: asObjectSafe(part.input),
}
}
return null
})
.filter((part): part is Anthropic.ContentBlock => part !== null),
stop_reason: null,
stop_sequence: null,
usage: {
input_tokens: 0,
output_tokens: 0,
},
}
}

View file

@ -47,6 +47,8 @@ import {
import { getApiMetrics } from "../shared/getApiMetrics"
import { HistoryItem } from "../shared/HistoryItem"
import { ClineAskResponse } from "../shared/WebviewMessage"
import { GlobalFileNames } from "../shared/globalFileNames"
import { defaultModeSlug, getModeBySlug, getFullModeDetails } from "../shared/modes"
import { calculateApiCost } from "../utils/cost"
import { fileExistsAtPath } from "../utils/fs"
import { arePathsEqual, getReadablePath } from "../utils/path"
@ -54,24 +56,34 @@ import { parseMentions } from "./mentions"
import { AssistantMessageContent, parseAssistantMessage, ToolParamName, ToolUseName } from "./assistant-message"
import { formatResponse } from "./prompts/responses"
import { SYSTEM_PROMPT } from "./prompts/system"
import { modes, defaultModeSlug, getModeBySlug } from "../shared/modes"
import { truncateConversationIfNeeded } from "./sliding-window"
import { ClineProvider, GlobalFileNames } from "./webview/ClineProvider"
import { ClineProvider } from "./webview/ClineProvider"
import { detectCodeOmission } from "../integrations/editor/detect-omission"
import { BrowserSession } from "../services/browser/BrowserSession"
import { OpenRouterHandler } from "../api/providers/openrouter"
import { McpHub } from "../services/mcp/McpHub"
import crypto from "crypto"
import { insertGroups } from "./diff/insert-groups"
import { EXPERIMENT_IDS, experiments as Experiments } from "../shared/experiments"
import { EXPERIMENT_IDS, experiments as Experiments, ExperimentId } from "../shared/experiments"
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
type ToolResponse = string | Array<Anthropic.TextBlockParam | Anthropic.ImageBlockParam>
type UserContent = Array<
Anthropic.TextBlockParam | Anthropic.ImageBlockParam | Anthropic.ToolUseBlockParam | Anthropic.ToolResultBlockParam
>
type UserContent = Array<Anthropic.Messages.ContentBlockParam>
export type ClineOptions = {
provider: ClineProvider
apiConfiguration: ApiConfiguration
customInstructions?: string
enableDiff?: boolean
enableCheckpoints?: boolean
fuzzyMatchThreshold?: number
task?: string
images?: string[]
historyItem?: HistoryItem
experiments?: Record<string, boolean>
startTask?: boolean
}
export class Cline {
readonly taskId: string
@ -118,19 +130,20 @@ export class Cline {
private didAlreadyUseTool = false
private didCompleteReadingStream = false
constructor(
provider: ClineProvider,
apiConfiguration: ApiConfiguration,
customInstructions?: string,
enableDiff?: boolean,
enableCheckpoints?: boolean,
fuzzyMatchThreshold?: number,
task?: string | undefined,
images?: string[] | undefined,
historyItem?: HistoryItem | undefined,
experiments?: Record<string, boolean>,
) {
if (!task && !images && !historyItem) {
constructor({
provider,
apiConfiguration,
customInstructions,
enableDiff,
enableCheckpoints,
fuzzyMatchThreshold,
task,
images,
historyItem,
experiments,
startTask = true,
}: ClineOptions) {
if (startTask && !task && !images && !historyItem) {
throw new Error("Either historyItem or task/images must be provided")
}
@ -153,13 +166,33 @@ export class Cline {
// Initialize diffStrategy based on current state
this.updateDiffStrategy(Experiments.isEnabled(experiments ?? {}, EXPERIMENT_IDS.DIFF_STRATEGY))
if (task || images) {
this.startTask(task, images)
} else if (historyItem) {
this.resumeTaskFromHistory()
if (startTask) {
if (task || images) {
this.startTask(task, images)
} else if (historyItem) {
this.resumeTaskFromHistory()
} else {
throw new Error("Either historyItem or task/images must be provided")
}
}
}
static create(options: ClineOptions): [Cline, Promise<void>] {
const instance = new Cline({ ...options, startTask: false })
const { images, task, historyItem } = options
let promise
if (images || task) {
promise = instance.startTask(task, images)
} else if (historyItem) {
promise = instance.resumeTaskFromHistory()
} else {
throw new Error("Either historyItem or task/images must be provided")
}
return [instance, promise]
}
// Add method to update diffStrategy
async updateDiffStrategy(experimentalDiffStrategy?: boolean) {
// If not provided, get from current state
@ -745,8 +778,12 @@ export class Cline {
}
}
async abortTask() {
async abortTask(isAbandoned = false) {
// Will stop any autonomously running promises.
if (isAbandoned) {
this.abandoned = true
}
this.abort = true
this.terminalManager.disposeAll()
@ -2753,7 +2790,7 @@ export class Cline {
"mistake_limit_reached",
this.api.getModel().id.includes("claude")
? `This may indicate a failure in his thought process or inability to use a tool properly, which can be mitigated with some user guidance (e.g. "Try breaking down the task into smaller steps").`
: "Roo Code uses complex prompts and iterative task execution that may be challenging for less capable models. For best results, it's recommended to use Claude 3.5 Sonnet for its advanced agentic coding capabilities.",
: "Roo Code uses complex prompts and iterative task execution that may be challenging for less capable models. For best results, it's recommended to use Claude 3.7 Sonnet for its advanced agentic coding capabilities.",
)
if (response === "messageResponse") {
userContent.push(
@ -2836,8 +2873,6 @@ export class Cline {
}
const abortStream = async (cancelReason: ClineApiReqCancelReason, streamingFailedMessage?: string) => {
console.log(`[Cline#abortStream] cancelReason = ${cancelReason}`)
if (this.diffViewProvider.isEditing) {
await this.diffViewProvider.revertChanges() // closes diff view
}
@ -2969,7 +3004,7 @@ export class Cline {
}
// need to call here in case the stream was aborted
if (this.abort) {
if (this.abort || this.abandoned) {
throw new Error("Roo Code instance aborted")
}
@ -3237,9 +3272,29 @@ export class Cline {
details += `\n\n# Current Context Size (Tokens)\n${contextTokens ? `${contextTokens.toLocaleString()} (${contextPercentage}%)` : "(Not available)"}`
// Add current mode and any mode-specific warnings
const { mode, customModes } = (await this.providerRef.deref()?.getState()) ?? {}
const {
mode,
customModes,
customModePrompts,
experiments = {} as Record<ExperimentId, boolean>,
customInstructions: globalCustomInstructions,
preferredLanguage,
} = (await this.providerRef.deref()?.getState()) ?? {}
const currentMode = mode ?? defaultModeSlug
details += `\n\n# Current Mode\n${currentMode}`
const modeDetails = await getFullModeDetails(currentMode, customModes, customModePrompts, {
cwd,
globalCustomInstructions,
preferredLanguage,
})
details += `\n\n# Current Mode\n`
details += `<slug>${currentMode}</slug>\n`
details += `<name>${modeDetails.name}</name>\n`
if (Experiments.isEnabled(experiments ?? {}, EXPERIMENT_IDS.POWER_STEERING)) {
details += `<role>${modeDetails.roleDefinition}</role>\n`
if (modeDetails.customInstructions) {
details += `<custom_instructions>${modeDetails.customInstructions}</custom_instructions>\n`
}
}
// Add warning if not in code mode
if (

View file

@ -1,3 +1,5 @@
// npx jest src/core/__tests__/Cline.test.ts
import { Cline } from "../Cline"
import { ClineProvider } from "../webview/ClineProvider"
import { ApiConfiguration, ModelInfo } from "../../shared/api"
@ -82,7 +84,20 @@ jest.mock("fs/promises", () => ({
return Promise.resolve(JSON.stringify(mockMessages))
}
if (filePath.includes("api_conversation_history.json")) {
return Promise.resolve("[]")
return Promise.resolve(
JSON.stringify([
{
role: "user",
content: [{ type: "text", text: "historical task" }],
ts: Date.now(),
},
{
role: "assistant",
content: [{ type: "text", text: "I'll help you with that task." }],
ts: Date.now(),
},
]),
)
}
return Promise.resolve("[]")
}),
@ -295,93 +310,102 @@ describe("Cline", () => {
taskDirPath: "/mock/storage/path/tasks/123",
apiConversationHistoryFilePath: "/mock/storage/path/tasks/123/api_conversation_history.json",
uiMessagesFilePath: "/mock/storage/path/tasks/123/ui_messages.json",
apiConversationHistory: [],
apiConversationHistory: [
{
role: "user",
content: [{ type: "text", text: "historical task" }],
ts: Date.now(),
},
{
role: "assistant",
content: [{ type: "text", text: "I'll help you with that task." }],
ts: Date.now(),
},
],
}))
})
describe("constructor", () => {
it("should respect provided settings", () => {
const cline = new Cline(
mockProvider,
mockApiConfig,
"custom instructions",
false,
false,
0.95, // 95% threshold
"test task",
)
it("should respect provided settings", async () => {
const [cline, task] = Cline.create({
provider: mockProvider,
apiConfiguration: mockApiConfig,
customInstructions: "custom instructions",
fuzzyMatchThreshold: 0.95,
task: "test task",
})
expect(cline.customInstructions).toBe("custom instructions")
expect(cline.diffEnabled).toBe(false)
await cline.abortTask(true)
await task.catch(() => {})
})
it("should use default fuzzy match threshold when not provided", () => {
const cline = new Cline(
mockProvider,
mockApiConfig,
"custom instructions",
true,
false,
undefined,
"test task",
)
it("should use default fuzzy match threshold when not provided", async () => {
const [cline, task] = await Cline.create({
provider: mockProvider,
apiConfiguration: mockApiConfig,
customInstructions: "custom instructions",
enableDiff: true,
fuzzyMatchThreshold: 0.95,
task: "test task",
})
expect(cline.diffEnabled).toBe(true)
// The diff strategy should be created with default threshold (1.0)
expect(cline.diffStrategy).toBeDefined()
await cline.abortTask(true)
await task.catch(() => {})
})
it("should use provided fuzzy match threshold", () => {
it("should use provided fuzzy match threshold", async () => {
const getDiffStrategySpy = jest.spyOn(require("../diff/DiffStrategy"), "getDiffStrategy")
const cline = new Cline(
mockProvider,
mockApiConfig,
"custom instructions",
true,
false,
0.9, // 90% threshold
"test task",
)
const [cline, task] = await Cline.create({
provider: mockProvider,
apiConfiguration: mockApiConfig,
customInstructions: "custom instructions",
enableDiff: true,
fuzzyMatchThreshold: 0.9,
task: "test task",
})
expect(cline.diffEnabled).toBe(true)
expect(cline.diffStrategy).toBeDefined()
expect(getDiffStrategySpy).toHaveBeenCalledWith("claude-3-5-sonnet-20241022", 0.9, false)
getDiffStrategySpy.mockRestore()
await cline.abortTask(true)
await task.catch(() => {})
})
it("should pass default threshold to diff strategy when not provided", () => {
it("should pass default threshold to diff strategy when not provided", async () => {
const getDiffStrategySpy = jest.spyOn(require("../diff/DiffStrategy"), "getDiffStrategy")
const cline = new Cline(
mockProvider,
mockApiConfig,
"custom instructions",
true,
false,
undefined,
"test task",
)
const [cline, task] = Cline.create({
provider: mockProvider,
apiConfiguration: mockApiConfig,
customInstructions: "custom instructions",
enableDiff: true,
task: "test task",
})
expect(cline.diffEnabled).toBe(true)
expect(cline.diffStrategy).toBeDefined()
expect(getDiffStrategySpy).toHaveBeenCalledWith("claude-3-5-sonnet-20241022", 1.0, false)
getDiffStrategySpy.mockRestore()
await cline.abortTask(true)
await task.catch(() => {})
})
it("should require either task or historyItem", () => {
expect(() => {
new Cline(
mockProvider,
mockApiConfig,
undefined, // customInstructions
false, // diffEnabled
false, // checkpointsEnabled
undefined, // fuzzyMatchThreshold
undefined, // task
)
new Cline({ provider: mockProvider, apiConfiguration: mockApiConfig })
}).toThrow("Either historyItem or task/images must be provided")
})
})
@ -431,7 +455,11 @@ describe("Cline", () => {
})
it("should include timezone information in environment details", async () => {
const cline = new Cline(mockProvider, mockApiConfig, undefined, false, false, undefined, "test task")
const [cline, task] = Cline.create({
provider: mockProvider,
apiConfiguration: mockApiConfig,
task: "test task",
})
const details = await cline["getEnvironmentDetails"](false)
@ -440,11 +468,21 @@ describe("Cline", () => {
expect(details).toMatch(/UTC-7:00/) // Fixed offset for America/Los_Angeles
expect(details).toContain("# Current Time")
expect(details).toMatch(/1\/1\/2024.*5:00:00 AM.*\(America\/Los_Angeles, UTC-7:00\)/) // Full time string format
await cline.abortTask(true)
await task.catch(() => {})
})
describe("API conversation handling", () => {
it("should clean conversation history before sending to API", async () => {
const cline = new Cline(mockProvider, mockApiConfig, undefined, false, false, undefined, "test task")
const [cline, task] = Cline.create({
provider: mockProvider,
apiConfiguration: mockApiConfig,
task: "test task",
})
cline.abandoned = true
await task
// Mock the API's createMessage method to capture the conversation history
const createMessageSpy = jest.fn()
@ -552,15 +590,12 @@ describe("Cline", () => {
]
// Test with model that supports images
const clineWithImages = new Cline(
mockProvider,
configWithImages,
undefined,
false,
false,
undefined,
"test task",
)
const [clineWithImages, taskWithImages] = Cline.create({
provider: mockProvider,
apiConfiguration: configWithImages,
task: "test task",
})
// Mock the model info to indicate image support
jest.spyOn(clineWithImages.api, "getModel").mockReturnValue({
id: "claude-3-sonnet",
@ -574,18 +609,16 @@ describe("Cline", () => {
outputPrice: 0.75,
} as ModelInfo,
})
clineWithImages.apiConversationHistory = conversationHistory
// Test with model that doesn't support images
const clineWithoutImages = new Cline(
mockProvider,
configWithoutImages,
undefined,
false,
false,
undefined,
"test task",
)
const [clineWithoutImages, taskWithoutImages] = Cline.create({
provider: mockProvider,
apiConfiguration: configWithoutImages,
task: "test task",
})
// Mock the model info to indicate no image support
jest.spyOn(clineWithoutImages.api, "getModel").mockReturnValue({
id: "gpt-3.5-turbo",
@ -599,6 +632,7 @@ describe("Cline", () => {
outputPrice: 0.2,
} as ModelInfo,
})
clineWithoutImages.apiConversationHistory = conversationHistory
// Mock abort state for both instances
@ -607,6 +641,7 @@ describe("Cline", () => {
set: () => {},
configurable: true,
})
Object.defineProperty(clineWithoutImages, "abort", {
get: () => false,
set: () => {},
@ -621,6 +656,7 @@ describe("Cline", () => {
content,
"",
])
// Set up mock streams
const mockStreamWithImages = (async function* () {
yield { type: "text", text: "test response" }
@ -648,6 +684,12 @@ describe("Cline", () => {
},
]
clineWithImages.abandoned = true
await taskWithImages.catch(() => {})
clineWithoutImages.abandoned = true
await taskWithoutImages.catch(() => {})
// Trigger API requests
await clineWithImages.recursivelyMakeClineRequests([{ type: "text", text: "test request" }])
await clineWithoutImages.recursivelyMakeClineRequests([{ type: "text", text: "test request" }])
@ -670,8 +712,12 @@ describe("Cline", () => {
})
})
it("should handle API retry with countdown", async () => {
const cline = new Cline(mockProvider, mockApiConfig, undefined, false, false, undefined, "test task")
it.skip("should handle API retry with countdown", async () => {
const [cline, task] = Cline.create({
provider: mockProvider,
apiConfiguration: mockApiConfig,
task: "test task",
})
// Mock delay to track countdown timing
const mockDelay = jest.fn().mockResolvedValue(undefined)
@ -785,10 +831,17 @@ describe("Cline", () => {
expect(errorMessage).toBe(
`${mockError.message}\n\nRetry attempt 1\nRetrying in ${baseDelay} seconds...`,
)
await cline.abortTask(true)
await task.catch(() => {})
})
it("should not apply retry delay twice", async () => {
const cline = new Cline(mockProvider, mockApiConfig, undefined, false, false, undefined, "test task")
it.skip("should not apply retry delay twice", async () => {
const [cline, task] = Cline.create({
provider: mockProvider,
apiConfiguration: mockApiConfig,
task: "test task",
})
// Mock delay to track countdown timing
const mockDelay = jest.fn().mockResolvedValue(undefined)
@ -901,19 +954,18 @@ describe("Cline", () => {
undefined,
false,
)
await cline.abortTask(true)
await task.catch(() => {})
})
describe("loadContext", () => {
it("should process mentions in task and feedback tags", async () => {
const cline = new Cline(
mockProvider,
mockApiConfig,
undefined,
false,
false,
undefined,
"test task",
)
const [cline, task] = Cline.create({
provider: mockProvider,
apiConfiguration: mockApiConfig,
task: "test task",
})
// Mock parseMentions to track calls
const mockParseMentions = jest.fn().mockImplementation((text) => `processed: ${text}`)
@ -978,6 +1030,9 @@ describe("Cline", () => {
const toolResult2 = processedContent[3] as Anthropic.ToolResultBlockParam
const content2 = Array.isArray(toolResult2.content) ? toolResult2.content[0] : toolResult2.content
expect((content2 as Anthropic.TextBlockParam).text).toBe("Regular tool result with @/path")
await cline.abortTask(true)
await task.catch(() => {})
})
})
})

View file

@ -1,3 +1,5 @@
// npx jest src/core/config/__tests__/CustomModesManager.test.ts
import * as vscode from "vscode"
import * as path from "path"
import * as fs from "fs/promises"
@ -15,9 +17,10 @@ describe("CustomModesManager", () => {
let mockOnUpdate: jest.Mock
let mockWorkspaceFolders: { uri: { fsPath: string } }[]
const mockStoragePath = "/mock/settings"
// Use path.sep to ensure correct path separators for the current platform
const mockStoragePath = `${path.sep}mock${path.sep}settings`
const mockSettingsPath = path.join(mockStoragePath, "settings", "cline_custom_modes.json")
const mockRoomodes = "/mock/workspace/.roomodes"
const mockRoomodes = `${path.sep}mock${path.sep}workspace${path.sep}.roomodes`
beforeEach(() => {
mockOnUpdate = jest.fn()
@ -243,7 +246,15 @@ describe("CustomModesManager", () => {
await manager.updateCustomMode("project-mode", projectMode)
// Verify .roomodes was created with the project mode
expect(fs.writeFile).toHaveBeenCalledWith(mockRoomodes, expect.stringContaining("project-mode"), "utf-8")
expect(fs.writeFile).toHaveBeenCalledWith(
expect.any(String), // Don't check exact path as it may have different separators on different platforms
expect.stringContaining("project-mode"),
"utf-8",
)
// Verify the path is correct regardless of separators
const writeCall = (fs.writeFile as jest.Mock).mock.calls[0]
expect(path.normalize(writeCall[0])).toBe(path.normalize(mockRoomodes))
// Verify the content written to .roomodes
expect(roomodesContent).toEqual({

View file

@ -2543,43 +2543,6 @@ Example: Requesting to list all top level source code definitions in the current
<path>.</path>
</list_code_definition_names>
## write_to_file
Description: Request to write full content to a file at the specified path. If the file exists, it will be overwritten with the provided content. If the file doesn't exist, it will be created. This tool will automatically create any directories needed to write the file.
Parameters:
- path: (required) The path of the file to write to (relative to the current working directory /test/path)
- content: (required) The content to write to the file. ALWAYS provide the COMPLETE intended content of the file, without any truncation or omissions. You MUST include ALL parts of the file, even if they haven't been modified. Do NOT include the line numbers in the content though, just the actual content of the file.
- line_count: (required) The number of lines in the file. Make sure to compute this based on the actual content of the file, not the number of lines in the content you're providing.
Usage:
<write_to_file>
<path>File path here</path>
<content>
Your file content here
</content>
<line_count>total number of lines in the file, including empty lines</line_count>
</write_to_file>
Example: Requesting to write to frontend-config.json
<write_to_file>
<path>frontend-config.json</path>
<content>
{
"apiEndpoint": "https://api.example.com",
"theme": {
"primaryColor": "#007bff",
"secondaryColor": "#6c757d",
"fontFamily": "Arial, sans-serif"
},
"features": {
"darkMode": true,
"notifications": true,
"analytics": false
},
"version": "1.0.0"
}
</content>
<line_count>14</line_count>
</write_to_file>
## apply_diff
Description: Request to replace existing code using a search and replace block.
This tool allows for precise, surgical replaces to files by specifying exactly what content to search for and what to replace it with.
@ -2640,6 +2603,43 @@ Your search/replace content here
<end_line>5</end_line>
</apply_diff>
## write_to_file
Description: Request to write full content to a file at the specified path. If the file exists, it will be overwritten with the provided content. If the file doesn't exist, it will be created. This tool will automatically create any directories needed to write the file.
Parameters:
- path: (required) The path of the file to write to (relative to the current working directory /test/path)
- content: (required) The content to write to the file. ALWAYS provide the COMPLETE intended content of the file, without any truncation or omissions. You MUST include ALL parts of the file, even if they haven't been modified. Do NOT include the line numbers in the content though, just the actual content of the file.
- line_count: (required) The number of lines in the file. Make sure to compute this based on the actual content of the file, not the number of lines in the content you're providing.
Usage:
<write_to_file>
<path>File path here</path>
<content>
Your file content here
</content>
<line_count>total number of lines in the file, including empty lines</line_count>
</write_to_file>
Example: Requesting to write to frontend-config.json
<write_to_file>
<path>frontend-config.json</path>
<content>
{
"apiEndpoint": "https://api.example.com",
"theme": {
"primaryColor": "#007bff",
"secondaryColor": "#6c757d",
"fontFamily": "Arial, sans-serif"
},
"features": {
"darkMode": true,
"notifications": true,
"analytics": false
},
"version": "1.0.0"
}
</content>
<line_count>14</line_count>
</write_to_file>
## execute_command
Description: Request to execute a CLI command on the system. Use this when you need to perform system operations or run specific commands to accomplish any step in the user's task. You must tailor your command to the user's system and provide a clear explanation of what the command does. For command chaining, use the appropriate chaining syntax for the user's shell. Prefer to execute complex CLI commands over creating executable scripts, as they are more flexible and easier to run. Commands will be executed in the current working directory: /test/path
Parameters:
@ -2758,7 +2758,7 @@ CAPABILITIES
- When the user initially gives you a task, a recursive list of all filepaths in the current working directory ('/test/path') will be included in environment_details. This provides an overview of the project's file structure, offering key insights into the project from directory/file names (how developers conceptualize and organize their code) and file extensions (the language used). This can also guide decision-making on which files to explore further. If you need to further explore directories such as outside the current working directory, you can use the list_files tool. If you pass 'true' for the recursive parameter, it will list files recursively. Otherwise, it will list files at the top level, which is better suited for generic directories where you don't necessarily need the nested structure, like the Desktop.
- You can use search_files to perform regex searches across files in a specified directory, outputting context-rich results that include surrounding lines. This is particularly useful for understanding code patterns, finding specific implementations, or identifying areas that need refactoring.
- You can use the list_code_definition_names tool to get an overview of source code definitions for all files at the top level of a specified directory. This can be particularly useful when you need to understand the broader context and relationships between certain parts of the code. You may need to call this tool multiple times to understand various parts of the codebase related to the task.
- For example, when asked to make edits or improvements you might analyze the file structure in the initial environment_details to get an overview of the project, then use list_code_definition_names to get further insight using source code definitions for files located in relevant directories, then read_file to examine the contents of relevant files, analyze the code and suggest improvements or make necessary edits, then use the write_to_file or apply_diff tool to apply the changes. If you refactored code that could affect other parts of the codebase, you could use search_files to ensure you update other files as needed.
- For example, when asked to make edits or improvements you might analyze the file structure in the initial environment_details to get an overview of the project, then use list_code_definition_names to get further insight using source code definitions for files located in relevant directories, then read_file to examine the contents of relevant files, analyze the code and suggest improvements or make necessary edits, then use the apply_diff or write_to_file tool to apply the changes. If you refactored code that could affect other parts of the codebase, you could use search_files to ensure you update other files as needed.
- You can use the execute_command tool to run commands on the user's computer whenever you feel it can help accomplish the user's task. When you need to execute a CLI command, you must provide a clear explanation of what the command does. Prefer to execute complex CLI commands over creating executable scripts, since they are more flexible and easier to run. Interactive and long-running commands are allowed, since the commands are run in the user's VSCode terminal. The user may keep commands running in the background and you will be kept updated on their status along the way. Each command you execute is run in a new terminal instance.
====
@ -2775,11 +2775,11 @@ RULES
- You cannot \`cd\` into a different directory to complete a task. You are stuck operating from '/test/path', so be sure to pass in the correct 'path' parameter when using tools that require a path.
- Do not use the ~ character or $HOME to refer to the home directory.
- Before using the execute_command tool, you must first think about the SYSTEM INFORMATION context provided to understand the user's environment and tailor your commands to ensure they are compatible with their system. You must also consider if the command you need to run should be executed in a specific directory outside of the current working directory '/test/path', and if so prepend with \`cd\`'ing into that directory && then executing the command (as one command since you are stuck operating from '/test/path'). For example, if you needed to run \`npm install\` in a project outside of '/test/path', you would need to prepend with a \`cd\` i.e. pseudocode for this would be \`cd (path to project) && (command, in this case npm install)\`.
- When using the search_files tool, craft your regex patterns carefully to balance specificity and flexibility. Based on the user's task you may use it to find code patterns, TODO comments, function definitions, or any text-based information across the project. The results include context, so analyze the surrounding code to better understand the matches. Leverage the search_files tool in combination with other tools for more comprehensive analysis. For example, use it to find specific code patterns, then use read_file to examine the full context of interesting matches before using write_to_file to make informed changes.
- When using the search_files tool, craft your regex patterns carefully to balance specificity and flexibility. Based on the user's task you may use it to find code patterns, TODO comments, function definitions, or any text-based information across the project. The results include context, so analyze the surrounding code to better understand the matches. Leverage the search_files tool in combination with other tools for more comprehensive analysis. For example, use it to find specific code patterns, then use read_file to examine the full context of interesting matches before using apply_diff or write_to_file to make informed changes.
- When creating a new project (such as an app, website, or any software project), organize all new files within a dedicated project directory unless the user specifies otherwise. Use appropriate file paths when writing files, as the write_to_file tool will automatically create any necessary directories. Structure the project logically, adhering to best practices for the specific type of project being created. Unless otherwise specified, new projects should be easily run without additional setup, for example most projects can be built in HTML, CSS, and JavaScript - which you can open in a browser.
- For editing files, you have access to these tools: write_to_file (for creating new files or complete file rewrites), apply_diff (for replacing lines in existing files).
- When using the write_to_file tool to modify a file, use the tool directly with the desired content. You do not need to display the content before using the tool. ALWAYS provide the COMPLETE file content in your response. This is NON-NEGOTIABLE. Partial updates or placeholders like '// rest of code unchanged' are STRICTLY FORBIDDEN. You MUST include ALL parts of the file, even if they haven't been modified. Failure to do so will result in incomplete or broken code, severely impacting the user's project.
- For editing files, you have access to these tools: apply_diff (for replacing lines in existing files), write_to_file (for creating new files or complete file rewrites).
- You should always prefer using other editing tools over write_to_file when making changes to existing files since write_to_file is much slower and cannot handle large files.
- When using the write_to_file tool to modify a file, use the tool directly with the desired content. You do not need to display the content before using the tool. ALWAYS provide the COMPLETE file content in your response. This is NON-NEGOTIABLE. Partial updates or placeholders like '// rest of code unchanged' are STRICTLY FORBIDDEN. You MUST include ALL parts of the file, even if they haven't been modified. Failure to do so will result in incomplete or broken code, severely impacting the user's project.
- Some modes have restrictions on which files they can edit. If you attempt to edit a restricted file, the operation will be rejected with a FileRestrictionError that will specify which file patterns are allowed for the current mode.
- Be sure to consider the type of project (e.g. Python, JavaScript, web application) when determining the appropriate structure and files to include. Also consider what files may be most relevant to accomplishing the task, for example looking at a project's manifest file would help you understand the project's dependencies, which you could incorporate into any code you write.
* For example, in architect mode trying to edit app.js would be rejected because architect mode can only edit files matching "\\.md$"

View file

@ -42,15 +42,15 @@ describe("getCapabilitiesSection", () => {
test("includes apply_diff in capabilities when diffStrategy is provided", () => {
const result = getCapabilitiesSection(cwd, false, mcpHub, mockDiffStrategy)
expect(result).toContain("or apply_diff")
expect(result).toContain("then use the write_to_file or apply_diff tool")
expect(result).toContain("apply_diff or")
expect(result).toContain("then use the apply_diff or write_to_file tool")
})
test("excludes apply_diff from capabilities when diffStrategy is undefined", () => {
const result = getCapabilitiesSection(cwd, false, mcpHub, undefined)
expect(result).not.toContain("or apply_diff")
expect(result).not.toContain("apply_diff or")
expect(result).toContain("then use the write_to_file tool")
expect(result).not.toContain("write_to_file or apply_diff")
expect(result).not.toContain("apply_diff or write_to_file")
})
})

View file

@ -17,7 +17,7 @@ CAPABILITIES
- When the user initially gives you a task, a recursive list of all filepaths in the current working directory ('${cwd}') will be included in environment_details. This provides an overview of the project's file structure, offering key insights into the project from directory/file names (how developers conceptualize and organize their code) and file extensions (the language used). This can also guide decision-making on which files to explore further. If you need to further explore directories such as outside the current working directory, you can use the list_files tool. If you pass 'true' for the recursive parameter, it will list files recursively. Otherwise, it will list files at the top level, which is better suited for generic directories where you don't necessarily need the nested structure, like the Desktop.
- You can use search_files to perform regex searches across files in a specified directory, outputting context-rich results that include surrounding lines. This is particularly useful for understanding code patterns, finding specific implementations, or identifying areas that need refactoring.
- You can use the list_code_definition_names tool to get an overview of source code definitions for all files at the top level of a specified directory. This can be particularly useful when you need to understand the broader context and relationships between certain parts of the code. You may need to call this tool multiple times to understand various parts of the codebase related to the task.
- For example, when asked to make edits or improvements you might analyze the file structure in the initial environment_details to get an overview of the project, then use list_code_definition_names to get further insight using source code definitions for files located in relevant directories, then read_file to examine the contents of relevant files, analyze the code and suggest improvements or make necessary edits, then use the write_to_file${diffStrategy ? " or apply_diff" : ""} tool to apply the changes. If you refactored code that could affect other parts of the codebase, you could use search_files to ensure you update other files as needed.
- For example, when asked to make edits or improvements you might analyze the file structure in the initial environment_details to get an overview of the project, then use list_code_definition_names to get further insight using source code definitions for files located in relevant directories, then read_file to examine the contents of relevant files, analyze the code and suggest improvements or make necessary edits, then use ${diffStrategy ? "the apply_diff or write_to_file" : "the write_to_file"} tool to apply the changes. If you refactored code that could affect other parts of the codebase, you could use search_files to ensure you update other files as needed.
- You can use the execute_command tool to run commands on the user's computer whenever you feel it can help accomplish the user's task. When you need to execute a CLI command, you must provide a clear explanation of what the command does. Prefer to execute complex CLI commands over creating executable scripts, since they are more flexible and easier to run. Interactive and long-running commands are allowed, since the commands are run in the user's VSCode terminal. The user may keep commands running in the background and you will be kept updated on their status along the way. Each command you execute is run in a new terminal instance.${
supportsComputerUse
? "\n- You can use the browser_action tool to interact with websites (including html files and locally running development servers) through a Puppeteer-controlled browser when you feel it is necessary in accomplishing the user's task. This tool is particularly useful for web development tasks as it allows you to launch a browser, navigate to pages, interact with elements through clicks and keyboard input, and capture the results through screenshots and console logs. This tool may be useful at key stages of web development tasks-such as after implementing new features, making substantial changes, when troubleshooting issues, or to verify the result of your work. You can analyze the provided screenshots to ensure correct rendering or identify errors, and review console logs for runtime issues.\n - For example, if asked to add a component to a react website, you might create the necessary files, use execute_command to run the site locally, then use browser_action to launch the browser, navigate to the local server, and verify the component renders & functions correctly before closing the browser."

View file

@ -45,7 +45,7 @@ Both files should follow this structure:
"roleDefinition": "You are Roo, a UI/UX expert specializing in design systems and frontend development. Your expertise includes:\\n- Creating and maintaining design systems\\n- Implementing responsive and accessible web interfaces\\n- Working with CSS, HTML, and modern frontend frameworks\\n- Ensuring consistent user experiences across platforms", // Required: non-empty
"groups": [ // Required: array of tool groups (can be empty)
"read", // Read files group (read_file, search_files, list_files, list_code_definition_names)
"edit", // Edit files group (write_to_file, apply_diff) - allows editing any file
"edit", // Edit files group (apply_diff, write_to_file) - allows editing any file
// Or with file restrictions:
// ["edit", { fileRegex: "\\.md$", description: "Markdown files only" }], // Edit group that only allows editing markdown files
"browser", // Browser group (browser_action)

View file

@ -5,11 +5,16 @@ import * as path from "path"
function getEditingInstructions(diffStrategy?: DiffStrategy, experiments?: Record<string, boolean>): string {
const instructions: string[] = []
const availableTools: string[] = ["write_to_file (for creating new files or complete file rewrites)"]
const availableTools: string[] = []
// Collect available editing tools
if (diffStrategy) {
availableTools.push("apply_diff (for replacing lines in existing files)")
availableTools.push(
"apply_diff (for replacing lines in existing files)",
"write_to_file (for creating new files or complete file rewrites)",
)
} else {
availableTools.push("write_to_file (for creating new files or complete file rewrites)")
}
if (experiments?.["insert_content"]) {
availableTools.push("insert_content (for adding lines to existing files)")
@ -36,16 +41,16 @@ function getEditingInstructions(diffStrategy?: DiffStrategy, experiments?: Recor
)
}
instructions.push(
"- When using the write_to_file tool to modify a file, use the tool directly with the desired content. You do not need to display the content before using the tool. ALWAYS provide the COMPLETE file content in your response. This is NON-NEGOTIABLE. Partial updates or placeholders like '// rest of code unchanged' are STRICTLY FORBIDDEN. You MUST include ALL parts of the file, even if they haven't been modified. Failure to do so will result in incomplete or broken code, severely impacting the user's project.",
)
if (availableTools.length > 1) {
instructions.push(
"- You should always prefer using other editing tools over write_to_file when making changes to existing files since write_to_file is much slower and cannot handle large files.",
)
}
instructions.push(
"- When using the write_to_file tool to modify a file, use the tool directly with the desired content. You do not need to display the content before using the tool. ALWAYS provide the COMPLETE file content in your response. This is NON-NEGOTIABLE. Partial updates or placeholders like '// rest of code unchanged' are STRICTLY FORBIDDEN. You MUST include ALL parts of the file, even if they haven't been modified. Failure to do so will result in incomplete or broken code, severely impacting the user's project.",
)
return instructions.join("\n")
}
@ -63,7 +68,7 @@ RULES
- You cannot \`cd\` into a different directory to complete a task. You are stuck operating from '${cwd.toPosix()}', so be sure to pass in the correct 'path' parameter when using tools that require a path.
- Do not use the ~ character or $HOME to refer to the home directory.
- Before using the execute_command tool, you must first think about the SYSTEM INFORMATION context provided to understand the user's environment and tailor your commands to ensure they are compatible with their system. You must also consider if the command you need to run should be executed in a specific directory outside of the current working directory '${cwd.toPosix()}', and if so prepend with \`cd\`'ing into that directory && then executing the command (as one command since you are stuck operating from '${cwd.toPosix()}'). For example, if you needed to run \`npm install\` in a project outside of '${cwd.toPosix()}', you would need to prepend with a \`cd\` i.e. pseudocode for this would be \`cd (path to project) && (command, in this case npm install)\`.
- When using the search_files tool, craft your regex patterns carefully to balance specificity and flexibility. Based on the user's task you may use it to find code patterns, TODO comments, function definitions, or any text-based information across the project. The results include context, so analyze the surrounding code to better understand the matches. Leverage the search_files tool in combination with other tools for more comprehensive analysis. For example, use it to find specific code patterns, then use read_file to examine the full context of interesting matches before using write_to_file to make informed changes.
- When using the search_files tool, craft your regex patterns carefully to balance specificity and flexibility. Based on the user's task you may use it to find code patterns, TODO comments, function definitions, or any text-based information across the project. The results include context, so analyze the surrounding code to better understand the matches. Leverage the search_files tool in combination with other tools for more comprehensive analysis. For example, use it to find specific code patterns, then use read_file to examine the full context of interesting matches before using ${diffStrategy ? "apply_diff or write_to_file" : "write_to_file"} to make informed changes.
- When creating a new project (such as an app, website, or any software project), organize all new files within a dedicated project directory unless the user specifies otherwise. Use appropriate file paths when writing files, as the write_to_file tool will automatically create any necessary directories. Structure the project logically, adhering to best practices for the specific type of project being created. Unless otherwise specified, new projects should be easily run without additional setup, for example most projects can be built in HTML, CSS, and JavaScript - which you can open in a browser.
${getEditingInstructions(diffStrategy, experiments)}
- Some modes have restrictions on which files they can edit. If you attempt to edit a restricted file, the operation will be rejected with a FileRestrictionError that will specify which file patterns are allowed for the current mode.

View file

@ -0,0 +1,231 @@
// npx jest src/core/sliding-window/__tests__/sliding-window.test.ts
import { Anthropic } from "@anthropic-ai/sdk"
import { ModelInfo } from "../../../shared/api"
import { truncateConversation, truncateConversationIfNeeded } from "../index"
/**
* Tests for the truncateConversation function
*/
describe("truncateConversation", () => {
it("should retain the first message", () => {
const messages: Anthropic.Messages.MessageParam[] = [
{ role: "user", content: "First message" },
{ role: "assistant", content: "Second message" },
{ role: "user", content: "Third message" },
]
const result = truncateConversation(messages, 0.5)
// With 2 messages after the first, 0.5 fraction means remove 1 message
// But 1 is odd, so it rounds down to 0 (to make it even)
expect(result.length).toBe(3) // First message + 2 remaining messages
expect(result[0]).toEqual(messages[0])
expect(result[1]).toEqual(messages[1])
expect(result[2]).toEqual(messages[2])
})
it("should remove the specified fraction of messages (rounded to even number)", () => {
const messages: Anthropic.Messages.MessageParam[] = [
{ role: "user", content: "First message" },
{ role: "assistant", content: "Second message" },
{ role: "user", content: "Third message" },
{ role: "assistant", content: "Fourth message" },
{ role: "user", content: "Fifth message" },
]
// 4 messages excluding first, 0.5 fraction = 2 messages to remove
// 2 is already even, so no rounding needed
const result = truncateConversation(messages, 0.5)
expect(result.length).toBe(3)
expect(result[0]).toEqual(messages[0])
expect(result[1]).toEqual(messages[3])
expect(result[2]).toEqual(messages[4])
})
it("should round to an even number of messages to remove", () => {
const messages: Anthropic.Messages.MessageParam[] = [
{ role: "user", content: "First message" },
{ role: "assistant", content: "Second message" },
{ role: "user", content: "Third message" },
{ role: "assistant", content: "Fourth message" },
{ role: "user", content: "Fifth message" },
{ role: "assistant", content: "Sixth message" },
{ role: "user", content: "Seventh message" },
]
// 6 messages excluding first, 0.3 fraction = 1.8 messages to remove
// 1.8 rounds down to 1, then to 0 to make it even
const result = truncateConversation(messages, 0.3)
expect(result.length).toBe(7) // No messages removed
expect(result).toEqual(messages)
})
it("should handle edge case with fracToRemove = 0", () => {
const messages: Anthropic.Messages.MessageParam[] = [
{ role: "user", content: "First message" },
{ role: "assistant", content: "Second message" },
{ role: "user", content: "Third message" },
]
const result = truncateConversation(messages, 0)
expect(result).toEqual(messages)
})
it("should handle edge case with fracToRemove = 1", () => {
const messages: Anthropic.Messages.MessageParam[] = [
{ role: "user", content: "First message" },
{ role: "assistant", content: "Second message" },
{ role: "user", content: "Third message" },
{ role: "assistant", content: "Fourth message" },
]
// 3 messages excluding first, 1.0 fraction = 3 messages to remove
// But 3 is odd, so it rounds down to 2 to make it even
const result = truncateConversation(messages, 1)
expect(result.length).toBe(2)
expect(result[0]).toEqual(messages[0])
expect(result[1]).toEqual(messages[3])
})
})
/**
* Tests for the getMaxTokens function (private but tested through truncateConversationIfNeeded)
*/
describe("getMaxTokens", () => {
// We'll test this indirectly through truncateConversationIfNeeded
const createModelInfo = (contextWindow: number, maxTokens?: number): ModelInfo => ({
contextWindow,
supportsPromptCache: true, // Not relevant for getMaxTokens
maxTokens,
})
// Reuse across tests for consistency
const messages: Anthropic.Messages.MessageParam[] = [
{ role: "user", content: "First message" },
{ role: "assistant", content: "Second message" },
{ role: "user", content: "Third message" },
{ role: "assistant", content: "Fourth message" },
{ role: "user", content: "Fifth message" },
]
it("should use maxTokens as buffer when specified", () => {
const modelInfo = createModelInfo(100000, 50000)
// Max tokens = 100000 - 50000 = 50000
// Below max tokens - no truncation
const result1 = truncateConversationIfNeeded(messages, 49999, modelInfo)
expect(result1).toEqual(messages)
// Above max tokens - truncate
const result2 = truncateConversationIfNeeded(messages, 50001, modelInfo)
expect(result2).not.toEqual(messages)
expect(result2.length).toBe(3) // Truncated with 0.5 fraction
})
it("should use 20% of context window as buffer when maxTokens is undefined", () => {
const modelInfo = createModelInfo(100000, undefined)
// Max tokens = 100000 - (100000 * 0.2) = 80000
// Below max tokens - no truncation
const result1 = truncateConversationIfNeeded(messages, 79999, modelInfo)
expect(result1).toEqual(messages)
// Above max tokens - truncate
const result2 = truncateConversationIfNeeded(messages, 80001, modelInfo)
expect(result2).not.toEqual(messages)
expect(result2.length).toBe(3) // Truncated with 0.5 fraction
})
it("should handle small context windows appropriately", () => {
const modelInfo = createModelInfo(50000, 10000)
// Max tokens = 50000 - 10000 = 40000
// Below max tokens - no truncation
const result1 = truncateConversationIfNeeded(messages, 39999, modelInfo)
expect(result1).toEqual(messages)
// Above max tokens - truncate
const result2 = truncateConversationIfNeeded(messages, 40001, modelInfo)
expect(result2).not.toEqual(messages)
expect(result2.length).toBe(3) // Truncated with 0.5 fraction
})
it("should handle large context windows appropriately", () => {
const modelInfo = createModelInfo(200000, 30000)
// Max tokens = 200000 - 30000 = 170000
// Below max tokens - no truncation
const result1 = truncateConversationIfNeeded(messages, 169999, modelInfo)
expect(result1).toEqual(messages)
// Above max tokens - truncate
const result2 = truncateConversationIfNeeded(messages, 170001, modelInfo)
expect(result2).not.toEqual(messages)
expect(result2.length).toBe(3) // Truncated with 0.5 fraction
})
})
/**
* Tests for the truncateConversationIfNeeded function
*/
describe("truncateConversationIfNeeded", () => {
const createModelInfo = (contextWindow: number, supportsPromptCache: boolean, maxTokens?: number): ModelInfo => ({
contextWindow,
supportsPromptCache,
maxTokens,
})
const messages: Anthropic.Messages.MessageParam[] = [
{ role: "user", content: "First message" },
{ role: "assistant", content: "Second message" },
{ role: "user", content: "Third message" },
{ role: "assistant", content: "Fourth message" },
{ role: "user", content: "Fifth message" },
]
it("should not truncate if tokens are below max tokens threshold", () => {
const modelInfo = createModelInfo(100000, true, 30000)
const maxTokens = 100000 - 30000 // 70000
const totalTokens = 69999 // Below threshold
const result = truncateConversationIfNeeded(messages, totalTokens, modelInfo)
expect(result).toEqual(messages) // No truncation occurs
})
it("should truncate if tokens are above max tokens threshold", () => {
const modelInfo = createModelInfo(100000, true, 30000)
const maxTokens = 100000 - 30000 // 70000
const totalTokens = 70001 // Above threshold
// When truncating, always uses 0.5 fraction
// With 4 messages after the first, 0.5 fraction means remove 2 messages
const expectedResult = [messages[0], messages[3], messages[4]]
const result = truncateConversationIfNeeded(messages, totalTokens, modelInfo)
expect(result).toEqual(expectedResult)
})
it("should work with non-prompt caching models the same as prompt caching models", () => {
// The implementation no longer differentiates between prompt caching and non-prompt caching models
const modelInfo1 = createModelInfo(100000, true, 30000)
const modelInfo2 = createModelInfo(100000, false, 30000)
// Test below threshold
const belowThreshold = 69999
expect(truncateConversationIfNeeded(messages, belowThreshold, modelInfo1)).toEqual(
truncateConversationIfNeeded(messages, belowThreshold, modelInfo2),
)
// Test above threshold
const aboveThreshold = 70001
expect(truncateConversationIfNeeded(messages, aboveThreshold, modelInfo1)).toEqual(
truncateConversationIfNeeded(messages, aboveThreshold, modelInfo2),
)
})
})

View file

@ -1,4 +1,5 @@
import { Anthropic } from "@anthropic-ai/sdk"
import { ModelInfo } from "../../shared/api"
/**
@ -27,13 +28,9 @@ export function truncateConversation(
/**
* Conditionally truncates the conversation messages if the total token count exceeds the model's limit.
*
* Depending on whether the model supports prompt caching, different maximum token thresholds
* and truncation fractions are used. If the current total tokens exceed the threshold,
* the conversation is truncated using the appropriate fraction.
*
* @param {Anthropic.Messages.MessageParam[]} messages - The conversation messages.
* @param {number} totalTokens - The total number of tokens in the conversation.
* @param {ModelInfo} modelInfo - Model metadata including context window size and prompt cache support.
* @param {ModelInfo} modelInfo - Model metadata including context window size.
* @returns {Anthropic.Messages.MessageParam[]} The original or truncated conversation messages.
*/
export function truncateConversationIfNeeded(
@ -41,57 +38,16 @@ export function truncateConversationIfNeeded(
totalTokens: number,
modelInfo: ModelInfo,
): Anthropic.Messages.MessageParam[] {
if (modelInfo.supportsPromptCache) {
return totalTokens < getMaxTokensForPromptCachingModels(modelInfo)
? messages
: truncateConversation(messages, getTruncFractionForPromptCachingModels(modelInfo))
} else {
return totalTokens < getMaxTokensForNonPromptCachingModels(modelInfo)
? messages
: truncateConversation(messages, getTruncFractionForNonPromptCachingModels(modelInfo))
}
return totalTokens < getMaxTokens(modelInfo) ? messages : truncateConversation(messages, 0.5)
}
/**
* Calculates the maximum allowed tokens for models that support prompt caching.
*
* The maximum is computed as the greater of (contextWindow - 40000) and 80% of the contextWindow.
* Calculates the maximum allowed tokens
*
* @param {ModelInfo} modelInfo - The model information containing the context window size.
* @returns {number} The maximum number of tokens allowed for prompt caching models.
* @returns {number} The maximum number of tokens allowed
*/
function getMaxTokensForPromptCachingModels(modelInfo: ModelInfo): number {
return Math.max(modelInfo.contextWindow - 40_000, modelInfo.contextWindow * 0.8)
}
/**
* Provides the fraction of messages to remove for models that support prompt caching.
*
* @param {ModelInfo} modelInfo - The model information (unused in current implementation).
* @returns {number} The truncation fraction for prompt caching models (fixed at 0.5).
*/
function getTruncFractionForPromptCachingModels(modelInfo: ModelInfo): number {
return 0.5
}
/**
* Calculates the maximum allowed tokens for models that do not support prompt caching.
*
* The maximum is computed as the greater of (contextWindow - 40000) and 80% of the contextWindow.
*
* @param {ModelInfo} modelInfo - The model information containing the context window size.
* @returns {number} The maximum number of tokens allowed for non-prompt caching models.
*/
function getMaxTokensForNonPromptCachingModels(modelInfo: ModelInfo): number {
return Math.max(modelInfo.contextWindow - 40_000, modelInfo.contextWindow * 0.8)
}
/**
* Provides the fraction of messages to remove for models that do not support prompt caching.
*
* @param {ModelInfo} modelInfo - The model information.
* @returns {number} The truncation fraction for non-prompt caching models (fixed at 0.1).
*/
function getTruncFractionForNonPromptCachingModels(modelInfo: ModelInfo): number {
return Math.min(40_000 / modelInfo.contextWindow, 0.2)
function getMaxTokens(modelInfo: ModelInfo): number {
// The buffer needs to be at least as large as `modelInfo.maxTokens`, or 20% of the context window if for some reason it's not set.
return modelInfo.contextWindow - (modelInfo.maxTokens || modelInfo.contextWindow * 0.2)
}

View file

@ -8,137 +8,51 @@ import * as path from "path"
import * as vscode from "vscode"
import simpleGit from "simple-git"
import { buildApiHandler } from "../../api"
import { ApiConfiguration, ApiProvider, ModelInfo } from "../../shared/api"
import { findLast } from "../../shared/array"
import { CustomSupportPrompts, supportPrompt } from "../../shared/support-prompt"
import { GlobalFileNames } from "../../shared/globalFileNames"
import type { SecretKey, GlobalStateKey } from "../../shared/globalState"
import { HistoryItem } from "../../shared/HistoryItem"
import { ApiConfigMeta, ExtensionMessage } from "../../shared/ExtensionMessage"
import { checkoutDiffPayloadSchema, checkoutRestorePayloadSchema, WebviewMessage } from "../../shared/WebviewMessage"
import { Mode, CustomModePrompts, PromptComponent, defaultModeSlug } from "../../shared/modes"
import { checkExistKey } from "../../shared/checkExistApiConfig"
import { EXPERIMENT_IDS, experiments as Experiments, experimentDefault, ExperimentId } from "../../shared/experiments"
import { downloadTask } from "../../integrations/misc/export-markdown"
import { openFile, openImage } from "../../integrations/misc/open-file"
import { selectImages } from "../../integrations/misc/process-images"
import { getTheme } from "../../integrations/theme/getTheme"
import { getDiffStrategy } from "../diff/DiffStrategy"
import WorkspaceTracker from "../../integrations/workspace/WorkspaceTracker"
import { McpHub } from "../../services/mcp/McpHub"
import { ApiConfiguration, ApiProvider, ModelInfo } from "../../shared/api"
import { findLast } from "../../shared/array"
import { ApiConfigMeta, ExtensionMessage } from "../../shared/ExtensionMessage"
import { HistoryItem } from "../../shared/HistoryItem"
import { checkoutDiffPayloadSchema, checkoutRestorePayloadSchema, WebviewMessage } from "../../shared/WebviewMessage"
import { Mode, CustomModePrompts, PromptComponent, defaultModeSlug } from "../../shared/modes"
import { SYSTEM_PROMPT } from "../prompts/system"
import { McpServerManager } from "../../services/mcp/McpServerManager"
import { fileExistsAtPath } from "../../utils/fs"
import { playSound, setSoundEnabled, setSoundVolume } from "../../utils/sound"
import { singleCompletionHandler } from "../../utils/single-completion-handler"
import { searchCommits } from "../../utils/git"
import { getDiffStrategy } from "../diff/DiffStrategy"
import { SYSTEM_PROMPT } from "../prompts/system"
import { ConfigManager } from "../config/ConfigManager"
import { CustomModesManager } from "../config/CustomModesManager"
import { buildApiHandler } from "../../api"
import { getOpenRouterModels } from "../../api/providers/openrouter"
import { getGlamaModels } from "../../api/providers/glama"
import { getUnboundModels } from "../../api/providers/unbound"
import { getRequestyModels } from "../../api/providers/requesty"
import { getOpenAiModels } from "../../api/providers/openai"
import { getOllamaModels } from "../../api/providers/ollama"
import { getVsCodeLmModels } from "../../api/providers/vscode-lm"
import { getLmStudioModels } from "../../api/providers/lmstudio"
import { ACTION_NAMES } from "../CodeActionProvider"
import { Cline } from "../Cline"
import { openMention } from "../mentions"
import { getNonce } from "./getNonce"
import { getUri } from "./getUri"
import { playSound, setSoundEnabled, setSoundVolume } from "../../utils/sound"
import { checkExistKey } from "../../shared/checkExistApiConfig"
import { singleCompletionHandler } from "../../utils/single-completion-handler"
import { searchCommits } from "../../utils/git"
import { ConfigManager } from "../config/ConfigManager"
import { CustomModesManager } from "../config/CustomModesManager"
import { EXPERIMENT_IDS, experiments as Experiments, experimentDefault, ExperimentId } from "../../shared/experiments"
import { CustomSupportPrompts, supportPrompt } from "../../shared/support-prompt"
import { ACTION_NAMES } from "../CodeActionProvider"
import { McpServerManager } from "../../services/mcp/McpServerManager"
/*
https://github.com/microsoft/vscode-webview-ui-toolkit-samples/blob/main/default/weather-webview/src/providers/WeatherViewProvider.ts
https://github.com/KumarVariable/vscode-extension-sidebar-html/blob/master/src/customSidebarViewProvider.ts
*/
type SecretKey =
| "apiKey"
| "glamaApiKey"
| "openRouterApiKey"
| "awsAccessKey"
| "awsSecretKey"
| "awsSessionToken"
| "openAiApiKey"
| "geminiApiKey"
| "openAiNativeApiKey"
| "deepSeekApiKey"
| "mistralApiKey"
| "unboundApiKey"
| "requestyApiKey"
type GlobalStateKey =
| "apiProvider"
| "apiModelId"
| "glamaModelId"
| "glamaModelInfo"
| "awsRegion"
| "awsUseCrossRegionInference"
| "awsProfile"
| "awsUseProfile"
| "vertexProjectId"
| "vertexRegion"
| "lastShownAnnouncementId"
| "customInstructions"
| "alwaysAllowReadOnly"
| "alwaysAllowWrite"
| "alwaysAllowExecute"
| "alwaysAllowBrowser"
| "alwaysAllowMcp"
| "alwaysAllowModeSwitch"
| "taskHistory"
| "openAiBaseUrl"
| "openAiModelId"
| "openAiCustomModelInfo"
| "openAiUseAzure"
| "ollamaModelId"
| "ollamaBaseUrl"
| "lmStudioModelId"
| "lmStudioBaseUrl"
| "anthropicBaseUrl"
| "azureApiVersion"
| "openAiStreamingEnabled"
| "openRouterModelId"
| "openRouterModelInfo"
| "openRouterBaseUrl"
| "openRouterUseMiddleOutTransform"
| "allowedCommands"
| "soundEnabled"
| "soundVolume"
| "diffEnabled"
| "checkpointsEnabled"
| "browserViewportSize"
| "screenshotQuality"
| "fuzzyMatchThreshold"
| "preferredLanguage" // Language setting for Cline's communication
| "writeDelayMs"
| "terminalOutputLineLimit"
| "mcpEnabled"
| "enableMcpServerCreation"
| "alwaysApproveResubmit"
| "requestDelaySeconds"
| "rateLimitSeconds"
| "currentApiConfigName"
| "listApiConfigMeta"
| "vsCodeLmModelSelector"
| "mode"
| "modeApiConfigs"
| "customModePrompts"
| "customSupportPrompts"
| "enhancementApiConfigId"
| "experiments" // Map of experiment IDs to their enabled state
| "autoApprovalEnabled"
| "customModes" // Array of custom modes
| "unboundModelId"
| "requestyModelId"
| "requestyModelInfo"
| "unboundModelInfo"
| "modelTemperature"
| "mistralCodestralUrl"
| "maxOpenTabsContext"
export const GlobalFileNames = {
apiConversationHistory: "api_conversation_history.json",
uiMessages: "ui_messages.json",
glamaModels: "glama_models.json",
openRouterModels: "openrouter_models.json",
requestyModels: "requesty_models.json",
mcpSettings: "cline_mcp_settings.json",
unboundModels: "unbound_models.json",
}
/**
* https://github.com/microsoft/vscode-webview-ui-toolkit-samples/blob/main/default/weather-webview/src/providers/WeatherViewProvider.ts
* https://github.com/KumarVariable/vscode-extension-sidebar-html/blob/master/src/customSidebarViewProvider.ts
*/
export class ClineProvider implements vscode.WebviewViewProvider {
public static readonly sideBarId = "roo-cline.SidebarProvider" // used in package.json as the view's id. This value cannot be changed due to how vscode caches views based on their id, and updating the id would break existing instances of the extension.
@ -413,18 +327,17 @@ export class ClineProvider implements vscode.WebviewViewProvider {
const modePrompt = customModePrompts?.[mode] as PromptComponent
const effectiveInstructions = [globalInstructions, modePrompt?.customInstructions].filter(Boolean).join("\n\n")
this.cline = new Cline(
this,
this.cline = new Cline({
provider: this,
apiConfiguration,
effectiveInstructions,
diffEnabled,
checkpointsEnabled,
customInstructions: effectiveInstructions,
enableDiff: diffEnabled,
enableCheckpoints: checkpointsEnabled,
fuzzyMatchThreshold,
task,
images,
undefined,
experiments,
)
})
}
public async initClineWithHistoryItem(historyItem: HistoryItem) {
@ -444,18 +357,16 @@ export class ClineProvider implements vscode.WebviewViewProvider {
const modePrompt = customModePrompts?.[mode] as PromptComponent
const effectiveInstructions = [globalInstructions, modePrompt?.customInstructions].filter(Boolean).join("\n\n")
this.cline = new Cline(
this,
this.cline = new Cline({
provider: this,
apiConfiguration,
effectiveInstructions,
diffEnabled,
checkpointsEnabled,
customInstructions: effectiveInstructions,
enableDiff: diffEnabled,
enableCheckpoints: checkpointsEnabled,
fuzzyMatchThreshold,
undefined,
undefined,
historyItem,
experiments,
)
})
}
public async postMessageToWebview(message: ExtensionMessage) {
@ -621,15 +532,10 @@ export class ClineProvider implements vscode.WebviewViewProvider {
this.postStateToWebview()
this.workspaceTracker?.initializeFilePaths() // don't await
getTheme().then((theme) =>
this.postMessageToWebview({ type: "theme", text: JSON.stringify(theme) }),
)
// post last cached models in case the call to endpoint fails
this.readOpenRouterModels().then((openRouterModels) => {
if (openRouterModels) {
this.postMessageToWebview({ type: "openRouterModels", openRouterModels })
}
})
// If MCP Hub is already initialized, update the webview with current server list
if (this.mcpHub) {
@ -639,13 +545,37 @@ export class ClineProvider implements vscode.WebviewViewProvider {
})
}
// gui relies on model info to be up-to-date to provide the most accurate pricing, so we need to fetch the latest details on launch.
// we do this for all users since many users switch between api providers and if they were to switch back to openrouter it would be showing outdated model info if we hadn't retrieved the latest at this point
// (see normalizeApiConfiguration > openrouter)
this.refreshOpenRouterModels().then(async (openRouterModels) => {
const cacheDir = await this.ensureCacheDirectoryExists()
// Post last cached models in case the call to endpoint fails.
this.readModelsFromCache(GlobalFileNames.openRouterModels).then((openRouterModels) => {
if (openRouterModels) {
// 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)
this.postMessageToWebview({ type: "openRouterModels", openRouterModels })
}
})
// GUI relies on model info to be up-to-date to provide
// the most accurate pricing, so we need to fetch the
// latest details on launch.
// We do this for all users since many users switch
// between api providers and if they were to switch back
// to OpenRouter it would be showing outdated model info
// if we hadn't retrieved the latest at this point
// (see normalizeApiConfiguration > openrouter).
getOpenRouterModels().then(async (openRouterModels) => {
if (Object.keys(openRouterModels).length > 0) {
await fs.writeFile(
path.join(cacheDir, GlobalFileNames.openRouterModels),
JSON.stringify(openRouterModels),
)
await this.postMessageToWebview({ type: "openRouterModels", openRouterModels })
// 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 this.getState()
if (apiConfiguration.openRouterModelId) {
await this.updateGlobalState(
"openRouterModelInfo",
@ -655,15 +585,23 @@ export class ClineProvider implements vscode.WebviewViewProvider {
}
}
})
this.readGlamaModels().then((glamaModels) => {
this.readModelsFromCache(GlobalFileNames.glamaModels).then((glamaModels) => {
if (glamaModels) {
this.postMessageToWebview({ type: "glamaModels", glamaModels })
}
})
this.refreshGlamaModels().then(async (glamaModels) => {
if (glamaModels) {
// 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)
getGlamaModels().then(async (glamaModels) => {
if (Object.keys(glamaModels).length > 0) {
await fs.writeFile(
path.join(cacheDir, GlobalFileNames.glamaModels),
JSON.stringify(glamaModels),
)
await this.postMessageToWebview({ type: "glamaModels", glamaModels })
const { apiConfiguration } = await this.getState()
if (apiConfiguration.glamaModelId) {
await this.updateGlobalState(
"glamaModelInfo",
@ -674,14 +612,22 @@ export class ClineProvider implements vscode.WebviewViewProvider {
}
})
this.readUnboundModels().then((unboundModels) => {
this.readModelsFromCache(GlobalFileNames.unboundModels).then((unboundModels) => {
if (unboundModels) {
this.postMessageToWebview({ type: "unboundModels", unboundModels })
}
})
this.refreshUnboundModels().then(async (unboundModels) => {
if (unboundModels) {
getUnboundModels().then(async (unboundModels) => {
if (Object.keys(unboundModels).length > 0) {
await fs.writeFile(
path.join(cacheDir, GlobalFileNames.unboundModels),
JSON.stringify(unboundModels),
)
await this.postMessageToWebview({ type: "unboundModels", unboundModels })
const { apiConfiguration } = await this.getState()
if (apiConfiguration?.unboundModelId) {
await this.updateGlobalState(
"unboundModelInfo",
@ -692,15 +638,22 @@ export class ClineProvider implements vscode.WebviewViewProvider {
}
})
this.readRequestyModels().then((requestyModels) => {
this.readModelsFromCache(GlobalFileNames.requestyModels).then((requestyModels) => {
if (requestyModels) {
this.postMessageToWebview({ type: "requestyModels", requestyModels })
}
})
this.refreshRequestyModels().then(async (requestyModels) => {
if (requestyModels) {
// 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)
getRequestyModels().then(async (requestyModels) => {
if (Object.keys(requestyModels).length > 0) {
await fs.writeFile(
path.join(cacheDir, GlobalFileNames.requestyModels),
JSON.stringify(requestyModels),
)
await this.postMessageToWebview({ type: "requestyModels", requestyModels })
const { apiConfiguration } = await this.getState()
if (apiConfiguration.requestyModelId) {
await this.updateGlobalState(
"requestyModelInfo",
@ -843,41 +796,82 @@ export class ClineProvider implements vscode.WebviewViewProvider {
case "resetState":
await this.resetState()
break
case "requestOllamaModels":
const ollamaModels = await this.getOllamaModels(message.text)
this.postMessageToWebview({ type: "ollamaModels", ollamaModels })
break
case "requestLmStudioModels":
const lmStudioModels = await this.getLmStudioModels(message.text)
this.postMessageToWebview({ type: "lmStudioModels", lmStudioModels })
break
case "requestVsCodeLmModels":
const vsCodeLmModels = await this.getVsCodeLmModels()
this.postMessageToWebview({ type: "vsCodeLmModels", vsCodeLmModels })
case "refreshOpenRouterModels":
const openRouterModels = await getOpenRouterModels()
if (Object.keys(openRouterModels).length > 0) {
const cacheDir = await this.ensureCacheDirectoryExists()
await fs.writeFile(
path.join(cacheDir, GlobalFileNames.openRouterModels),
JSON.stringify(openRouterModels),
)
await this.postMessageToWebview({ type: "openRouterModels", openRouterModels })
}
break
case "refreshGlamaModels":
await this.refreshGlamaModels()
const glamaModels = await getGlamaModels()
if (Object.keys(glamaModels).length > 0) {
const cacheDir = await this.ensureCacheDirectoryExists()
await fs.writeFile(
path.join(cacheDir, GlobalFileNames.glamaModels),
JSON.stringify(glamaModels),
)
await this.postMessageToWebview({ type: "glamaModels", glamaModels })
}
break
case "refreshOpenRouterModels":
await this.refreshOpenRouterModels()
case "refreshUnboundModels":
const unboundModels = await getUnboundModels()
if (Object.keys(unboundModels).length > 0) {
const cacheDir = await this.ensureCacheDirectoryExists()
await fs.writeFile(
path.join(cacheDir, GlobalFileNames.unboundModels),
JSON.stringify(unboundModels),
)
await this.postMessageToWebview({ type: "unboundModels", unboundModels })
}
break
case "refreshRequestyModels":
const requestyModels = await getRequestyModels()
if (Object.keys(requestyModels).length > 0) {
const cacheDir = await this.ensureCacheDirectoryExists()
await fs.writeFile(
path.join(cacheDir, GlobalFileNames.requestyModels),
JSON.stringify(requestyModels),
)
await this.postMessageToWebview({ type: "requestyModels", requestyModels })
}
break
case "refreshOpenAiModels":
if (message?.values?.baseUrl && message?.values?.apiKey) {
const openAiModels = await this.getOpenAiModels(
const openAiModels = await getOpenAiModels(
message?.values?.baseUrl,
message?.values?.apiKey,
)
this.postMessageToWebview({ type: "openAiModels", openAiModels })
}
break
case "refreshUnboundModels":
await this.refreshUnboundModels()
case "requestOllamaModels":
const ollamaModels = await getOllamaModels(message.text)
// TODO: Cache like we do for OpenRouter, etc?
this.postMessageToWebview({ type: "ollamaModels", ollamaModels })
break
case "refreshRequestyModels":
if (message?.values?.apiKey) {
const requestyModels = await this.refreshRequestyModels(message?.values?.apiKey)
this.postMessageToWebview({ type: "requestyModels", requestyModels: requestyModels })
}
case "requestLmStudioModels":
const lmStudioModels = await getLmStudioModels(message.text)
// TODO: Cache like we do for OpenRouter, etc?
this.postMessageToWebview({ type: "lmStudioModels", lmStudioModels })
break
case "requestVsCodeLmModels":
const vsCodeLmModels = await getVsCodeLmModels()
// TODO: Cache like we do for OpenRouter, etc?
this.postMessageToWebview({ type: "vsCodeLmModels", vsCodeLmModels })
break
case "openImage":
openImage(message.text!)
@ -1657,6 +1651,7 @@ export class ClineProvider implements vscode.WebviewViewProvider {
lmStudioModelId,
lmStudioBaseUrl,
anthropicBaseUrl,
anthropicThinking,
geminiApiKey,
openAiNativeApiKey,
deepSeekApiKey,
@ -1704,6 +1699,7 @@ export class ClineProvider implements vscode.WebviewViewProvider {
this.updateGlobalState("lmStudioModelId", lmStudioModelId),
this.updateGlobalState("lmStudioBaseUrl", lmStudioBaseUrl),
this.updateGlobalState("anthropicBaseUrl", anthropicBaseUrl),
this.updateGlobalState("anthropicThinking", anthropicThinking),
this.storeSecret("geminiApiKey", geminiApiKey),
this.storeSecret("openAiNativeApiKey", openAiNativeApiKey),
this.storeSecret("deepSeekApiKey", deepSeekApiKey),
@ -1789,175 +1785,24 @@ export class ClineProvider implements vscode.WebviewViewProvider {
return settingsDir
}
// Ollama
async getOllamaModels(baseUrl?: string) {
try {
if (!baseUrl) {
baseUrl = "http://localhost:11434"
}
if (!URL.canParse(baseUrl)) {
return []
}
const response = await axios.get(`${baseUrl}/api/tags`)
const modelsArray = response.data?.models?.map((model: any) => model.name) || []
const models = [...new Set<string>(modelsArray)]
return models
} catch (error) {
return []
}
private async ensureCacheDirectoryExists() {
const cacheDir = path.join(this.context.globalStorageUri.fsPath, "cache")
await fs.mkdir(cacheDir, { recursive: true })
return cacheDir
}
// LM Studio
private async readModelsFromCache(filename: string): Promise<Record<string, ModelInfo> | undefined> {
const filePath = path.join(await this.ensureCacheDirectoryExists(), filename)
const fileExists = await fileExistsAtPath(filePath)
async getLmStudioModels(baseUrl?: string) {
try {
if (!baseUrl) {
baseUrl = "http://localhost:1234"
}
if (!URL.canParse(baseUrl)) {
return []
}
const response = await axios.get(`${baseUrl}/v1/models`)
const modelsArray = response.data?.data?.map((model: any) => model.id) || []
const models = [...new Set<string>(modelsArray)]
return models
} catch (error) {
return []
}
}
// VSCode LM API
private async getVsCodeLmModels() {
try {
const models = await vscode.lm.selectChatModels({})
return models || []
} catch (error) {
this.outputChannel.appendLine(
`Error fetching VS Code LM models: ${JSON.stringify(error, Object.getOwnPropertyNames(error), 2)}`,
)
return []
}
}
// OpenAi
async getOpenAiModels(baseUrl?: string, apiKey?: string) {
try {
if (!baseUrl) {
return []
}
if (!URL.canParse(baseUrl)) {
return []
}
const config: Record<string, any> = {}
if (apiKey) {
config["headers"] = { Authorization: `Bearer ${apiKey}` }
}
const response = await axios.get(`${baseUrl}/models`, config)
const modelsArray = response.data?.data?.map((model: any) => model.id) || []
const models = [...new Set<string>(modelsArray)]
return models
} catch (error) {
return []
}
}
// Requesty
async readRequestyModels(): Promise<Record<string, ModelInfo> | undefined> {
const requestyModelsFilePath = path.join(
await this.ensureCacheDirectoryExists(),
GlobalFileNames.requestyModels,
)
const fileExists = await fileExistsAtPath(requestyModelsFilePath)
if (fileExists) {
const fileContents = await fs.readFile(requestyModelsFilePath, "utf8")
const fileContents = await fs.readFile(filePath, "utf8")
return JSON.parse(fileContents)
}
return undefined
}
async refreshRequestyModels(apiKey?: string) {
const requestyModelsFilePath = path.join(
await this.ensureCacheDirectoryExists(),
GlobalFileNames.requestyModels,
)
const models: Record<string, ModelInfo> = {}
try {
const config: Record<string, any> = {}
if (!apiKey) {
apiKey = (await this.getSecret("requestyApiKey")) as string
}
if (!apiKey) {
this.outputChannel.appendLine("No Requesty API key found")
return models
}
if (apiKey) {
config["headers"] = { Authorization: `Bearer ${apiKey}` }
}
const response = await axios.get("https://router.requesty.ai/v1/models", config)
/*
{
"id": "anthropic/claude-3-5-sonnet-20240620",
"object": "model",
"created": 1738243330,
"owned_by": "system",
"input_price": 0.000003,
"caching_price": 0.00000375,
"cached_price": 3E-7,
"output_price": 0.000015,
"max_output_tokens": 8192,
"context_window": 200000,
"supports_caching": true,
"description": "Anthropic's most intelligent model. Highest level of intelligence and capability"
},
}
*/
if (response.data) {
const rawModels = response.data.data
const parsePrice = (price: any) => {
if (price) {
return parseFloat(price) * 1_000_000
}
return undefined
}
for (const rawModel of rawModels) {
const modelInfo: ModelInfo = {
maxTokens: rawModel.max_output_tokens,
contextWindow: rawModel.context_window,
supportsImages: rawModel.support_image,
supportsComputerUse: rawModel.support_computer_use,
supportsPromptCache: rawModel.supports_caching,
inputPrice: parsePrice(rawModel.input_price),
outputPrice: parsePrice(rawModel.output_price),
description: rawModel.description,
cacheWritesPrice: parsePrice(rawModel.caching_price),
cacheReadsPrice: parsePrice(rawModel.cached_price),
}
models[rawModel.id] = modelInfo
}
} else {
this.outputChannel.appendLine("Invalid response from Requesty API")
}
await fs.writeFile(requestyModelsFilePath, JSON.stringify(models))
} catch (error) {
this.outputChannel.appendLine(
`Error fetching Requesty models: ${JSON.stringify(error, Object.getOwnPropertyNames(error), 2)}`,
)
}
await this.postMessageToWebview({ type: "requestyModels", requestyModels: models })
return models
}
// OpenRouter
async handleOpenRouterCallback(code: string) {
@ -1986,11 +1831,7 @@ export class ClineProvider implements vscode.WebviewViewProvider {
// await this.postMessageToWebview({ type: "action", action: "settingsButtonClicked" }) // bad ux if user is on welcome
}
private async ensureCacheDirectoryExists(): Promise<string> {
const cacheDir = path.join(this.context.globalStorageUri.fsPath, "cache")
await fs.mkdir(cacheDir, { recursive: true })
return cacheDir
}
// Glama
async handleGlamaCallback(code: string) {
let apiKey: string
@ -2021,246 +1862,6 @@ export class ClineProvider implements vscode.WebviewViewProvider {
// await this.postMessageToWebview({ type: "action", action: "settingsButtonClicked" }) // bad ux if user is on welcome
}
private async readModelsFromCache(filename: string): Promise<Record<string, ModelInfo> | undefined> {
const filePath = path.join(await this.ensureCacheDirectoryExists(), filename)
const fileExists = await fileExistsAtPath(filePath)
if (fileExists) {
const fileContents = await fs.readFile(filePath, "utf8")
return JSON.parse(fileContents)
}
return undefined
}
async readGlamaModels(): Promise<Record<string, ModelInfo> | undefined> {
return this.readModelsFromCache(GlobalFileNames.glamaModels)
}
async refreshGlamaModels() {
const glamaModelsFilePath = path.join(await this.ensureCacheDirectoryExists(), GlobalFileNames.glamaModels)
const models: Record<string, ModelInfo> = {}
try {
const response = await axios.get("https://glama.ai/api/gateway/v1/models")
/*
{
"added": "2024-12-24T15:12:49.324Z",
"capabilities": [
"adjustable_safety_settings",
"caching",
"code_execution",
"function_calling",
"json_mode",
"json_schema",
"system_instructions",
"tuning",
"input:audio",
"input:image",
"input:text",
"input:video",
"output:text"
],
"id": "google-vertex/gemini-1.5-flash-002",
"maxTokensInput": 1048576,
"maxTokensOutput": 8192,
"pricePerToken": {
"cacheRead": null,
"cacheWrite": null,
"input": "0.000000075",
"output": "0.0000003"
}
}
*/
if (response.data) {
const rawModels = response.data
const parsePrice = (price: any) => {
if (price) {
return parseFloat(price) * 1_000_000
}
return undefined
}
for (const rawModel of rawModels) {
const modelInfo: ModelInfo = {
maxTokens: rawModel.maxTokensOutput,
contextWindow: rawModel.maxTokensInput,
supportsImages: rawModel.capabilities?.includes("input:image"),
supportsComputerUse: rawModel.capabilities?.includes("computer_use"),
supportsPromptCache: rawModel.capabilities?.includes("caching"),
inputPrice: parsePrice(rawModel.pricePerToken?.input),
outputPrice: parsePrice(rawModel.pricePerToken?.output),
description: undefined,
cacheWritesPrice: parsePrice(rawModel.pricePerToken?.cacheWrite),
cacheReadsPrice: parsePrice(rawModel.pricePerToken?.cacheRead),
}
models[rawModel.id] = modelInfo
}
} else {
this.outputChannel.appendLine("Invalid response from Glama API")
}
await fs.writeFile(glamaModelsFilePath, JSON.stringify(models))
} catch (error) {
this.outputChannel.appendLine(
`Error fetching Glama models: ${JSON.stringify(error, Object.getOwnPropertyNames(error), 2)}`,
)
}
await this.postMessageToWebview({ type: "glamaModels", glamaModels: models })
return models
}
async readOpenRouterModels(): Promise<Record<string, ModelInfo> | undefined> {
return this.readModelsFromCache(GlobalFileNames.openRouterModels)
}
async refreshOpenRouterModels() {
const openRouterModelsFilePath = path.join(
await this.ensureCacheDirectoryExists(),
GlobalFileNames.openRouterModels,
)
const models: Record<string, ModelInfo> = {}
try {
const response = await axios.get("https://openrouter.ai/api/v1/models")
/*
{
"id": "anthropic/claude-3.5-sonnet",
"name": "Anthropic: Claude 3.5 Sonnet",
"created": 1718841600,
"description": "Claude 3.5 Sonnet delivers better-than-Opus capabilities, faster-than-Sonnet speeds, at the same Sonnet prices. Sonnet is particularly good at:\n\n- Coding: Autonomously writes, edits, and runs code with reasoning and troubleshooting\n- Data science: Augments human data science expertise; navigates unstructured data while using multiple tools for insights\n- Visual processing: excelling at interpreting charts, graphs, and images, accurately transcribing text to derive insights beyond just the text alone\n- Agentic tasks: exceptional tool use, making it great at agentic tasks (i.e. complex, multi-step problem solving tasks that require engaging with other systems)\n\n#multimodal",
"context_length": 200000,
"architecture": {
"modality": "text+image-\u003Etext",
"tokenizer": "Claude",
"instruct_type": null
},
"pricing": {
"prompt": "0.000003",
"completion": "0.000015",
"image": "0.0048",
"request": "0"
},
"top_provider": {
"context_length": 200000,
"max_completion_tokens": 8192,
"is_moderated": true
},
"per_request_limits": null
},
*/
if (response.data?.data) {
const rawModels = response.data.data
const parsePrice = (price: any) => {
if (price) {
return parseFloat(price) * 1_000_000
}
return undefined
}
for (const rawModel of rawModels) {
const modelInfo: ModelInfo = {
maxTokens: rawModel.top_provider?.max_completion_tokens,
contextWindow: rawModel.context_length,
supportsImages: rawModel.architecture?.modality?.includes("image"),
supportsPromptCache: false,
inputPrice: parsePrice(rawModel.pricing?.prompt),
outputPrice: parsePrice(rawModel.pricing?.completion),
description: rawModel.description,
}
switch (rawModel.id) {
case "anthropic/claude-3.5-sonnet":
case "anthropic/claude-3.5-sonnet:beta":
// NOTE: this needs to be synced with api.ts/openrouter default model info
modelInfo.supportsComputerUse = true
modelInfo.supportsPromptCache = true
modelInfo.cacheWritesPrice = 3.75
modelInfo.cacheReadsPrice = 0.3
break
case "anthropic/claude-3.5-sonnet-20240620":
case "anthropic/claude-3.5-sonnet-20240620:beta":
modelInfo.supportsPromptCache = true
modelInfo.cacheWritesPrice = 3.75
modelInfo.cacheReadsPrice = 0.3
break
case "anthropic/claude-3-5-haiku":
case "anthropic/claude-3-5-haiku:beta":
case "anthropic/claude-3-5-haiku-20241022":
case "anthropic/claude-3-5-haiku-20241022:beta":
case "anthropic/claude-3.5-haiku":
case "anthropic/claude-3.5-haiku:beta":
case "anthropic/claude-3.5-haiku-20241022":
case "anthropic/claude-3.5-haiku-20241022:beta":
modelInfo.supportsPromptCache = true
modelInfo.cacheWritesPrice = 1.25
modelInfo.cacheReadsPrice = 0.1
break
case "anthropic/claude-3-opus":
case "anthropic/claude-3-opus:beta":
modelInfo.supportsPromptCache = true
modelInfo.cacheWritesPrice = 18.75
modelInfo.cacheReadsPrice = 1.5
break
case "anthropic/claude-3-haiku":
case "anthropic/claude-3-haiku:beta":
modelInfo.supportsPromptCache = true
modelInfo.cacheWritesPrice = 0.3
modelInfo.cacheReadsPrice = 0.03
break
}
models[rawModel.id] = modelInfo
}
} else {
this.outputChannel.appendLine("Invalid response from OpenRouter API")
}
await fs.writeFile(openRouterModelsFilePath, JSON.stringify(models))
} catch (error) {
this.outputChannel.appendLine(
`Error fetching OpenRouter models: ${JSON.stringify(error, Object.getOwnPropertyNames(error), 2)}`,
)
}
await this.postMessageToWebview({ type: "openRouterModels", openRouterModels: models })
return models
}
async readUnboundModels(): Promise<Record<string, ModelInfo> | undefined> {
return this.readModelsFromCache(GlobalFileNames.unboundModels)
}
async refreshUnboundModels() {
const unboundModelsFilePath = path.join(await this.ensureCacheDirectoryExists(), GlobalFileNames.unboundModels)
const models: Record<string, ModelInfo> = {}
try {
const response = await axios.get("https://api.getunbound.ai/models")
if (response.data) {
const rawModels: Record<string, any> = response.data
for (const [modelId, model] of Object.entries(rawModels)) {
models[modelId] = {
maxTokens: model?.maxTokens ? parseInt(model.maxTokens) : undefined,
contextWindow: model?.contextWindow ? parseInt(model.contextWindow) : 0,
supportsImages: model?.supportsImages ?? false,
supportsPromptCache: model?.supportsPromptCaching ?? false,
supportsComputerUse: model?.supportsComputerUse ?? false,
inputPrice: model?.inputTokenPrice ? parseFloat(model.inputTokenPrice) : undefined,
outputPrice: model?.outputTokenPrice ? parseFloat(model.outputTokenPrice) : undefined,
cacheWritesPrice: model?.cacheWritePrice ? parseFloat(model.cacheWritePrice) : undefined,
cacheReadsPrice: model?.cacheReadPrice ? parseFloat(model.cacheReadPrice) : undefined,
}
}
}
await fs.writeFile(unboundModelsFilePath, JSON.stringify(models))
} catch (error) {
this.outputChannel.appendLine(
`Error fetching Unbound models: ${JSON.stringify(error, Object.getOwnPropertyNames(error), 2)}`,
)
}
await this.postMessageToWebview({ type: "unboundModels", unboundModels: models })
return models
}
// Task history
async getTaskWithId(id: string): Promise<{
@ -2423,6 +2024,8 @@ export class ClineProvider implements vscode.WebviewViewProvider {
const allowedCommands = vscode.workspace.getConfiguration("roo-cline").get<string[]>("allowedCommands") || []
const cwd = vscode.workspace.workspaceFolders?.map((folder) => folder.uri.fsPath).at(0) || ""
return {
version: this.context.extension?.packageJSON?.version ?? "",
apiConfiguration,
@ -2469,6 +2072,7 @@ export class ClineProvider implements vscode.WebviewViewProvider {
experiments: experiments ?? experimentDefault,
mcpServers: this.mcpHub?.getAllServers() ?? [],
maxOpenTabsContext: maxOpenTabsContext ?? 20,
cwd: cwd,
}
}
@ -2551,6 +2155,7 @@ export class ClineProvider implements vscode.WebviewViewProvider {
lmStudioModelId,
lmStudioBaseUrl,
anthropicBaseUrl,
anthropicThinking,
geminiApiKey,
openAiNativeApiKey,
deepSeekApiKey,
@ -2633,6 +2238,7 @@ export class ClineProvider implements vscode.WebviewViewProvider {
this.getGlobalState("lmStudioModelId") as Promise<string | undefined>,
this.getGlobalState("lmStudioBaseUrl") as Promise<string | undefined>,
this.getGlobalState("anthropicBaseUrl") as Promise<string | undefined>,
this.getGlobalState("anthropicThinking") as Promise<number | undefined>,
this.getSecret("geminiApiKey") as Promise<string | undefined>,
this.getSecret("openAiNativeApiKey") as Promise<string | undefined>,
this.getSecret("deepSeekApiKey") as Promise<string | undefined>,
@ -2732,6 +2338,7 @@ export class ClineProvider implements vscode.WebviewViewProvider {
lmStudioModelId,
lmStudioBaseUrl,
anthropicBaseUrl,
anthropicThinking,
geminiApiKey,
openAiNativeApiKey,
deepSeekApiKey,
@ -2844,26 +2451,6 @@ export class ClineProvider implements vscode.WebviewViewProvider {
return await this.context.globalState.get(key)
}
// workspace
private async updateWorkspaceState(key: string, value: any) {
await this.context.workspaceState.update(key, value)
}
private async getWorkspaceState(key: string) {
return await this.context.workspaceState.get(key)
}
// private async clearState() {
// this.context.workspaceState.keys().forEach((key) => {
// this.context.workspaceState.update(key, undefined)
// })
// this.context.globalState.keys().forEach((key) => {
// this.context.globalState.update(key, undefined)
// })
// this.context.secrets.delete("apiKey")
// }
// secrets
public async storeSecret(key: SecretKey, value?: string) {

View file

@ -9,12 +9,41 @@ import { setSoundEnabled } from "../../../utils/sound"
import { defaultModeSlug } from "../../../shared/modes"
import { experimentDefault } from "../../../shared/experiments"
// Mock custom-instructions module
const mockAddCustomInstructions = jest.fn()
// Mock setup must come before imports
jest.mock("../../prompts/sections/custom-instructions")
jest.mock("../../prompts/sections/custom-instructions", () => ({
addCustomInstructions: mockAddCustomInstructions,
}))
// Mock dependencies
jest.mock("vscode")
jest.mock("delay")
jest.mock(
"@modelcontextprotocol/sdk/types.js",
() => ({
CallToolResultSchema: {},
ListResourcesResultSchema: {},
ListResourceTemplatesResultSchema: {},
ListToolsResultSchema: {},
ReadResourceResultSchema: {},
ErrorCode: {
InvalidRequest: "InvalidRequest",
MethodNotFound: "MethodNotFound",
InternalError: "InternalError",
},
McpError: class McpError extends Error {
code: string
constructor(code: string, message: string) {
super(message)
this.code = code
this.name = "McpError"
}
},
}),
{ virtual: true },
)
// Initialize mocks
const mockAddCustomInstructions = jest.fn().mockResolvedValue("Combined instructions")
;(jest.requireMock("../../prompts/sections/custom-instructions") as any).addCustomInstructions =
mockAddCustomInstructions
// Mock delay module
jest.mock("delay", () => {
@ -661,19 +690,18 @@ describe("ClineProvider", () => {
await provider.initClineWithTask("Test task")
// Verify Cline was initialized with mode-specific instructions
expect(Cline).toHaveBeenCalledWith(
expect(Cline).toHaveBeenCalledWith({
provider,
mockApiConfig,
modeCustomInstructions,
true,
false,
1.0,
"Test task",
undefined,
undefined,
experimentDefault,
)
apiConfiguration: mockApiConfig,
customInstructions: modeCustomInstructions,
enableDiff: true,
enableCheckpoints: false,
fuzzyMatchThreshold: 1.0,
task: "Test task",
experiments: experimentDefault,
})
})
test("handles mode-specific custom instructions updates", async () => {
await provider.resolveWebviewView(mockWebviewView)
const messageHandler = (mockWebviewView.webview.onDidReceiveMessage as jest.Mock).mock.calls[0][0]

View file

@ -1,123 +0,0 @@
/*
import * as vscode from "vscode"
import deepEqual from "fast-deep-equal"
type FileDiagnostics = [vscode.Uri, vscode.Diagnostic[]][]
About Diagnostics:
The Problems tab shows diagnostics that have been reported for your project. These diagnostics are categorized into:
Errors: Critical issues that usually prevent your code from compiling or running correctly.
Warnings: Potential problems in the code that may not prevent it from running but could cause issues (e.g., bad practices, unused variables).
Information: Non-critical suggestions or tips (e.g., formatting issues or notes from linters).
The Problems tab displays diagnostics from various sources:
1. Language Servers:
- TypeScript: Type errors, missing imports, syntax issues
- Python: Syntax errors, invalid type hints, undefined variables
- JavaScript/Node.js: Parsing and execution errors
2. Linters:
- ESLint: Code style, best practices, potential bugs
- Pylint: Unused imports, naming conventions
- TSLint: Style and correctness issues in TypeScript
3. Build Tools:
- Webpack: Module resolution failures, build errors
- Gulp: Build errors during task execution
4. Custom Validators:
- Extensions can generate custom diagnostics for specific languages or tools
Each problem typically indicates its source (e.g., language server, linter, build tool).
Diagnostics update in real-time as you edit code, helping identify issues quickly. For example, if you introduce a syntax error in a TypeScript file, the Problems tab will immediately display the new error.
Notes on diagnostics:
- linter diagnostics are only captured for open editors
- this works great for us since when cline edits/creates files its through vscode's textedit api's and we get those diagnostics for free
- some tools might require you to save the file or manually refresh to clear the problem from the list.
System Prompt
- You will automatically receive workspace error diagnostics in environment_details. Be mindful that this may include issues beyond the scope of your task or the user's request. Only address errors relevant to your work, and avoid fixing pre-existing or unrelated issues unless the user specifically instructs you to do so.
- If you are unable to resolve errors provided in environment_details after two attempts, consider using ask_followup_question to ask the user for additional information, such as the latest documentation related to a problematic framework, to help you make progress on the task. If the error remains unresolved after this step, proceed with your task while disregarding the error.
class DiagnosticsMonitor {
private diagnosticsChangeEmitter: vscode.EventEmitter<void> = new vscode.EventEmitter<void>()
private disposables: vscode.Disposable[] = []
private lastDiagnostics: FileDiagnostics = []
constructor() {
this.disposables.push(
vscode.languages.onDidChangeDiagnostics(() => {
this.diagnosticsChangeEmitter.fire()
})
)
}
public async getCurrentDiagnostics(shouldWaitForChanges: boolean): Promise<FileDiagnostics> {
const currentDiagnostics = this.getDiagnostics()
if (!shouldWaitForChanges) {
this.lastDiagnostics = currentDiagnostics
return currentDiagnostics
}
if (!deepEqual(this.lastDiagnostics, currentDiagnostics)) {
this.lastDiagnostics = currentDiagnostics
return currentDiagnostics
}
let timeout = 300 // only way this happens is if theres no errors
// if diagnostics contain existing errors (since the check above didn't trigger) then it's likely cline just did something that should have fixed the error, so we'll give a longer grace period for diagnostics to catch up
const hasErrors = currentDiagnostics.some(([_, diagnostics]) =>
diagnostics.some((d) => d.severity === vscode.DiagnosticSeverity.Error)
)
if (hasErrors) {
console.log("Existing errors detected, extending timeout", currentDiagnostics)
timeout = 10_000
}
return this.waitForUpdatedDiagnostics(timeout)
}
private async waitForUpdatedDiagnostics(timeout: number): Promise<FileDiagnostics> {
return new Promise((resolve, reject) => {
const timer = setTimeout(() => {
cleanup()
const finalDiagnostics = this.getDiagnostics()
this.lastDiagnostics = finalDiagnostics
resolve(finalDiagnostics)
}, timeout)
const disposable = this.diagnosticsChangeEmitter.event(() => {
const updatedDiagnostics = this.getDiagnostics() // I thought this would only trigger when diagnostics changed, but that's not the case.
if (deepEqual(this.lastDiagnostics, updatedDiagnostics)) {
// diagnostics have not changed, ignoring...
return
}
cleanup()
this.lastDiagnostics = updatedDiagnostics
resolve(updatedDiagnostics)
})
const cleanup = () => {
clearTimeout(timer)
disposable.dispose()
}
})
}
private getDiagnostics(): FileDiagnostics {
const allDiagnostics = vscode.languages.getDiagnostics()
return allDiagnostics
.filter(([_, diagnostics]) => diagnostics.some((d) => d.severity === vscode.DiagnosticSeverity.Error))
.map(([uri, diagnostics]) => [
uri,
diagnostics.filter((d) => d.severity === vscode.DiagnosticSeverity.Error),
])
}
public dispose() {
this.disposables.forEach((d) => d.dispose())
this.disposables = []
this.diagnosticsChangeEmitter.dispose()
}
}
export default DiagnosticsMonitor
*/

View file

@ -41,14 +41,7 @@ export async function downloadTask(dateTs: number, conversationHistory: Anthropi
}
}
export function formatContentBlockToMarkdown(
block:
| Anthropic.TextBlockParam
| Anthropic.ImageBlockParam
| Anthropic.ToolUseBlockParam
| Anthropic.ToolResultBlockParam,
// messages: Anthropic.MessageParam[]
): string {
export function formatContentBlockToMarkdown(block: Anthropic.Messages.ContentBlockParam): string {
switch (block.type) {
case "text":
return block.text

View file

@ -1,42 +0,0 @@
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 = vscode.workspace.workspaceFolders?.[0]
if (!workspaceFolder) {
return undefined
}
// Get the active python environment path for the current workspace
const pythonEnv = await pythonApi?.environments?.getActiveEnvironmentPath(workspaceFolder.uri)
if (pythonEnv && pythonEnv.path) {
return pythonEnv.path
} else {
return undefined
}
}

View file

@ -9,6 +9,8 @@ import { simpleGit, SimpleGit } from "simple-git"
import { CheckpointServiceFactory } from "../CheckpointServiceFactory"
import { LocalCheckpointService } from "../LocalCheckpointService"
const tmpDir = path.join(os.tmpdir(), "test-LocalCheckpointService")
describe("LocalCheckpointService", () => {
const taskId = "test-task"
@ -29,7 +31,7 @@ describe("LocalCheckpointService", () => {
textFileContent?: string
}) => {
// Create a temporary directory for testing.
await fs.mkdir(workspaceDir)
await fs.mkdir(workspaceDir, { recursive: true })
// Initialize git repo.
const git = simpleGit(workspaceDir)
@ -49,7 +51,7 @@ describe("LocalCheckpointService", () => {
}
beforeEach(async () => {
const workspaceDir = path.join(os.tmpdir(), `checkpoint-service-test-${Date.now()}`)
const workspaceDir = path.join(tmpDir, `checkpoint-service-test-${Date.now()}`)
const repo = await initRepo({ workspaceDir })
testFile = repo.testFile
@ -60,10 +62,13 @@ describe("LocalCheckpointService", () => {
})
afterEach(async () => {
await fs.rm(service.workspaceDir, { recursive: true, force: true })
jest.restoreAllMocks()
})
afterAll(async () => {
await fs.rm(tmpDir, { recursive: true, force: true })
})
describe("getDiff", () => {
it("returns the correct diff between commits", async () => {
await fs.writeFile(testFile, "Ahoy, world!")
@ -316,7 +321,7 @@ describe("LocalCheckpointService", () => {
describe("create", () => {
it("initializes a git repository if one does not already exist", async () => {
const workspaceDir = path.join(os.tmpdir(), `checkpoint-service-test2-${Date.now()}`)
const workspaceDir = path.join(tmpDir, `checkpoint-service-test2-${Date.now()}`)
await fs.mkdir(workspaceDir)
const newTestFile = path.join(workspaceDir, "test.txt")
await fs.writeFile(newTestFile, "Hello, world!")
@ -364,7 +369,7 @@ describe("LocalCheckpointService", () => {
})
it("respects existing git user configuration", async () => {
const workspaceDir = path.join(os.tmpdir(), `checkpoint-service-test-config2-${Date.now()}`)
const workspaceDir = path.join(tmpDir, `checkpoint-service-test-config2-${Date.now()}`)
const userName = "Custom User"
const userEmail = "custom@example.com"
await initRepo({ workspaceDir, userName, userEmail })

View file

@ -13,11 +13,12 @@ jest.mock("globby", () => ({
globby: jest.fn().mockResolvedValue([]),
}))
const tmpDir = path.join(os.tmpdir(), "test-ShadowCheckpointService")
describe("ShadowCheckpointService", () => {
const taskId = "test-task"
let workspaceGit: SimpleGit
let shadowGit: SimpleGit
let testFile: string
let service: ShadowCheckpointService
@ -35,7 +36,7 @@ describe("ShadowCheckpointService", () => {
textFileContent?: string
}) => {
// Create a temporary directory for testing.
await fs.mkdir(workspaceDir)
await fs.mkdir(workspaceDir, { recursive: true })
// Initialize git repo.
const git = simpleGit(workspaceDir)
@ -57,8 +58,8 @@ describe("ShadowCheckpointService", () => {
beforeEach(async () => {
jest.mocked(require("globby").globby).mockClear().mockResolvedValue([])
const shadowDir = path.join(os.tmpdir(), `shadow-${Date.now()}`)
const workspaceDir = path.join(os.tmpdir(), `workspace-${Date.now()}`)
const shadowDir = path.join(tmpDir, `shadow-${Date.now()}`)
const workspaceDir = path.join(tmpDir, `workspace-${Date.now()}`)
const repo = await initRepo({ workspaceDir })
testFile = repo.testFile
@ -69,15 +70,16 @@ describe("ShadowCheckpointService", () => {
})
workspaceGit = repo.git
shadowGit = service.git
})
afterEach(async () => {
await fs.rm(service.shadowDir, { recursive: true, force: true })
await fs.rm(service.workspaceDir, { recursive: true, force: true })
jest.restoreAllMocks()
})
afterAll(async () => {
await fs.rm(tmpDir, { recursive: true, force: true })
})
describe("getDiff", () => {
it("returns the correct diff between commits", async () => {
await fs.writeFile(testFile, "Ahoy, world!")
@ -299,8 +301,8 @@ describe("ShadowCheckpointService", () => {
describe("create", () => {
it("initializes a git repository if one does not already exist", async () => {
const shadowDir = path.join(os.tmpdir(), `shadow2-${Date.now()}`)
const workspaceDir = path.join(os.tmpdir(), `workspace2-${Date.now()}`)
const shadowDir = path.join(tmpDir, `shadow2-${Date.now()}`)
const workspaceDir = path.join(tmpDir, `workspace2-${Date.now()}`)
await fs.mkdir(workspaceDir)
const newTestFile = path.join(workspaceDir, "test.txt")

View file

@ -14,7 +14,9 @@ import * as fs from "fs/promises"
import * as path from "path"
import * as vscode from "vscode"
import { z } from "zod"
import { ClineProvider, GlobalFileNames } from "../../core/webview/ClineProvider"
import { ClineProvider } from "../../core/webview/ClineProvider"
import { GlobalFileNames } from "../../shared/globalFileNames"
import {
McpResource,
McpResourceResponse,

View file

@ -27,10 +27,11 @@ export interface ExtensionMessage {
| "workspaceUpdated"
| "invoke"
| "partialMessage"
| "glamaModels"
| "openRouterModels"
| "openAiModels"
| "glamaModels"
| "unboundModels"
| "requestyModels"
| "openAiModels"
| "mcpServers"
| "enhancedPrompt"
| "commitSearchResults"
@ -43,8 +44,6 @@ export interface ExtensionMessage {
| "autoApprovalEnabled"
| "updateCustomMode"
| "deleteCustomMode"
| "unboundModels"
| "refreshUnboundModels"
| "currentCheckpointUpdated"
text?: string
action?:
@ -67,11 +66,11 @@ export interface ExtensionMessage {
path?: string
}>
partialMessage?: ClineMessage
glamaModels?: Record<string, ModelInfo>
requestyModels?: Record<string, ModelInfo>
openRouterModels?: Record<string, ModelInfo>
openAiModels?: string[]
glamaModels?: Record<string, ModelInfo>
unboundModels?: Record<string, ModelInfo>
requestyModels?: Record<string, ModelInfo>
openAiModels?: string[]
mcpServers?: McpServer[]
commits?: GitCommit[]
listApiConfig?: ApiConfigMeta[]
@ -129,6 +128,7 @@ export interface ExtensionState {
customModes: ModeConfig[]
toolRequirements?: Record<string, boolean> // Map of tool names to their requirements (e.g. {"apply_diff": true} if diffEnabled)
maxOpenTabsContext: number // Maximum number of VSCode open tabs to include in context (0-500)
cwd?: string // Current working directory
}
export interface ClineMessage {

View file

@ -40,11 +40,11 @@ export interface WebviewMessage {
| "openFile"
| "openMention"
| "cancelTask"
| "refreshGlamaModels"
| "refreshOpenRouterModels"
| "refreshOpenAiModels"
| "refreshGlamaModels"
| "refreshUnboundModels"
| "refreshRequestyModels"
| "refreshOpenAiModels"
| "alwaysAllowBrowser"
| "alwaysAllowMcp"
| "alwaysAllowModeSwitch"
@ -71,7 +71,6 @@ export interface WebviewMessage {
| "mcpEnabled"
| "enableMcpServerCreation"
| "searchCommits"
| "refreshGlamaModels"
| "alwaysApproveResubmit"
| "requestDelaySeconds"
| "rateLimitSeconds"

View file

@ -32,6 +32,7 @@ describe("checkExistKey", () => {
apiKey: "test-key",
apiProvider: undefined,
anthropicBaseUrl: undefined,
anthropicThinking: undefined,
}
expect(checkExistKey(config)).toBe(true)
})

View file

@ -0,0 +1,47 @@
import { EXPERIMENT_IDS, experimentConfigsMap, experiments as Experiments, ExperimentId } from "../experiments"
describe("experiments", () => {
describe("POWER_STEERING", () => {
it("is configured correctly", () => {
expect(EXPERIMENT_IDS.POWER_STEERING).toBe("powerSteering")
expect(experimentConfigsMap.POWER_STEERING).toMatchObject({
name: 'Use experimental "power steering" mode',
description:
"When enabled, Roo will remind the model about the details of its current mode definition more frequently. This will lead to stronger adherence to role definitions and custom instructions, but will use more tokens per message.",
enabled: false,
})
})
})
describe("isEnabled", () => {
it("returns false when experiment is not enabled", () => {
const experiments: Record<ExperimentId, boolean> = {
powerSteering: false,
experimentalDiffStrategy: false,
search_and_replace: false,
insert_content: false,
}
expect(Experiments.isEnabled(experiments, EXPERIMENT_IDS.POWER_STEERING)).toBe(false)
})
it("returns true when experiment is enabled", () => {
const experiments: Record<ExperimentId, boolean> = {
powerSteering: true,
experimentalDiffStrategy: false,
search_and_replace: false,
insert_content: false,
}
expect(Experiments.isEnabled(experiments, EXPERIMENT_IDS.POWER_STEERING)).toBe(true)
})
it("returns false when experiment is not present", () => {
const experiments: Record<ExperimentId, boolean> = {
experimentalDiffStrategy: false,
search_and_replace: false,
insert_content: false,
powerSteering: false,
}
expect(Experiments.isEnabled(experiments, EXPERIMENT_IDS.POWER_STEERING)).toBe(false)
})
})
})

View file

@ -1,4 +1,13 @@
import { isToolAllowedForMode, FileRestrictionError, ModeConfig } from "../modes"
// Mock setup must come before imports
jest.mock("vscode")
const mockAddCustomInstructions = jest.fn().mockResolvedValue("Combined instructions")
jest.mock("../../core/prompts/sections/custom-instructions", () => ({
addCustomInstructions: mockAddCustomInstructions,
}))
import { isToolAllowedForMode, FileRestrictionError, ModeConfig, getFullModeDetails, modes } from "../modes"
import * as vscode from "vscode"
import { addCustomInstructions } from "../../core/prompts/sections/custom-instructions"
describe("isToolAllowedForMode", () => {
const customModes: ModeConfig[] = [
@ -324,6 +333,98 @@ describe("FileRestrictionError", () => {
expect(error.name).toBe("FileRestrictionError")
})
describe("debug mode", () => {
it("is configured correctly", () => {
const debugMode = modes.find((mode) => mode.slug === "debug")
expect(debugMode).toBeDefined()
expect(debugMode).toMatchObject({
slug: "debug",
name: "Debug",
roleDefinition:
"You are Roo, an expert software debugger specializing in systematic problem diagnosis and resolution.",
groups: ["read", "edit", "browser", "command", "mcp"],
})
expect(debugMode?.customInstructions).toContain(
"Reflect on 5-7 different possible sources of the problem, distill those down to 1-2 most likely sources, and then add logs to validate your assumptions. Explicitly ask the user to confirm the diagnosis before fixing the problem.",
)
})
})
describe("getFullModeDetails", () => {
beforeEach(() => {
jest.clearAllMocks()
;(addCustomInstructions as jest.Mock).mockResolvedValue("Combined instructions")
})
it("returns base mode when no overrides exist", async () => {
const result = await getFullModeDetails("debug")
expect(result).toMatchObject({
slug: "debug",
name: "Debug",
roleDefinition:
"You are Roo, an expert software debugger specializing in systematic problem diagnosis and resolution.",
})
})
it("applies custom mode overrides", async () => {
const customModes = [
{
slug: "debug",
name: "Custom Debug",
roleDefinition: "Custom debug role",
groups: ["read"],
},
]
const result = await getFullModeDetails("debug", customModes)
expect(result).toMatchObject({
slug: "debug",
name: "Custom Debug",
roleDefinition: "Custom debug role",
groups: ["read"],
})
})
it("applies prompt component overrides", async () => {
const customModePrompts = {
debug: {
roleDefinition: "Overridden role",
customInstructions: "Overridden instructions",
},
}
const result = await getFullModeDetails("debug", undefined, customModePrompts)
expect(result.roleDefinition).toBe("Overridden role")
expect(result.customInstructions).toBe("Overridden instructions")
})
it("combines custom instructions when cwd provided", async () => {
const options = {
cwd: "/test/path",
globalCustomInstructions: "Global instructions",
preferredLanguage: "en",
}
await getFullModeDetails("debug", undefined, undefined, options)
expect(addCustomInstructions).toHaveBeenCalledWith(
expect.any(String),
"Global instructions",
"/test/path",
"debug",
{ preferredLanguage: "en" },
)
})
it("falls back to first mode for non-existent mode", async () => {
const result = await getFullModeDetails("non-existent")
expect(result).toMatchObject({
...modes[0],
customInstructions: "",
})
})
})
it("formats error message with description when provided", () => {
const error = new FileRestrictionError("Markdown Editor", "\\.md$", "Markdown files only", "test.js")
expect(error.message).toBe(

View file

@ -21,6 +21,7 @@ export interface ApiHandlerOptions {
apiModelId?: string
apiKey?: string // anthropic
anthropicBaseUrl?: string
anthropicThinking?: number
vsCodeLmModelSelector?: vscode.LanguageModelChatSelector
glamaModelId?: string
glamaModelInfo?: ModelInfo
@ -88,13 +89,44 @@ export interface ModelInfo {
cacheReadsPrice?: number
description?: string
reasoningEffort?: "low" | "medium" | "high"
thinking?: boolean
}
export const THINKING_BUDGET = {
step: 1024,
min: 1024,
default: 8 * 1024,
}
// Anthropic
// https://docs.anthropic.com/en/docs/about-claude/models
export type AnthropicModelId = keyof typeof anthropicModels
export const anthropicDefaultModelId: AnthropicModelId = "claude-3-5-sonnet-20241022"
export const anthropicDefaultModelId: AnthropicModelId = "claude-3-7-sonnet-20250219"
export const anthropicModels = {
"claude-3-7-sonnet-20250219:thinking": {
maxTokens: 16384,
contextWindow: 200_000,
supportsImages: true,
supportsComputerUse: true,
supportsPromptCache: true,
inputPrice: 3.0, // $3 per million input tokens
outputPrice: 15.0, // $15 per million output tokens
cacheWritesPrice: 3.75, // $3.75 per million tokens
cacheReadsPrice: 0.3, // $0.30 per million tokens
thinking: true,
},
"claude-3-7-sonnet-20250219": {
maxTokens: 16384,
contextWindow: 200_000,
supportsImages: true,
supportsComputerUse: true,
supportsPromptCache: true,
inputPrice: 3.0, // $3 per million input tokens
outputPrice: 15.0, // $15 per million output tokens
cacheWritesPrice: 3.75, // $3.75 per million tokens
cacheReadsPrice: 0.3, // $0.30 per million tokens
thinking: false,
},
"claude-3-5-sonnet-20241022": {
maxTokens: 8192,
contextWindow: 200_000,
@ -162,7 +194,7 @@ export interface MessageContent {
}
export type BedrockModelId = keyof typeof bedrockModels
export const bedrockDefaultModelId: BedrockModelId = "anthropic.claude-3-5-sonnet-20241022-v2:0"
export const bedrockDefaultModelId: BedrockModelId = "anthropic.claude-3-7-sonnet-20250219-v1:0"
export const bedrockModels = {
"amazon.nova-pro-v1:0": {
maxTokens: 5000,
@ -197,6 +229,17 @@ export const bedrockModels = {
cacheWritesPrice: 0.035, // per million tokens
cacheReadsPrice: 0.00875, // per million tokens
},
"anthropic.claude-3-7-sonnet-20250219-v1:0": {
maxTokens: 8192,
contextWindow: 200_000,
supportsImages: true,
supportsComputerUse: true,
supportsPromptCache: true,
inputPrice: 3.0,
outputPrice: 15.0,
cacheWritesPrice: 3.75,
cacheReadsPrice: 0.3,
},
"anthropic.claude-3-5-sonnet-20241022-v2:0": {
maxTokens: 8192,
contextWindow: 200_000,
@ -205,8 +248,8 @@ export const bedrockModels = {
supportsPromptCache: false,
inputPrice: 3.0,
outputPrice: 15.0,
cacheWritesPrice: 3.75, // per million tokens
cacheReadsPrice: 0.3, // per million tokens
cacheWritesPrice: 3.75,
cacheReadsPrice: 0.3,
},
"anthropic.claude-3-5-haiku-20241022-v1:0": {
maxTokens: 8192,
@ -344,7 +387,7 @@ export const bedrockModels = {
// Glama
// https://glama.ai/models
export const glamaDefaultModelId = "anthropic/claude-3-5-sonnet"
export const glamaDefaultModelId = "anthropic/claude-3-7-sonnet"
export const glamaDefaultModelInfo: ModelInfo = {
maxTokens: 8192,
contextWindow: 200_000,
@ -356,9 +399,12 @@ export const glamaDefaultModelInfo: ModelInfo = {
cacheWritesPrice: 3.75,
cacheReadsPrice: 0.3,
description:
"The new Claude 3.5 Sonnet delivers better-than-Opus capabilities, faster-than-Sonnet speeds, at the same Sonnet prices. Sonnet is particularly good at:\n\n- Coding: New Sonnet scores ~49% on SWE-Bench Verified, higher than the last best score, and without any fancy prompt scaffolding\n- Data science: Augments human data science expertise; navigates unstructured data while using multiple tools for insights\n- Visual processing: excelling at interpreting charts, graphs, and images, accurately transcribing text to derive insights beyond just the text alone\n- Agentic tasks: exceptional tool use, making it great at agentic tasks (i.e. complex, multi-step problem solving tasks that require engaging with other systems)\n\n#multimodal\n\n_This is a faster endpoint, made available in collaboration with Anthropic, that is self-moderated: response moderation happens on the provider's side instead of OpenRouter's. For requests that pass moderation, it's identical to the [Standard](/anthropic/claude-3.5-sonnet) variant._",
"Claude 3.7 Sonnet is an advanced large language model with improved reasoning, coding, and problem-solving capabilities. It introduces a hybrid reasoning approach, allowing users to choose between rapid responses and extended, step-by-step processing for complex tasks. The model demonstrates notable improvements in coding, particularly in front-end development and full-stack updates, and excels in agentic workflows, where it can autonomously navigate multi-step processes. Claude 3.7 Sonnet maintains performance parity with its predecessor in standard mode while offering an extended reasoning mode for enhanced accuracy in math, coding, and instruction-following tasks. Read more at the [blog post here](https://www.anthropic.com/news/claude-3-7-sonnet)",
}
// Requesty
// https://requesty.ai/router-2
export const requestyDefaultModelId = "anthropic/claude-3-7-sonnet-latest"
export const requestyDefaultModelInfo: ModelInfo = {
maxTokens: 8192,
contextWindow: 200_000,
@ -370,13 +416,12 @@ export const requestyDefaultModelInfo: ModelInfo = {
cacheWritesPrice: 3.75,
cacheReadsPrice: 0.3,
description:
"The new Claude 3.5 Sonnet delivers better-than-Opus capabilities, faster-than-Sonnet speeds, at the same Sonnet prices. Sonnet is particularly good at:\n\n- Coding: New Sonnet scores ~49% on SWE-Bench Verified, higher than the last best score, and without any fancy prompt scaffolding\n- Data science: Augments human data science expertise; navigates unstructured data while using multiple tools for insights\n- Visual processing: excelling at interpreting charts, graphs, and images, accurately transcribing text to derive insights beyond just the text alone\n- Agentic tasks: exceptional tool use, making it great at agentic tasks (i.e. complex, multi-step problem solving tasks that require engaging with other systems)\n\n#multimodal\n\n_This is a faster endpoint, made available in collaboration with Anthropic, that is self-moderated: response moderation happens on the provider's side instead of OpenRouter's. For requests that pass moderation, it's identical to the [Standard](/anthropic/claude-3.5-sonnet) variant._",
"Claude 3.7 Sonnet is an advanced large language model with improved reasoning, coding, and problem-solving capabilities. It introduces a hybrid reasoning approach, allowing users to choose between rapid responses and extended, step-by-step processing for complex tasks. The model demonstrates notable improvements in coding, particularly in front-end development and full-stack updates, and excels in agentic workflows, where it can autonomously navigate multi-step processes. Claude 3.7 Sonnet maintains performance parity with its predecessor in standard mode while offering an extended reasoning mode for enhanced accuracy in math, coding, and instruction-following tasks. Read more at the [blog post here](https://www.anthropic.com/news/claude-3-7-sonnet)",
}
export const requestyDefaultModelId = "anthropic/claude-3-5-sonnet"
// OpenRouter
// https://openrouter.ai/models?order=newest&supported_parameters=tools
export const openRouterDefaultModelId = "anthropic/claude-3.5-sonnet:beta" // will always exist in openRouterModels
export const openRouterDefaultModelId = "anthropic/claude-3.7-sonnet"
export const openRouterDefaultModelInfo: ModelInfo = {
maxTokens: 8192,
contextWindow: 200_000,
@ -388,14 +433,23 @@ export const openRouterDefaultModelInfo: ModelInfo = {
cacheWritesPrice: 3.75,
cacheReadsPrice: 0.3,
description:
"The new Claude 3.5 Sonnet delivers better-than-Opus capabilities, faster-than-Sonnet speeds, at the same Sonnet prices. Sonnet is particularly good at:\n\n- Coding: New Sonnet scores ~49% on SWE-Bench Verified, higher than the last best score, and without any fancy prompt scaffolding\n- Data science: Augments human data science expertise; navigates unstructured data while using multiple tools for insights\n- Visual processing: excelling at interpreting charts, graphs, and images, accurately transcribing text to derive insights beyond just the text alone\n- Agentic tasks: exceptional tool use, making it great at agentic tasks (i.e. complex, multi-step problem solving tasks that require engaging with other systems)\n\n#multimodal\n\n_This is a faster endpoint, made available in collaboration with Anthropic, that is self-moderated: response moderation happens on the provider's side instead of OpenRouter's. For requests that pass moderation, it's identical to the [Standard](/anthropic/claude-3.5-sonnet) variant._",
"Claude 3.7 Sonnet is an advanced large language model with improved reasoning, coding, and problem-solving capabilities. It introduces a hybrid reasoning approach, allowing users to choose between rapid responses and extended, step-by-step processing for complex tasks. The model demonstrates notable improvements in coding, particularly in front-end development and full-stack updates, and excels in agentic workflows, where it can autonomously navigate multi-step processes. Claude 3.7 Sonnet maintains performance parity with its predecessor in standard mode while offering an extended reasoning mode for enhanced accuracy in math, coding, and instruction-following tasks. Read more at the [blog post here](https://www.anthropic.com/news/claude-3-7-sonnet)",
}
// Vertex AI
// https://cloud.google.com/vertex-ai/generative-ai/docs/partner-models/use-claude
export type VertexModelId = keyof typeof vertexModels
export const vertexDefaultModelId: VertexModelId = "claude-3-5-sonnet-v2@20241022"
export const vertexDefaultModelId: VertexModelId = "claude-3-7-sonnet@20250219"
export const vertexModels = {
"claude-3-7-sonnet@20250219": {
maxTokens: 8192,
contextWindow: 200_000,
supportsImages: true,
supportsComputerUse: true,
supportsPromptCache: false,
inputPrice: 3.0,
outputPrice: 15.0,
},
"claude-3-5-sonnet-v2@20241022": {
maxTokens: 8192,
contextWindow: 200_000,

View file

@ -2,6 +2,7 @@ export const EXPERIMENT_IDS = {
DIFF_STRATEGY: "experimentalDiffStrategy",
SEARCH_AND_REPLACE: "search_and_replace",
INSERT_BLOCK: "insert_content",
POWER_STEERING: "powerSteering",
} as const
export type ExperimentKey = keyof typeof EXPERIMENT_IDS
@ -35,6 +36,12 @@ export const experimentConfigsMap: Record<ExperimentKey, ExperimentConfig> = {
"Enable the experimental insert content tool, allowing Roo to insert content at specific line numbers without needing to create a diff.",
enabled: false,
},
POWER_STEERING: {
name: 'Use experimental "power steering" mode',
description:
"When enabled, Roo will remind the model about the details of its current mode definition more frequently. This will lead to stronger adherence to role definitions and custom instructions, but will use more tokens per message.",
enabled: false,
},
}
export const experimentDefault = Object.fromEntries(

View file

@ -0,0 +1,9 @@
export const GlobalFileNames = {
apiConversationHistory: "api_conversation_history.json",
uiMessages: "ui_messages.json",
glamaModels: "glama_models.json",
openRouterModels: "openrouter_models.json",
requestyModels: "requesty_models.json",
mcpSettings: "cline_mcp_settings.json",
unboundModels: "unbound_models.json",
}

85
src/shared/globalState.ts Normal file
View file

@ -0,0 +1,85 @@
export type SecretKey =
| "apiKey"
| "glamaApiKey"
| "openRouterApiKey"
| "awsAccessKey"
| "awsSecretKey"
| "awsSessionToken"
| "openAiApiKey"
| "geminiApiKey"
| "openAiNativeApiKey"
| "deepSeekApiKey"
| "mistralApiKey"
| "unboundApiKey"
| "requestyApiKey"
export type GlobalStateKey =
| "apiProvider"
| "apiModelId"
| "glamaModelId"
| "glamaModelInfo"
| "awsRegion"
| "awsUseCrossRegionInference"
| "awsProfile"
| "awsUseProfile"
| "vertexProjectId"
| "vertexRegion"
| "lastShownAnnouncementId"
| "customInstructions"
| "alwaysAllowReadOnly"
| "alwaysAllowWrite"
| "alwaysAllowExecute"
| "alwaysAllowBrowser"
| "alwaysAllowMcp"
| "alwaysAllowModeSwitch"
| "taskHistory"
| "openAiBaseUrl"
| "openAiModelId"
| "openAiCustomModelInfo"
| "openAiUseAzure"
| "ollamaModelId"
| "ollamaBaseUrl"
| "lmStudioModelId"
| "lmStudioBaseUrl"
| "anthropicBaseUrl"
| "anthropicThinking"
| "azureApiVersion"
| "openAiStreamingEnabled"
| "openRouterModelId"
| "openRouterModelInfo"
| "openRouterBaseUrl"
| "openRouterUseMiddleOutTransform"
| "allowedCommands"
| "soundEnabled"
| "soundVolume"
| "diffEnabled"
| "checkpointsEnabled"
| "browserViewportSize"
| "screenshotQuality"
| "fuzzyMatchThreshold"
| "preferredLanguage" // Language setting for Cline's communication
| "writeDelayMs"
| "terminalOutputLineLimit"
| "mcpEnabled"
| "enableMcpServerCreation"
| "alwaysApproveResubmit"
| "requestDelaySeconds"
| "rateLimitSeconds"
| "currentApiConfigName"
| "listApiConfigMeta"
| "vsCodeLmModelSelector"
| "mode"
| "modeApiConfigs"
| "customModePrompts"
| "customSupportPrompts"
| "enhancementApiConfigId"
| "experiments" // Map of experiment IDs to their enabled state
| "autoApprovalEnabled"
| "customModes" // Array of custom modes
| "unboundModelId"
| "requestyModelId"
| "requestyModelInfo"
| "unboundModelInfo"
| "modelTemperature"
| "mistralCodestralUrl"
| "maxOpenTabsContext"

View file

@ -1,5 +1,6 @@
import * as vscode from "vscode"
import { TOOL_GROUPS, ToolGroup, ALWAYS_AVAILABLE_TOOLS } from "./tool-groups"
import { addCustomInstructions } from "../core/prompts/sections/custom-instructions"
// Mode types
export type Mode = string
@ -98,6 +99,15 @@ export const modes: readonly ModeConfig[] = [
customInstructions:
"You can analyze code, explain concepts, and access external resources. Make sure to answer the user's questions and don't rush to switch to implementing code.",
},
{
slug: "debug",
name: "Debug",
roleDefinition:
"You are Roo, an expert software debugger specializing in systematic problem diagnosis and resolution.",
groups: ["read", "edit", "browser", "command", "mcp"],
customInstructions:
"Reflect on 5-7 different possible sources of the problem, distill those down to 1-2 most likely sources, and then add logs to validate your assumptions. Explicitly ask the user to confirm the diagnosis before fixing the problem.",
},
] as const
// Export the default mode slug
@ -253,6 +263,46 @@ export async function getAllModesWithPrompts(context: vscode.ExtensionContext):
}))
}
// Helper function to get complete mode details with all overrides
export async function getFullModeDetails(
modeSlug: string,
customModes?: ModeConfig[],
customModePrompts?: CustomModePrompts,
options?: {
cwd?: string
globalCustomInstructions?: string
preferredLanguage?: string
},
): Promise<ModeConfig> {
// First get the base mode config from custom modes or built-in modes
const baseMode = getModeBySlug(modeSlug, customModes) || modes.find((m) => m.slug === modeSlug) || modes[0]
// Check for any prompt component overrides
const promptComponent = customModePrompts?.[modeSlug]
// Get the base custom instructions
const baseCustomInstructions = promptComponent?.customInstructions || baseMode.customInstructions || ""
// If we have cwd, load and combine all custom instructions
let fullCustomInstructions = baseCustomInstructions
if (options?.cwd) {
fullCustomInstructions = await addCustomInstructions(
baseCustomInstructions,
options.globalCustomInstructions || "",
options.cwd,
modeSlug,
{ preferredLanguage: options.preferredLanguage },
)
}
// Return mode with any overrides applied
return {
...baseMode,
roleDefinition: promptComponent?.roleDefinition || baseMode.roleDefinition,
customInstructions: fullCustomInstructions,
}
}
// Helper function to safely get role definition
export function getRoleDefinition(modeSlug: string, customModes?: ModeConfig[]): string {
const mode = getModeBySlug(modeSlug, customModes)

View file

@ -28,7 +28,7 @@ export const TOOL_GROUPS: Record<string, ToolGroupConfig> = {
tools: ["read_file", "search_files", "list_files", "list_code_definition_names"],
},
edit: {
tools: ["write_to_file", "apply_diff", "insert_content", "search_and_replace"],
tools: ["apply_diff", "write_to_file", "insert_content", "search_and_replace"],
},
browser: {
tools: ["browser_action"],

View file

@ -13,23 +13,23 @@ declare global {
}
export async function run(): Promise<void> {
// Create the mocha test
const mocha = new Mocha({
ui: "tdd",
timeout: 600000, // 10 minutes to compensate for time communicating with LLM while running in GHA
timeout: 600000, // 10 minutes to compensate for time communicating with LLM while running in GHA.
})
const testsRoot = path.resolve(__dirname, "..")
try {
// Find all test files
// Find all test files.
const files = await glob("**/**.test.js", { cwd: testsRoot })
// Add files to the test suite
// Add files to the test suite.
files.forEach((f: string) => mocha.addFile(path.resolve(testsRoot, f)))
//Set up global extension, api, provider, and panel
// Set up global extension, api, provider, and panel.
globalThis.extension = vscode.extensions.getExtension("RooVeterinaryInc.roo-cline")
if (!globalThis.extension) {
throw new Error("Extension not found")
}
@ -37,9 +37,12 @@ export async function run(): Promise<void> {
globalThis.api = globalThis.extension.isActive
? globalThis.extension.exports
: await globalThis.extension.activate()
globalThis.provider = globalThis.api.sidebarProvider
await globalThis.provider.updateGlobalState("apiProvider", "openrouter")
await globalThis.provider.updateGlobalState("openRouterModelId", "anthropic/claude-3.5-sonnet")
await globalThis.provider.storeSecret(
"openRouterApiKey",
process.env.OPENROUTER_API_KEY || "sk-or-v1-fake-api-key",
@ -71,7 +74,7 @@ export async function run(): Promise<void> {
await new Promise((resolve) => setTimeout(resolve, interval))
}
// Run the mocha test
// Run the mocha test.
return new Promise((resolve, reject) => {
try {
mocha.run((failures: number) => {

View file

@ -1,101 +1,105 @@
import * as assert from "assert"
import * as vscode from "vscode"
suite("Roo Code Modes", () => {
test("Should handle switching modes correctly", async function () {
const timeout = 30000
const interval = 1000
const testPrompt =
"For each mode (Code, Architect, Ask) respond with the mode name and what it specializes in after switching to that mode, do not start with the current mode, be sure to say 'I AM DONE' after the task is complete"
if (!globalThis.extension) {
assert.fail("Extension not found")
}
try {
let startTime = Date.now()
let startTime = Date.now()
// Ensure the webview is launched.
while (Date.now() - startTime < timeout) {
if (globalThis.provider.viewLaunched) {
break
}
await new Promise((resolve) => setTimeout(resolve, interval))
// Ensure the webview is launched.
while (Date.now() - startTime < timeout) {
if (globalThis.provider.viewLaunched) {
break
}
await globalThis.provider.updateGlobalState("mode", "Ask")
await globalThis.provider.updateGlobalState("alwaysAllowModeSwitch", true)
await globalThis.provider.updateGlobalState("autoApprovalEnabled", true)
// Start a new task.
await globalThis.api.startNewTask(testPrompt)
// Wait for task to appear in history with tokens.
startTime = Date.now()
while (Date.now() - startTime < timeout) {
const messages = globalThis.provider.messages
if (
messages.some(
({ type, text }) =>
type === "say" && text?.includes("I AM DONE") && !text?.includes("be sure to say"),
)
) {
break
}
await new Promise((resolve) => setTimeout(resolve, interval))
}
if (globalThis.provider.messages.length === 0) {
assert.fail("No messages received")
}
//Log the messages to the console
globalThis.provider.messages.forEach(({ type, text }) => {
if (type === "say") {
console.log(text)
}
})
//Start Grading Portion of test to grade the response from 1 to 10
await globalThis.provider.updateGlobalState("mode", "Ask")
let output = globalThis.provider.messages.map(({ type, text }) => (type === "say" ? text : "")).join("\n")
await globalThis.api.startNewTask(
`Given this prompt: ${testPrompt} grade the response from 1 to 10 in the format of "Grade: (1-10)": ${output} \n Be sure to say 'I AM DONE GRADING' after the task is complete`,
)
startTime = Date.now()
while (Date.now() - startTime < timeout) {
const messages = globalThis.provider.messages
if (
messages.some(
({ type, text }) =>
type === "say" && text?.includes("I AM DONE GRADING") && !text?.includes("be sure to say"),
)
) {
break
}
await new Promise((resolve) => setTimeout(resolve, interval))
}
if (globalThis.provider.messages.length === 0) {
assert.fail("No messages received")
}
globalThis.provider.messages.forEach(({ type, text }) => {
if (type === "say" && text?.includes("Grade:")) {
console.log(text)
}
})
const gradeMessage = globalThis.provider.messages.find(
({ type, text }) => type === "say" && !text?.includes("Grade: (1-10)") && text?.includes("Grade:"),
)?.text
const gradeMatch = gradeMessage?.match(/Grade: (\d+)/)
const gradeNum = gradeMatch ? parseInt(gradeMatch[1]) : undefined
assert.ok(gradeNum !== undefined && gradeNum >= 7 && gradeNum <= 10, "Grade must be between 7 and 10")
} finally {
await new Promise((resolve) => setTimeout(resolve, interval))
}
await globalThis.provider.updateGlobalState("mode", "Ask")
await globalThis.provider.updateGlobalState("alwaysAllowModeSwitch", true)
await globalThis.provider.updateGlobalState("autoApprovalEnabled", true)
// Start a new task.
await globalThis.api.startNewTask(testPrompt)
// Wait for task to appear in history with tokens.
startTime = Date.now()
while (Date.now() - startTime < timeout) {
const messages = globalThis.provider.messages
if (
messages.some(
({ type, text }) =>
type === "say" && text?.includes("I AM DONE") && !text?.includes("be sure to say"),
)
) {
break
}
await new Promise((resolve) => setTimeout(resolve, interval))
}
if (globalThis.provider.messages.length === 0) {
assert.fail("No messages received")
}
// Log the messages to the console.
globalThis.provider.messages.forEach(({ type, text }) => {
if (type === "say") {
console.log(text)
}
})
// Start Grading Portion of test to grade the response from 1 to 10.
await globalThis.provider.updateGlobalState("mode", "Ask")
let output = globalThis.provider.messages.map(({ type, text }) => (type === "say" ? text : "")).join("\n")
await globalThis.api.startNewTask(
`Given this prompt: ${testPrompt} grade the response from 1 to 10 in the format of "Grade: (1-10)": ${output} \n Be sure to say 'I AM DONE GRADING' after the task is complete`,
)
startTime = Date.now()
while (Date.now() - startTime < timeout) {
const messages = globalThis.provider.messages
if (
messages.some(
({ type, text }) =>
type === "say" && text?.includes("I AM DONE GRADING") && !text?.includes("be sure to say"),
)
) {
break
}
await new Promise((resolve) => setTimeout(resolve, interval))
}
if (globalThis.provider.messages.length === 0) {
assert.fail("No messages received")
}
globalThis.provider.messages.forEach(({ type, text }) => {
if (type === "say" && text?.includes("Grade:")) {
console.log(text)
}
})
const gradeMessage = globalThis.provider.messages.find(
({ type, text }) => type === "say" && !text?.includes("Grade: (1-10)") && text?.includes("Grade:"),
)?.text
const gradeMatch = gradeMessage?.match(/Grade: (\d+)/)
const gradeNum = gradeMatch ? parseInt(gradeMatch[1]) : undefined
assert.ok(gradeNum !== undefined && gradeNum >= 7 && gradeNum <= 10, "Grade must be between 7 and 10")
})
})

View file

@ -1,5 +1,4 @@
import * as assert from "assert"
import * as vscode from "vscode"
suite("Roo Code Task", () => {
test("Should handle prompt and response correctly", async function () {
@ -10,48 +9,43 @@ suite("Roo Code Task", () => {
assert.fail("Extension not found")
}
try {
// Ensure the webview is launched.
let startTime = Date.now()
// Ensure the webview is launched.
let startTime = Date.now()
while (Date.now() - startTime < timeout) {
if (globalThis.provider.viewLaunched) {
break
}
await new Promise((resolve) => setTimeout(resolve, interval))
while (Date.now() - startTime < timeout) {
if (globalThis.provider.viewLaunched) {
break
}
await globalThis.provider.updateGlobalState("mode", "Code")
await globalThis.provider.updateGlobalState("alwaysAllowModeSwitch", true)
await globalThis.provider.updateGlobalState("autoApprovalEnabled", true)
await globalThis.api.startNewTask("Hello world, what is your name? Respond with 'My name is ...'")
// Wait for task to appear in history with tokens.
startTime = Date.now()
while (Date.now() - startTime < timeout) {
const messages = globalThis.provider.messages
if (messages.some(({ type, text }) => type === "say" && text?.includes("My name is Roo"))) {
break
}
await new Promise((resolve) => setTimeout(resolve, interval))
}
if (globalThis.provider.messages.length === 0) {
assert.fail("No messages received")
}
assert.ok(
globalThis.provider.messages.some(
({ type, text }) => type === "say" && text?.includes("My name is Roo"),
),
"Did not receive expected response containing 'My name is Roo'",
)
} finally {
await new Promise((resolve) => setTimeout(resolve, interval))
}
await globalThis.provider.updateGlobalState("mode", "Code")
await globalThis.provider.updateGlobalState("alwaysAllowModeSwitch", true)
await globalThis.provider.updateGlobalState("autoApprovalEnabled", true)
await globalThis.api.startNewTask("Hello world, what is your name? Respond with 'My name is ...'")
// Wait for task to appear in history with tokens.
startTime = Date.now()
while (Date.now() - startTime < timeout) {
const messages = globalThis.provider.messages
if (messages.some(({ type, text }) => type === "say" && text?.includes("My name is Roo"))) {
break
}
await new Promise((resolve) => setTimeout(resolve, interval))
}
if (globalThis.provider.messages.length === 0) {
assert.fail("No messages received")
}
assert.ok(
globalThis.provider.messages.some(({ type, text }) => type === "say" && text?.includes("My name is Roo")),
"Did not receive expected response containing 'My name is Roo'",
)
})
})

View file

@ -1,6 +1,9 @@
import { arePathsEqual, getReadablePath } from "../path"
import * as path from "path"
// npx jest src/utils/__tests__/path.test.ts
import os from "os"
import * as path from "path"
import { arePathsEqual, getReadablePath } from "../path"
describe("Path Utilities", () => {
const originalPlatform = process.platform
@ -92,22 +95,24 @@ describe("Path Utilities", () => {
describe("getReadablePath", () => {
const homeDir = os.homedir()
const desktop = path.join(homeDir, "Desktop")
const cwd = process.platform === "win32" ? "C:\\Users\\test\\project" : "/Users/test/project"
it("should return basename when path equals cwd", () => {
const cwd = "/Users/test/project"
expect(getReadablePath(cwd, cwd)).toBe("project")
})
it("should return relative path when inside cwd", () => {
const cwd = "/Users/test/project"
const filePath = "/Users/test/project/src/file.txt"
const filePath =
process.platform === "win32"
? "C:\\Users\\test\\project\\src\\file.txt"
: "/Users/test/project/src/file.txt"
expect(getReadablePath(cwd, filePath)).toBe("src/file.txt")
})
it("should return absolute path when outside cwd", () => {
const cwd = "/Users/test/project"
const filePath = "/Users/test/other/file.txt"
expect(getReadablePath(cwd, filePath)).toBe("/Users/test/other/file.txt")
const filePath =
process.platform === "win32" ? "C:\\Users\\test\\other\\file.txt" : "/Users/test/other/file.txt"
expect(getReadablePath(cwd, filePath)).toBe(filePath.toPosix())
})
it("should handle Desktop as cwd", () => {
@ -116,19 +121,20 @@ describe("Path Utilities", () => {
})
it("should handle undefined relative path", () => {
const cwd = "/Users/test/project"
expect(getReadablePath(cwd)).toBe("project")
})
it("should handle parent directory traversal", () => {
const cwd = "/Users/test/project"
const filePath = "../../other/file.txt"
expect(getReadablePath(cwd, filePath)).toBe("/Users/other/file.txt")
const filePath =
process.platform === "win32" ? "C:\\Users\\test\\other\\file.txt" : "/Users/test/other/file.txt"
expect(getReadablePath(cwd, filePath)).toBe(filePath.toPosix())
})
it("should normalize paths with redundant segments", () => {
const cwd = "/Users/test/project"
const filePath = "/Users/test/project/./src/../src/file.txt"
const filePath =
process.platform === "win32"
? "C:\\Users\\test\\project\\src\\file.txt"
: "/Users/test/project/./src/../src/file.txt"
expect(getReadablePath(cwd, filePath)).toBe("src/file.txt")
})
})

View file

@ -22,3 +22,5 @@ export function calculateApiCost(
const totalCost = cacheWritesCost + cacheReadsCost + baseInputCost + outputCost
return totalCost
}
export const parseApiPrice = (price: any) => (price ? parseFloat(price) * 1_000_000 : undefined)

View file

@ -1,3 +1,4 @@
{
"extends": "react-app"
"extends": "react-app",
"ignorePatterns": ["!.storybook"]
}

File diff suppressed because it is too large Load diff

View file

@ -75,13 +75,13 @@
"eslint-plugin-react-hooks": "^4.6.0",
"eslint-plugin-storybook": "^0.11.2",
"identity-obj-proxy": "^3.0.0",
"jest": "^27.5.1",
"jest-environment-jsdom": "^27.5.1",
"jest": "^29.7.0",
"jest-environment-jsdom": "^29.7.0",
"jest-simple-dot-reporter": "^1.0.5",
"shiki": "^2.3.2",
"storybook": "^8.5.6",
"storybook-dark-mode": "^4.0.2",
"ts-jest": "^27.1.5",
"ts-jest": "^29.2.5",
"typescript": "^4.9.5",
"vite": "6.0.11"
}

View file

@ -0,0 +1,6 @@
import React from "react"
export const Check = () => React.createElement("div")
export const ChevronsUpDown = () => React.createElement("div")
export const Loader = () => React.createElement("div")
export const X = () => React.createElement("div")

View file

@ -8,6 +8,9 @@ export const Dropdown = ({ children, value, onChange }: any) =>
export const Pane = ({ children }: any) => React.createElement("div", { "data-testid": "mock-pane" }, children)
export const Button = ({ children, ...props }: any) =>
React.createElement("div", { "data-testid": "mock-button", ...props }, children)
export type DropdownOption = {
label: string
value: string

View file

@ -16,6 +16,7 @@ import { vscode } from "../../utils/vscode"
import { WebviewMessage } from "../../../../src/shared/WebviewMessage"
import { Mode, getAllModes } from "../../../../src/shared/modes"
import { CaretIcon } from "../common/CaretIcon"
import { convertToMentionPath } from "../../utils/path-mentions"
interface ChatTextAreaProps {
inputValue: string
@ -50,7 +51,7 @@ const ChatTextArea = forwardRef<HTMLTextAreaElement, ChatTextAreaProps>(
},
ref,
) => {
const { filePaths, openedTabs, currentApiConfigName, listApiConfigMeta, customModes } = useExtensionState()
const { filePaths, openedTabs, currentApiConfigName, listApiConfigMeta, customModes, cwd } = useExtensionState()
const [gitCommits, setGitCommits] = useState<any[]>([])
const [showDropdown, setShowDropdown] = useState(false)
@ -589,18 +590,24 @@ const ChatTextArea = forwardRef<HTMLTextAreaElement, ChatTextAreaProps>(
const files = Array.from(e.dataTransfer.files)
const text = e.dataTransfer.getData("text")
if (text) {
const newValue = inputValue.slice(0, cursorPosition) + text + inputValue.slice(cursorPosition)
// Convert the path to a mention-friendly format
const mentionText = convertToMentionPath(text, cwd)
const newValue =
inputValue.slice(0, cursorPosition) + mentionText + " " + inputValue.slice(cursorPosition)
setInputValue(newValue)
const newCursorPosition = cursorPosition + text.length
const newCursorPosition = cursorPosition + mentionText.length + 1
setCursorPosition(newCursorPosition)
setIntendedCursorPosition(newCursorPosition)
return
}
const acceptedTypes = ["png", "jpeg", "webp"]
const imageFiles = files.filter((file) => {
const [type, subtype] = file.type.split("/")
return type === "image" && acceptedTypes.includes(subtype)
})
if (!shouldDisableImages && imageFiles.length > 0) {
const imagePromises = imageFiles.map((file) => {
return new Promise<string | null>((resolve) => {

View file

@ -880,9 +880,8 @@ const ChatView = ({ isHidden, showAnnouncement, hideAnnouncement, showHistoryVie
const placeholderText = useMemo(() => {
const baseText = task ? "Type a message..." : "Type your task here..."
const contextText = "(@ to add context, / to switch modes"
const imageText = shouldDisableImages ? "" : ", hold shift to drag in images"
const helpText = imageText ? `\n${contextText}${imageText})` : `\n${contextText})`
return baseText + helpText
const imageText = shouldDisableImages ? "hold shift to drag in files" : ", hold shift to drag in files/images"
return baseText + `\n${contextText}${imageText})`
}, [task, shouldDisableImages])
const itemContent = useCallback(

View file

@ -351,7 +351,7 @@ const TaskActions = ({ item }: { item: HistoryItem | undefined }) => (
<Button variant="ghost" size="sm" onClick={() => vscode.postMessage({ type: "exportCurrentTask" })}>
<span className="codicon codicon-cloud-download" />
</Button>
{item?.size && (
{!!item?.size && item.size > 0 && (
<Button
variant="ghost"
size="sm"

View file

@ -1,130 +0,0 @@
import {
VSCodeBadge,
VSCodeButton,
VSCodeCheckbox,
VSCodeDataGrid,
VSCodeDataGridCell,
VSCodeDataGridRow,
VSCodeDivider,
VSCodeDropdown,
VSCodeLink,
VSCodeOption,
VSCodePanels,
VSCodePanelTab,
VSCodePanelView,
VSCodeProgressRing,
VSCodeRadio,
VSCodeRadioGroup,
VSCodeTag,
VSCodeTextArea,
VSCodeTextField,
} from "@vscode/webview-ui-toolkit/react"
function Demo() {
// function handleHowdyClick() {
// vscode.postMessage({
// command: "hello",
// text: "Hey there partner! 🤠",
// })
// }
const rowData = [
{
cell1: "Cell Data",
cell2: "Cell Data",
cell3: "Cell Data",
cell4: "Cell Data",
},
{
cell1: "Cell Data",
cell2: "Cell Data",
cell3: "Cell Data",
cell4: "Cell Data",
},
{
cell1: "Cell Data",
cell2: "Cell Data",
cell3: "Cell Data",
cell4: "Cell Data",
},
]
return (
<main>
<h1>Hello World!</h1>
<VSCodeButton>Howdy!</VSCodeButton>
<div className="grid gap-3 p-2 place-items-start">
<VSCodeDataGrid>
<VSCodeDataGridRow row-type="header">
<VSCodeDataGridCell cell-type="columnheader" grid-column="1">
A Custom Header Title
</VSCodeDataGridCell>
<VSCodeDataGridCell cell-type="columnheader" grid-column="2">
Another Custom Title
</VSCodeDataGridCell>
<VSCodeDataGridCell cell-type="columnheader" grid-column="3">
Title Is Custom
</VSCodeDataGridCell>
<VSCodeDataGridCell cell-type="columnheader" grid-column="4">
Custom Title
</VSCodeDataGridCell>
</VSCodeDataGridRow>
{rowData.map((row, index) => (
<VSCodeDataGridRow key={index}>
<VSCodeDataGridCell grid-column="1">{row.cell1}</VSCodeDataGridCell>
<VSCodeDataGridCell grid-column="2">{row.cell2}</VSCodeDataGridCell>
<VSCodeDataGridCell grid-column="3">{row.cell3}</VSCodeDataGridCell>
<VSCodeDataGridCell grid-column="4">{row.cell4}</VSCodeDataGridCell>
</VSCodeDataGridRow>
))}
</VSCodeDataGrid>
<VSCodeTextField>
<section slot="end" style={{ display: "flex", alignItems: "center" }}>
<VSCodeButton appearance="icon" aria-label="Match Case">
<span className="codicon codicon-case-sensitive"></span>
</VSCodeButton>
<VSCodeButton appearance="icon" aria-label="Match Whole Word">
<span className="codicon codicon-whole-word"></span>
</VSCodeButton>
<VSCodeButton appearance="icon" aria-label="Use Regular Expression">
<span className="codicon codicon-regex"></span>
</VSCodeButton>
</section>
</VSCodeTextField>
<span slot="end" className="codicon codicon-chevron-right"></span>
<span className="flex gap-3">
<VSCodeProgressRing />
<VSCodeTextField />
<VSCodeButton>Add</VSCodeButton>
<VSCodeButton appearance="secondary">Remove</VSCodeButton>
</span>
<VSCodeBadge>Badge</VSCodeBadge>
<VSCodeCheckbox>Checkbox</VSCodeCheckbox>
<VSCodeDivider />
<VSCodeDropdown>
<VSCodeOption>Option 1</VSCodeOption>
<VSCodeOption>Option 2</VSCodeOption>
</VSCodeDropdown>
<VSCodeLink href="#">Link</VSCodeLink>
<VSCodePanels>
<VSCodePanelTab id="tab-1">Tab 1</VSCodePanelTab>
<VSCodePanelTab id="tab-2">Tab 2</VSCodePanelTab>
<VSCodePanelView id="view-1">Panel View 1</VSCodePanelView>
<VSCodePanelView id="view-2">Panel View 2</VSCodePanelView>
</VSCodePanels>
<VSCodeRadioGroup>
<VSCodeRadio>Radio 1</VSCodeRadio>
<VSCodeRadio>Radio 2</VSCodeRadio>
</VSCodeRadioGroup>
<VSCodeTag>Tag</VSCodeTag>
<VSCodeTextArea placeholder="Text Area" />
</div>
</main>
)
}
export default Demo

View file

@ -0,0 +1,49 @@
import React from "react"
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
} from "@/components/ui/alert-dialog"
import { Button } from "@/components/ui"
import { vscode } from "@/utils/vscode"
interface DeleteTaskDialogProps {
taskId: string
open: boolean
onOpenChange: (open: boolean) => void
}
export const DeleteTaskDialog = ({ taskId, open, onOpenChange }: DeleteTaskDialogProps) => {
const handleDelete = () => {
vscode.postMessage({ type: "deleteTaskWithId", text: taskId })
onOpenChange(false)
}
return (
<AlertDialog open={open} onOpenChange={onOpenChange}>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>Delete Task</AlertDialogTitle>
<AlertDialogDescription>
Are you sure you want to delete this task? This action cannot be undone.
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel asChild>
<Button variant="secondary">Cancel</Button>
</AlertDialogCancel>
<AlertDialogAction asChild>
<Button variant="destructive" onClick={handleDelete}>
Delete
</Button>
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
)
}

View file

@ -1,4 +1,5 @@
import React, { memo, useMemo, useState, useEffect } from "react"
import { DeleteTaskDialog } from "./DeleteTaskDialog"
import { Fzf } from "fzf"
import prettyBytes from "pretty-bytes"
import { Virtuoso } from "react-virtuoso"
@ -37,8 +38,12 @@ const HistoryView = ({ onDone }: HistoryViewProps) => {
vscode.postMessage({ type: "showTaskWithId", text: id })
}
const [deleteDialogOpen, setDeleteDialogOpen] = useState(false)
const [taskToDelete, setTaskToDelete] = useState<string | null>(null)
const handleDeleteHistoryItem = (id: string) => {
vscode.postMessage({ type: "deleteTaskWithId", text: id })
setTaskToDelete(id)
setDeleteDialogOpen(true)
}
const formatDate = (timestamp: number) => {
@ -398,6 +403,18 @@ const HistoryView = ({ onDone }: HistoryViewProps) => {
)}
/>
</div>
{taskToDelete && (
<DeleteTaskDialog
taskId={taskToDelete}
open={deleteDialogOpen}
onOpenChange={(open) => {
setDeleteDialogOpen(open)
if (!open) {
setTaskToDelete(null)
}
}}
/>
)}
</div>
)
}

View file

@ -135,7 +135,7 @@ describe("HistoryView", () => {
})
})
it("handles task deletion", () => {
it("handles task deletion", async () => {
const onDone = jest.fn()
render(<HistoryView onDone={onDone} />)
@ -143,9 +143,14 @@ describe("HistoryView", () => {
const taskContainer = screen.getByTestId("virtuoso-item-1")
fireEvent.mouseEnter(taskContainer)
// Click delete button to open confirmation dialog
const deleteButton = within(taskContainer).getByTitle("Delete Task")
fireEvent.click(deleteButton)
// Find and click the confirm delete button in the dialog
const confirmDeleteButton = screen.getByRole("button", { name: /delete/i })
fireEvent.click(confirmDeleteButton)
// Verify vscode message was sent
expect(vscode.postMessage).toHaveBeenCalledWith({
type: "deleteTaskWithId",

View file

@ -0,0 +1,16 @@
import React from "react"
interface ApiErrorMessageProps {
errorMessage: string | undefined
children?: React.ReactNode
}
export const ApiErrorMessage = ({ errorMessage, children }: ApiErrorMessageProps) => (
<div className="flex flex-col gap-2 text-vscode-errorForeground text-sm">
<div className="flex flex-row items-center gap-1">
<div className="codicon codicon-close" />
<div>{errorMessage}</div>
</div>
{children}
</div>
)

View file

@ -1,8 +1,7 @@
import { memo, useCallback, useMemo, useState } from "react"
import React, { memo, useCallback, useEffect, useMemo, useState } from "react"
import { useDebounce, useEvent } from "react-use"
import { Checkbox, Dropdown, Pane, type DropdownOption } from "vscrui"
import { VSCodeLink, VSCodeRadio, VSCodeRadioGroup, VSCodeTextField } from "@vscode/webview-ui-toolkit/react"
import { TemperatureControl } from "./TemperatureControl"
import * as vscodemodels from "vscode"
import {
@ -34,45 +33,76 @@ import {
requestyDefaultModelInfo,
} from "../../../../src/shared/api"
import { ExtensionMessage } from "../../../../src/shared/ExtensionMessage"
import { vscode } from "../../utils/vscode"
import VSCodeButtonLink from "../common/VSCodeButtonLink"
import { OpenRouterModelPicker } from "./OpenRouterModelPicker"
import OpenAiModelPicker from "./OpenAiModelPicker"
import { GlamaModelPicker } from "./GlamaModelPicker"
import { UnboundModelPicker } from "./UnboundModelPicker"
import { ModelInfoView } from "./ModelInfoView"
import { DROPDOWN_Z_INDEX } from "./styles"
import { RequestyModelPicker } from "./RequestyModelPicker"
import { ModelPicker } from "./ModelPicker"
import { TemperatureControl } from "./TemperatureControl"
import { validateApiConfiguration, validateModelId } from "@/utils/validate"
import { ApiErrorMessage } from "./ApiErrorMessage"
import { ThinkingBudget } from "./ThinkingBudget"
const modelsByProvider: Record<string, Record<string, ModelInfo>> = {
anthropic: anthropicModels,
bedrock: bedrockModels,
vertex: vertexModels,
gemini: geminiModels,
"openai-native": openAiNativeModels,
deepseek: deepSeekModels,
mistral: mistralModels,
}
interface ApiOptionsProps {
uriScheme: string | undefined
apiConfiguration: ApiConfiguration | undefined
apiConfiguration: ApiConfiguration
setApiConfigurationField: <K extends keyof ApiConfiguration>(field: K, value: ApiConfiguration[K]) => void
apiErrorMessage?: string
modelIdErrorMessage?: string
fromWelcomeView?: boolean
errorMessage: string | undefined
setErrorMessage: React.Dispatch<React.SetStateAction<string | undefined>>
}
const ApiOptions = ({
uriScheme,
apiConfiguration,
setApiConfigurationField,
apiErrorMessage,
modelIdErrorMessage,
fromWelcomeView,
errorMessage,
setErrorMessage,
}: ApiOptionsProps) => {
const [ollamaModels, setOllamaModels] = useState<string[]>([])
const [lmStudioModels, setLmStudioModels] = useState<string[]>([])
const [vsCodeLmModels, setVsCodeLmModels] = useState<vscodemodels.LanguageModelChatSelector[]>([])
const [openRouterModels, setOpenRouterModels] = useState<Record<string, ModelInfo>>({
[openRouterDefaultModelId]: openRouterDefaultModelInfo,
})
const [glamaModels, setGlamaModels] = useState<Record<string, ModelInfo>>({
[glamaDefaultModelId]: glamaDefaultModelInfo,
})
const [unboundModels, setUnboundModels] = useState<Record<string, ModelInfo>>({
[unboundDefaultModelId]: unboundDefaultModelInfo,
})
const [requestyModels, setRequestyModels] = useState<Record<string, ModelInfo>>({
[requestyDefaultModelId]: requestyDefaultModelInfo,
})
const [openAiModels, setOpenAiModels] = useState<Record<string, ModelInfo> | null>(null)
const [anthropicBaseUrlSelected, setAnthropicBaseUrlSelected] = useState(!!apiConfiguration?.anthropicBaseUrl)
const [azureApiVersionSelected, setAzureApiVersionSelected] = useState(!!apiConfiguration?.azureApiVersion)
const [openRouterBaseUrlSelected, setOpenRouterBaseUrlSelected] = useState(!!apiConfiguration?.openRouterBaseUrl)
const [isDescriptionExpanded, setIsDescriptionExpanded] = useState(false)
const inputEventTransform = <E,>(event: E) => (event as { target: HTMLInputElement })?.target?.value as any
const noTransform = <T,>(value: T) => value
const inputEventTransform = <E,>(event: E) => (event as { target: HTMLInputElement })?.target?.value as any
const dropdownEventTransform = <T,>(event: DropdownOption | string | undefined) =>
(typeof event == "string" ? event : event?.value) as T
const handleInputChange = useCallback(
<K extends keyof ApiConfiguration, E>(
field: K,
@ -84,15 +114,32 @@ const ApiOptions = ({
[setApiConfigurationField],
)
const { selectedProvider, selectedModelId, selectedModelInfo } = useMemo(() => {
return normalizeApiConfiguration(apiConfiguration)
}, [apiConfiguration])
const { selectedProvider, selectedModelId, selectedModelInfo } = useMemo(
() => normalizeApiConfiguration(apiConfiguration),
[apiConfiguration],
)
// Pull ollama/lmstudio models
// Debounced model updates, only executed 250ms after the user stops typing
// Debounced refresh model updates, only executed 250ms after the user
// stops typing.
useDebounce(
() => {
if (selectedProvider === "ollama") {
if (selectedProvider === "openrouter") {
vscode.postMessage({ type: "refreshOpenRouterModels" })
} else if (selectedProvider === "glama") {
vscode.postMessage({ type: "refreshGlamaModels" })
} else if (selectedProvider === "unbound") {
vscode.postMessage({ type: "refreshUnboundModels" })
} else if (selectedProvider === "requesty") {
vscode.postMessage({
type: "refreshRequestyModels",
values: { apiKey: apiConfiguration?.requestyApiKey },
})
} else if (selectedProvider === "openai") {
vscode.postMessage({
type: "refreshOpenAiModels",
values: { baseUrl: apiConfiguration?.openAiBaseUrl, apiKey: apiConfiguration?.openAiApiKey },
})
} else if (selectedProvider === "ollama") {
vscode.postMessage({ type: "requestOllamaModels", text: apiConfiguration?.ollamaBaseUrl })
} else if (selectedProvider === "lmstudio") {
vscode.postMessage({ type: "requestLmStudioModels", text: apiConfiguration?.lmStudioBaseUrl })
@ -101,49 +148,95 @@ const ApiOptions = ({
}
},
250,
[selectedProvider, apiConfiguration?.ollamaBaseUrl, apiConfiguration?.lmStudioBaseUrl],
[
selectedProvider,
apiConfiguration?.requestyApiKey,
apiConfiguration?.openAiBaseUrl,
apiConfiguration?.openAiApiKey,
apiConfiguration?.ollamaBaseUrl,
apiConfiguration?.lmStudioBaseUrl,
],
)
const handleMessage = useCallback((event: MessageEvent) => {
useEffect(() => {
const apiValidationResult =
validateApiConfiguration(apiConfiguration) ||
validateModelId(apiConfiguration, glamaModels, openRouterModels, unboundModels, requestyModels)
setErrorMessage(apiValidationResult)
}, [apiConfiguration, glamaModels, openRouterModels, setErrorMessage, unboundModels, requestyModels])
const onMessage = useCallback((event: MessageEvent) => {
const message: ExtensionMessage = event.data
if (message.type === "ollamaModels" && Array.isArray(message.ollamaModels)) {
const newModels = message.ollamaModels
setOllamaModels(newModels)
} else if (message.type === "lmStudioModels" && Array.isArray(message.lmStudioModels)) {
const newModels = message.lmStudioModels
setLmStudioModels(newModels)
} else if (message.type === "vsCodeLmModels" && Array.isArray(message.vsCodeLmModels)) {
const newModels = message.vsCodeLmModels
setVsCodeLmModels(newModels)
switch (message.type) {
case "openRouterModels": {
const updatedModels = message.openRouterModels ?? {}
setOpenRouterModels({ [openRouterDefaultModelId]: openRouterDefaultModelInfo, ...updatedModels })
break
}
case "glamaModels": {
const updatedModels = message.glamaModels ?? {}
setGlamaModels({ [glamaDefaultModelId]: glamaDefaultModelInfo, ...updatedModels })
break
}
case "unboundModels": {
const updatedModels = message.unboundModels ?? {}
setUnboundModels({ [unboundDefaultModelId]: unboundDefaultModelInfo, ...updatedModels })
break
}
case "requestyModels": {
const updatedModels = message.requestyModels ?? {}
setRequestyModels({ [requestyDefaultModelId]: requestyDefaultModelInfo, ...updatedModels })
break
}
case "openAiModels": {
const updatedModels = message.openAiModels ?? []
setOpenAiModels(Object.fromEntries(updatedModels.map((item) => [item, openAiModelInfoSaneDefaults])))
break
}
case "ollamaModels":
{
const newModels = message.ollamaModels ?? []
setOllamaModels(newModels)
}
break
case "lmStudioModels":
{
const newModels = message.lmStudioModels ?? []
setLmStudioModels(newModels)
}
break
case "vsCodeLmModels":
{
const newModels = message.vsCodeLmModels ?? []
setVsCodeLmModels(newModels)
}
break
}
}, [])
useEvent("message", handleMessage)
const createDropdown = (models: Record<string, ModelInfo>) => {
const options: DropdownOption[] = [
{ value: "", label: "Select a model..." },
...Object.keys(models).map((modelId) => ({
value: modelId,
label: modelId,
})),
]
return (
<Dropdown
id="model-id"
value={selectedModelId}
onChange={(value) => {
setApiConfigurationField("apiModelId", typeof value == "string" ? value : value?.value)
}}
style={{ width: "100%" }}
options={options}
/>
)
}
useEvent("message", onMessage)
const selectedProviderModelOptions: DropdownOption[] = useMemo(
() =>
modelsByProvider[selectedProvider]
? [
{ value: "", label: "Select a model..." },
...Object.keys(modelsByProvider[selectedProvider]).map((modelId) => ({
value: modelId,
label: modelId,
})),
]
: [],
[selectedProvider],
)
return (
<div style={{ display: "flex", flexDirection: "column", gap: 5 }}>
<div className="dropdown-container">
<label htmlFor="api-provider">
<span style={{ fontWeight: 500 }}>API Provider</span>
<label htmlFor="api-provider" className="font-medium">
API Provider
</label>
<Dropdown
id="api-provider"
@ -170,6 +263,8 @@ const ApiOptions = ({
/>
</div>
{errorMessage && <ApiErrorMessage errorMessage={errorMessage} />}
{selectedProvider === "anthropic" && (
<div>
<VSCodeTextField
@ -178,13 +273,14 @@ const ApiOptions = ({
type="password"
onInput={handleInputChange("apiKey")}
placeholder="Enter API Key...">
<span style={{ fontWeight: 500 }}>Anthropic API Key</span>
<span className="font-medium">Anthropic API Key</span>
</VSCodeTextField>
<Checkbox
checked={anthropicBaseUrlSelected}
onChange={(checked: boolean) => {
setAnthropicBaseUrlSelected(checked)
if (!checked) {
setApiConfigurationField("anthropicBaseUrl", "")
}
@ -228,7 +324,7 @@ const ApiOptions = ({
type="password"
onInput={handleInputChange("glamaApiKey")}
placeholder="Enter API Key...">
<span style={{ fontWeight: 500 }}>Glama API Key</span>
<span className="font-medium">Glama API Key</span>
</VSCodeTextField>
{!apiConfiguration?.glamaApiKey && (
<VSCodeButtonLink
@ -257,7 +353,7 @@ const ApiOptions = ({
type="password"
onInput={handleInputChange("requestyApiKey")}
placeholder="Enter API Key...">
<span style={{ fontWeight: 500 }}>Requesty API Key</span>
<span className="font-medium">Requesty API Key</span>
</VSCodeTextField>
<p
style={{
@ -278,7 +374,7 @@ const ApiOptions = ({
type="password"
onInput={handleInputChange("openAiNativeApiKey")}
placeholder="Enter API Key...">
<span style={{ fontWeight: 500 }}>OpenAI API Key</span>
<span className="font-medium">OpenAI API Key</span>
</VSCodeTextField>
<p
style={{
@ -306,7 +402,7 @@ const ApiOptions = ({
type="password"
onInput={handleInputChange("mistralApiKey")}
placeholder="Enter API Key...">
<span style={{ fontWeight: 500 }}>Mistral API Key</span>
<span className="font-medium">Mistral API Key</span>
</VSCodeTextField>
<p
style={{
@ -335,7 +431,7 @@ const ApiOptions = ({
type="url"
onInput={handleInputChange("mistralCodestralUrl")}
placeholder="Default: https://codestral.mistral.ai">
<span style={{ fontWeight: 500 }}>Codestral Base URL (Optional)</span>
<span className="font-medium">Codestral Base URL (Optional)</span>
</VSCodeTextField>
<p
style={{
@ -358,7 +454,7 @@ const ApiOptions = ({
type="password"
onInput={handleInputChange("openRouterApiKey")}
placeholder="Enter API Key...">
<span style={{ fontWeight: 500 }}>OpenRouter API Key</span>
<span className="font-medium">OpenRouter API Key</span>
</VSCodeTextField>
{!apiConfiguration?.openRouterApiKey && (
<p>
@ -384,6 +480,7 @@ const ApiOptions = ({
checked={openRouterBaseUrlSelected}
onChange={(checked: boolean) => {
setOpenRouterBaseUrlSelected(checked)
if (!checked) {
setApiConfigurationField("openRouterBaseUrl", "")
}
@ -429,7 +526,7 @@ const ApiOptions = ({
style={{ width: "100%" }}
onInput={handleInputChange("awsProfile")}
placeholder="Enter profile name">
<span style={{ fontWeight: 500 }}>AWS Profile Name</span>
<span className="font-medium">AWS Profile Name</span>
</VSCodeTextField>
) : (
<>
@ -440,7 +537,7 @@ const ApiOptions = ({
type="password"
onInput={handleInputChange("awsAccessKey")}
placeholder="Enter Access Key...">
<span style={{ fontWeight: 500 }}>AWS Access Key</span>
<span className="font-medium">AWS Access Key</span>
</VSCodeTextField>
<VSCodeTextField
value={apiConfiguration?.awsSecretKey || ""}
@ -448,7 +545,7 @@ const ApiOptions = ({
type="password"
onInput={handleInputChange("awsSecretKey")}
placeholder="Enter Secret Key...">
<span style={{ fontWeight: 500 }}>AWS Secret Key</span>
<span className="font-medium">AWS Secret Key</span>
</VSCodeTextField>
<VSCodeTextField
value={apiConfiguration?.awsSessionToken || ""}
@ -456,21 +553,19 @@ const ApiOptions = ({
type="password"
onInput={handleInputChange("awsSessionToken")}
placeholder="Enter Session Token...">
<span style={{ fontWeight: 500 }}>AWS Session Token</span>
<span className="font-medium">AWS Session Token</span>
</VSCodeTextField>
</>
)}
<div className="dropdown-container">
<label htmlFor="aws-region-dropdown">
<span style={{ fontWeight: 500 }}>AWS Region</span>
<span className="font-medium">AWS Region</span>
</label>
<Dropdown
id="aws-region-dropdown"
value={apiConfiguration?.awsRegion || ""}
style={{ width: "100%" }}
onChange={(value: unknown) => {
handleInputChange("awsRegion", dropdownEventTransform)
}}
onChange={handleInputChange("awsRegion", dropdownEventTransform)}
options={[
{ value: "", label: "Select a region..." },
{ value: "us-east-1", label: "us-east-1" },
@ -509,18 +604,18 @@ const ApiOptions = ({
</div>
)}
{apiConfiguration?.apiProvider === "vertex" && (
{selectedProvider === "vertex" && (
<div style={{ display: "flex", flexDirection: "column", gap: 5 }}>
<VSCodeTextField
value={apiConfiguration?.vertexProjectId || ""}
style={{ width: "100%" }}
onInput={handleInputChange("vertexProjectId")}
placeholder="Enter Project ID...">
<span style={{ fontWeight: 500 }}>Google Cloud Project ID</span>
<span className="font-medium">Google Cloud Project ID</span>
</VSCodeTextField>
<div className="dropdown-container">
<label htmlFor="vertex-region-dropdown">
<span style={{ fontWeight: 500 }}>Google Cloud Region</span>
<span className="font-medium">Google Cloud Region</span>
</label>
<Dropdown
id="vertex-region-dropdown"
@ -568,7 +663,7 @@ const ApiOptions = ({
type="password"
onInput={handleInputChange("geminiApiKey")}
placeholder="Enter API Key...">
<span style={{ fontWeight: 500 }}>Gemini API Key</span>
<span className="font-medium">Gemini API Key</span>
</VSCodeTextField>
<p
style={{
@ -596,7 +691,7 @@ const ApiOptions = ({
type="url"
onInput={handleInputChange("openAiBaseUrl")}
placeholder={"Enter base URL..."}>
<span style={{ fontWeight: 500 }}>Base URL</span>
<span className="font-medium">Base URL</span>
</VSCodeTextField>
<VSCodeTextField
value={apiConfiguration?.openAiApiKey || ""}
@ -604,9 +699,19 @@ const ApiOptions = ({
type="password"
onInput={handleInputChange("openAiApiKey")}
placeholder="Enter API Key...">
<span style={{ fontWeight: 500 }}>API Key</span>
<span className="font-medium">API Key</span>
</VSCodeTextField>
<OpenAiModelPicker />
<ModelPicker
apiConfiguration={apiConfiguration}
setApiConfigurationField={setApiConfigurationField}
defaultModelId="gpt-4o"
defaultModelInfo={openAiModelInfoSaneDefaults}
models={openAiModels}
modelIdKey="openAiModelId"
modelInfoKey="openAiCustomModelInfo"
serviceName="OpenAI"
serviceUrl="https://platform.openai.com"
/>
<div style={{ display: "flex", alignItems: "center" }}>
<Checkbox
checked={apiConfiguration?.openAiStreamingEnabled ?? true}
@ -623,6 +728,7 @@ const ApiOptions = ({
checked={azureApiVersionSelected}
onChange={(checked: boolean) => {
setAzureApiVersionSelected(checked)
if (!checked) {
setApiConfigurationField("azureApiVersion", "")
}
@ -637,12 +743,7 @@ const ApiOptions = ({
placeholder={`Default: ${azureOpenAiDefaultApiVersion}`}
/>
)}
<div
style={{
marginTop: 15,
}}
/>
<div className="mt-4" />
<Pane
title="Model Configuration"
open={false}
@ -693,7 +794,7 @@ const ApiOptions = ({
})(),
}}
title="Maximum number of tokens the model can generate in a single response"
onChange={handleInputChange("openAiCustomModelInfo", (e) => {
onInput={handleInputChange("openAiCustomModelInfo", (e) => {
const value = parseInt((e.target as HTMLInputElement).value)
return {
...(apiConfiguration?.openAiCustomModelInfo ||
@ -702,7 +803,7 @@ const ApiOptions = ({
}
})}
placeholder="e.g. 4096">
<span style={{ fontWeight: 500 }}>Max Output Tokens</span>
<span className="font-medium">Max Output Tokens</span>
</VSCodeTextField>
<div
style={{
@ -740,7 +841,7 @@ const ApiOptions = ({
})(),
}}
title="Total number of tokens (input + output) the model can process in a single request"
onChange={handleInputChange("openAiCustomModelInfo", (e) => {
onInput={handleInputChange("openAiCustomModelInfo", (e) => {
const value = (e.target as HTMLInputElement).value
const parsed = parseInt(value)
return {
@ -752,7 +853,7 @@ const ApiOptions = ({
}
})}
placeholder="e.g. 128000">
<span style={{ fontWeight: 500 }}>Context Window Size</span>
<span className="font-medium">Context Window Size</span>
</VSCodeTextField>
<div
style={{
@ -790,7 +891,7 @@ const ApiOptions = ({
supportsImages: checked,
}
})}>
<span style={{ fontWeight: 500 }}>Image Support</span>
<span className="font-medium">Image Support</span>
</Checkbox>
<i
className="codicon codicon-info"
@ -834,7 +935,7 @@ const ApiOptions = ({
supportsComputerUse: checked,
}
})}>
<span style={{ fontWeight: 500 }}>Computer Use</span>
<span className="font-medium">Computer Use</span>
</Checkbox>
<i
className="codicon codicon-info"
@ -886,9 +987,9 @@ const ApiOptions = ({
: "var(--vscode-errorForeground)"
})(),
}}
onChange={handleInputChange("openAiCustomModelInfo", (e) => {
onInput={handleInputChange("openAiCustomModelInfo", (e) => {
const value = (e.target as HTMLInputElement).value
const parsed = parseInt(value)
const parsed = parseFloat(value)
return {
...(apiConfiguration?.openAiCustomModelInfo ??
openAiModelInfoSaneDefaults),
@ -899,7 +1000,7 @@ const ApiOptions = ({
})}
placeholder="e.g. 0.0001">
<div style={{ display: "flex", alignItems: "center", gap: "4px" }}>
<span style={{ fontWeight: 500 }}>Input Price</span>
<span className="font-medium">Input Price</span>
<i
className="codicon codicon-info"
title="Cost per million tokens in the input/prompt. This affects the cost of sending context and instructions to the model."
@ -931,9 +1032,9 @@ const ApiOptions = ({
: "var(--vscode-errorForeground)"
})(),
}}
onChange={handleInputChange("openAiCustomModelInfo", (e) => {
onInput={handleInputChange("openAiCustomModelInfo", (e) => {
const value = (e.target as HTMLInputElement).value
const parsed = parseInt(value)
const parsed = parseFloat(value)
return {
...(apiConfiguration?.openAiCustomModelInfo ||
openAiModelInfoSaneDefaults),
@ -944,7 +1045,7 @@ const ApiOptions = ({
})}
placeholder="e.g. 0.0002">
<div style={{ display: "flex", alignItems: "center", gap: "4px" }}>
<span style={{ fontWeight: 500 }}>Output Price</span>
<span className="font-medium">Output Price</span>
<i
className="codicon codicon-info"
title="Cost per million tokens in the model's response. This affects the cost of generated content and completions."
@ -968,18 +1069,6 @@ const ApiOptions = ({
/>
{/* end Model Info Configuration */}
<p
style={{
fontSize: "12px",
marginTop: 3,
color: "var(--vscode-descriptionForeground)",
}}>
<span style={{ color: "var(--vscode-errorForeground)" }}>
(<span style={{ fontWeight: 500 }}>Note:</span> Roo Code uses complex prompts and works best
with Claude models. Less capable models may not work as expected.)
</span>
</p>
</div>
)}
@ -991,14 +1080,14 @@ const ApiOptions = ({
type="url"
onInput={handleInputChange("lmStudioBaseUrl")}
placeholder={"Default: http://localhost:1234"}>
<span style={{ fontWeight: 500 }}>Base URL (optional)</span>
<span className="font-medium">Base URL (optional)</span>
</VSCodeTextField>
<VSCodeTextField
value={apiConfiguration?.lmStudioModelId || ""}
style={{ width: "100%" }}
onInput={handleInputChange("lmStudioModelId")}
placeholder={"e.g. meta-llama-3.1-8b-instruct"}>
<span style={{ fontWeight: 500 }}>Model ID</span>
<span className="font-medium">Model ID</span>
</VSCodeTextField>
{lmStudioModels.length > 0 && (
<VSCodeRadioGroup
@ -1037,7 +1126,7 @@ const ApiOptions = ({
</VSCodeLink>{" "}
feature to use it with this extension.{" "}
<span style={{ color: "var(--vscode-errorForeground)" }}>
(<span style={{ fontWeight: 500 }}>Note:</span> Roo Code uses complex prompts and works best
(<span className="font-medium">Note:</span> Roo Code uses complex prompts and works best
with Claude models. Less capable models may not work as expected.)
</span>
</p>
@ -1052,7 +1141,7 @@ const ApiOptions = ({
type="password"
onInput={handleInputChange("deepSeekApiKey")}
placeholder="Enter API Key...">
<span style={{ fontWeight: 500 }}>DeepSeek API Key</span>
<span className="font-medium">DeepSeek API Key</span>
</VSCodeTextField>
<p
style={{
@ -1076,7 +1165,7 @@ const ApiOptions = ({
<div>
<div className="dropdown-container">
<label htmlFor="vscode-lm-model">
<span style={{ fontWeight: 500 }}>Language Model</span>
<span className="font-medium">Language Model</span>
</label>
{vsCodeLmModels.length > 0 ? (
<Dropdown
@ -1135,15 +1224,21 @@ const ApiOptions = ({
type="url"
onInput={handleInputChange("ollamaBaseUrl")}
placeholder={"Default: http://localhost:11434"}>
<span style={{ fontWeight: 500 }}>Base URL (optional)</span>
<span className="font-medium">Base URL (optional)</span>
</VSCodeTextField>
<VSCodeTextField
value={apiConfiguration?.ollamaModelId || ""}
style={{ width: "100%" }}
onInput={handleInputChange("ollamaModelId")}
placeholder={"e.g. llama3.1"}>
<span style={{ fontWeight: 500 }}>Model ID</span>
<span className="font-medium">Model ID</span>
</VSCodeTextField>
{errorMessage && (
<div className="text-vscode-errorForeground text-sm">
<span style={{ fontSize: "2em" }} className={`codicon codicon-close align-middle mr-1`} />
{errorMessage}
</div>
)}
{ollamaModels.length > 0 && (
<VSCodeRadioGroup
value={
@ -1176,7 +1271,7 @@ const ApiOptions = ({
quickstart guide.
</VSCodeLink>
<span style={{ color: "var(--vscode-errorForeground)" }}>
(<span style={{ fontWeight: 500 }}>Note:</span> Roo Code uses complex prompts and works best
(<span className="font-medium">Note:</span> Roo Code uses complex prompts and works best
with Claude models. Less capable models may not work as expected.)
</span>
</p>
@ -1191,7 +1286,7 @@ const ApiOptions = ({
type="password"
onChange={handleInputChange("unboundApiKey")}
placeholder="Enter API Key...">
<span style={{ fontWeight: 500 }}>Unbound API Key</span>
<span className="font-medium">Unbound API Key</span>
</VSCodeTextField>
{!apiConfiguration?.unboundApiKey && (
<VSCodeButtonLink
@ -1209,59 +1304,97 @@ const ApiOptions = ({
}}>
This key is stored locally and only used to make API requests from this extension.
</p>
<UnboundModelPicker />
</div>
)}
{apiErrorMessage && (
<p
style={{
margin: "-10px 0 4px 0",
fontSize: 12,
color: "var(--vscode-errorForeground)",
}}>
<span style={{ fontSize: "2em" }} className={`codicon codicon-close align-middle mr-1`} />
{apiErrorMessage}
</p>
{selectedProvider === "openrouter" && (
<ModelPicker
apiConfiguration={apiConfiguration}
setApiConfigurationField={setApiConfigurationField}
defaultModelId={openRouterDefaultModelId}
defaultModelInfo={openRouterDefaultModelInfo}
models={openRouterModels}
modelIdKey="openRouterModelId"
modelInfoKey="openRouterModelInfo"
serviceName="OpenRouter"
serviceUrl="https://openrouter.ai/models"
/>
)}
{selectedProvider === "glama" && <GlamaModelPicker />}
{selectedProvider === "glama" && (
<ModelPicker
apiConfiguration={apiConfiguration}
setApiConfigurationField={setApiConfigurationField}
defaultModelId={glamaDefaultModelId}
defaultModelInfo={glamaDefaultModelInfo}
models={glamaModels}
modelInfoKey="glamaModelInfo"
modelIdKey="glamaModelId"
serviceName="Glama"
serviceUrl="https://glama.ai/models"
/>
)}
{selectedProvider === "openrouter" && <OpenRouterModelPicker />}
{selectedProvider === "requesty" && <RequestyModelPicker />}
{selectedProvider === "unbound" && (
<ModelPicker
apiConfiguration={apiConfiguration}
defaultModelId={unboundDefaultModelId}
defaultModelInfo={unboundDefaultModelInfo}
models={unboundModels}
modelInfoKey="unboundModelInfo"
modelIdKey="unboundModelId"
serviceName="Unbound"
serviceUrl="https://api.getunbound.ai/models"
setApiConfigurationField={setApiConfigurationField}
/>
)}
{selectedProvider !== "glama" &&
selectedProvider !== "openrouter" &&
selectedProvider !== "requesty" &&
selectedProvider !== "openai" &&
selectedProvider !== "ollama" &&
selectedProvider !== "lmstudio" &&
selectedProvider !== "unbound" && (
<>
<div className="dropdown-container">
<label htmlFor="model-id">
<span style={{ fontWeight: 500 }}>Model</span>
</label>
{selectedProvider === "anthropic" && createDropdown(anthropicModels)}
{selectedProvider === "bedrock" && createDropdown(bedrockModels)}
{selectedProvider === "vertex" && createDropdown(vertexModels)}
{selectedProvider === "gemini" && createDropdown(geminiModels)}
{selectedProvider === "openai-native" && createDropdown(openAiNativeModels)}
{selectedProvider === "deepseek" && createDropdown(deepSeekModels)}
{selectedProvider === "mistral" && createDropdown(mistralModels)}
</div>
{selectedProvider === "requesty" && (
<ModelPicker
apiConfiguration={apiConfiguration}
setApiConfigurationField={setApiConfigurationField}
defaultModelId={requestyDefaultModelId}
defaultModelInfo={requestyDefaultModelInfo}
models={requestyModels}
modelIdKey="requestyModelId"
modelInfoKey="requestyModelInfo"
serviceName="Requesty"
serviceUrl="https://requesty.ai"
/>
)}
<ModelInfoView
selectedModelId={selectedModelId}
modelInfo={selectedModelInfo}
isDescriptionExpanded={isDescriptionExpanded}
setIsDescriptionExpanded={setIsDescriptionExpanded}
{selectedProviderModelOptions.length > 0 && (
<>
<div className="dropdown-container">
<label htmlFor="model-id" className="font-medium">
Model
</label>
<Dropdown
id="model-id"
value={selectedModelId}
onChange={(value) => {
setApiConfigurationField("apiModelId", typeof value == "string" ? value : value?.value)
}}
options={selectedProviderModelOptions}
className="w-full"
/>
</>
)}
</div>
<ThinkingBudget
apiConfiguration={apiConfiguration}
setApiConfigurationField={setApiConfigurationField}
modelInfo={selectedModelInfo}
/>
<ModelInfoView
selectedModelId={selectedModelId}
modelInfo={selectedModelInfo}
isDescriptionExpanded={isDescriptionExpanded}
setIsDescriptionExpanded={setIsDescriptionExpanded}
/>
</>
)}
{!fromWelcomeView && (
<div style={{ marginTop: "10px" }}>
<div className="mt-2">
<TemperatureControl
value={apiConfiguration?.modelTemperature}
onChange={handleInputChange("modelTemperature", noTransform)}
@ -1269,18 +1402,6 @@ const ApiOptions = ({
/>
</div>
)}
{modelIdErrorMessage && (
<p
style={{
margin: "-10px 0 4px 0",
fontSize: 12,
color: "var(--vscode-errorForeground)",
}}>
<span style={{ fontSize: "2em" }} className={`codicon codicon-close align-middle mr-1`} />
{modelIdErrorMessage}
</p>
)}
</div>
)
}
@ -1302,6 +1423,7 @@ export function normalizeApiConfiguration(apiConfiguration?: ApiConfiguration) {
const getProviderData = (models: Record<string, ModelInfo>, defaultId: string) => {
let selectedModelId: string
let selectedModelInfo: ModelInfo
if (modelId && modelId in models) {
selectedModelId = modelId
selectedModelInfo = models[modelId]
@ -1309,8 +1431,10 @@ export function normalizeApiConfiguration(apiConfiguration?: ApiConfiguration) {
selectedModelId = defaultId
selectedModelInfo = models[defaultId]
}
return { selectedProvider: provider, selectedModelId, selectedModelInfo }
}
switch (provider) {
case "anthropic":
return getProviderData(anthropicModels, anthropicDefaultModelId)
@ -1324,12 +1448,6 @@ export function normalizeApiConfiguration(apiConfiguration?: ApiConfiguration) {
return getProviderData(deepSeekModels, deepSeekDefaultModelId)
case "openai-native":
return getProviderData(openAiNativeModels, openAiNativeDefaultModelId)
case "glama":
return {
selectedProvider: provider,
selectedModelId: apiConfiguration?.glamaModelId || glamaDefaultModelId,
selectedModelInfo: apiConfiguration?.glamaModelInfo || glamaDefaultModelInfo,
}
case "mistral":
return getProviderData(mistralModels, mistralDefaultModelId)
case "openrouter":
@ -1338,6 +1456,24 @@ export function normalizeApiConfiguration(apiConfiguration?: ApiConfiguration) {
selectedModelId: apiConfiguration?.openRouterModelId || openRouterDefaultModelId,
selectedModelInfo: apiConfiguration?.openRouterModelInfo || openRouterDefaultModelInfo,
}
case "glama":
return {
selectedProvider: provider,
selectedModelId: apiConfiguration?.glamaModelId || glamaDefaultModelId,
selectedModelInfo: apiConfiguration?.glamaModelInfo || glamaDefaultModelInfo,
}
case "unbound":
return {
selectedProvider: provider,
selectedModelId: apiConfiguration?.unboundModelId || unboundDefaultModelId,
selectedModelInfo: apiConfiguration?.unboundModelInfo || unboundDefaultModelInfo,
}
case "requesty":
return {
selectedProvider: provider,
selectedModelId: apiConfiguration?.requestyModelId || requestyDefaultModelId,
selectedModelInfo: apiConfiguration?.requestyModelInfo || requestyDefaultModelInfo,
}
case "openai":
return {
selectedProvider: provider,
@ -1364,21 +1500,9 @@ export function normalizeApiConfiguration(apiConfiguration?: ApiConfiguration) {
: "",
selectedModelInfo: {
...openAiModelInfoSaneDefaults,
supportsImages: false, // VSCode LM API currently doesn't support images
supportsImages: false, // VSCode LM API currently doesn't support images.
},
}
case "unbound":
return {
selectedProvider: provider,
selectedModelId: apiConfiguration?.unboundModelId || unboundDefaultModelId,
selectedModelInfo: apiConfiguration?.unboundModelInfo || unboundDefaultModelInfo,
}
case "requesty":
return {
selectedProvider: provider,
selectedModelId: apiConfiguration?.requestyModelId || requestyDefaultModelId,
selectedModelInfo: apiConfiguration?.requestyModelInfo || requestyDefaultModelInfo,
}
default:
return getProviderData(anthropicModels, anthropicDefaultModelId)
}

View file

@ -1,15 +0,0 @@
import { ModelPicker } from "./ModelPicker"
import { glamaDefaultModelId } from "../../../../src/shared/api"
export const GlamaModelPicker = () => (
<ModelPicker
defaultModelId={glamaDefaultModelId}
modelsKey="glamaModels"
configKey="glamaModelId"
infoKey="glamaModelInfo"
refreshMessageType="refreshGlamaModels"
serviceName="Glama"
serviceUrl="https://glama.ai/models"
recommendedModel="anthropic/claude-3-5-sonnet"
/>
)

View file

@ -1,186 +1,95 @@
import { VSCodeLink } from "@vscode/webview-ui-toolkit/react"
import debounce from "debounce"
import { useMemo, useState, useCallback, useEffect, useRef } from "react"
import { useMount } from "react-use"
import { CaretSortIcon, CheckIcon } from "@radix-ui/react-icons"
import { VSCodeLink } from "@vscode/webview-ui-toolkit/react"
import { cn } from "@/lib/utils"
import {
Button,
Command,
CommandEmpty,
CommandGroup,
CommandInput,
CommandItem,
CommandList,
Popover,
PopoverContent,
PopoverTrigger,
} from "@/components/ui"
import { Combobox, ComboboxContent, ComboboxEmpty, ComboboxInput, ComboboxItem } from "@/components/ui/combobox"
import { ApiConfiguration, ModelInfo } from "../../../../src/shared/api"
import { useExtensionState } from "../../context/ExtensionStateContext"
import { vscode } from "../../utils/vscode"
import { normalizeApiConfiguration } from "./ApiOptions"
import { ThinkingBudget } from "./ThinkingBudget"
import { ModelInfoView } from "./ModelInfoView"
type ModelProvider = "glama" | "openRouter" | "unbound" | "requesty" | "openAi"
type ExtractType<T> = NonNullable<
{ [K in keyof ApiConfiguration]: Required<ApiConfiguration>[K] extends T ? K : never }[keyof ApiConfiguration]
>
type ModelKeys<T extends ModelProvider> = `${T}Models`
type ConfigKeys<T extends ModelProvider> = `${T}ModelId`
type InfoKeys<T extends ModelProvider> = `${T}ModelInfo`
type RefreshMessageType<T extends ModelProvider> = `refresh${Capitalize<T>}Models`
type ModelIdKeys = NonNullable<
{ [K in keyof ApiConfiguration]: K extends `${string}ModelId` ? K : never }[keyof ApiConfiguration]
>
interface ModelPickerProps<T extends ModelProvider = ModelProvider> {
interface ModelPickerProps {
defaultModelId: string
modelsKey: ModelKeys<T>
configKey: ConfigKeys<T>
infoKey: InfoKeys<T>
refreshMessageType: RefreshMessageType<T>
refreshValues?: Record<string, any>
defaultModelInfo?: ModelInfo
models: Record<string, ModelInfo> | null
modelIdKey: ModelIdKeys
modelInfoKey: ExtractType<ModelInfo>
serviceName: string
serviceUrl: string
recommendedModel: string
allowCustomModel?: boolean
apiConfiguration: ApiConfiguration
setApiConfigurationField: <K extends keyof ApiConfiguration>(field: K, value: ApiConfiguration[K]) => void
}
export const ModelPicker = ({
defaultModelId,
modelsKey,
configKey,
infoKey,
refreshMessageType,
refreshValues,
models,
modelIdKey,
modelInfoKey,
serviceName,
serviceUrl,
recommendedModel,
allowCustomModel = false,
apiConfiguration,
setApiConfigurationField,
defaultModelInfo,
}: ModelPickerProps) => {
const [customModelId, setCustomModelId] = useState("")
const [isCustomModel, setIsCustomModel] = useState(false)
const [open, setOpen] = useState(false)
const [value, setValue] = useState(defaultModelId)
const [isDescriptionExpanded, setIsDescriptionExpanded] = useState(false)
const prevRefreshValuesRef = useRef<Record<string, any> | undefined>()
const isInitialized = useRef(false)
const { apiConfiguration, [modelsKey]: models, onUpdateApiConfig, setApiConfiguration } = useExtensionState()
const modelIds = useMemo(
() => (Array.isArray(models) ? models : Object.keys(models)).sort((a, b) => a.localeCompare(b)),
[models],
)
const modelIds = useMemo(() => Object.keys(models ?? {}).sort((a, b) => a.localeCompare(b)), [models])
const { selectedModelId, selectedModelInfo } = useMemo(
() => normalizeApiConfiguration(apiConfiguration),
[apiConfiguration],
)
const onSelectCustomModel = useCallback(
(modelId: string) => {
setCustomModelId(modelId)
const modelInfo = { id: modelId }
const apiConfig = { ...apiConfiguration, [configKey]: modelId, [infoKey]: modelInfo }
setApiConfiguration(apiConfig)
onUpdateApiConfig(apiConfig)
setValue(modelId)
setOpen(false)
setIsCustomModel(false)
},
[apiConfiguration, configKey, infoKey, onUpdateApiConfig, setApiConfiguration],
)
const onSelect = useCallback(
(modelId: string) => {
const modelInfo = Array.isArray(models)
? { id: modelId } // For OpenAI models which are just strings
: models[modelId] // For other models that have full info objects
const apiConfig = { ...apiConfiguration, [configKey]: modelId, [infoKey]: modelInfo }
setApiConfiguration(apiConfig)
onUpdateApiConfig(apiConfig)
setValue(modelId)
setOpen(false)
const modelInfo = models?.[modelId]
setApiConfigurationField(modelIdKey, modelId)
setApiConfigurationField(modelInfoKey, modelInfo ?? defaultModelInfo)
},
[apiConfiguration, configKey, infoKey, models, onUpdateApiConfig, setApiConfiguration],
[modelIdKey, modelInfoKey, models, setApiConfigurationField, defaultModelInfo],
)
const debouncedRefreshModels = useMemo(() => {
return debounce(() => {
const message = refreshValues
? { type: refreshMessageType, values: refreshValues }
: { type: refreshMessageType }
vscode.postMessage(message)
}, 100)
}, [refreshMessageType, refreshValues])
useMount(() => {
debouncedRefreshModels()
return () => debouncedRefreshModels.clear()
})
const inputValue = apiConfiguration[modelIdKey]
useEffect(() => {
if (!refreshValues) {
prevRefreshValuesRef.current = undefined
return
if (!inputValue && !isInitialized.current) {
const initialValue = modelIds.includes(selectedModelId) ? selectedModelId : defaultModelId
setApiConfigurationField(modelIdKey, initialValue)
}
// Check if all values in refreshValues are truthy
if (Object.values(refreshValues).some((value) => !value)) {
prevRefreshValuesRef.current = undefined
return
}
// Compare with previous values
const prevValues = prevRefreshValuesRef.current
if (prevValues && JSON.stringify(prevValues) === JSON.stringify(refreshValues)) {
return
}
prevRefreshValuesRef.current = refreshValues
debouncedRefreshModels()
}, [debouncedRefreshModels, refreshValues])
useEffect(() => setValue(selectedModelId), [selectedModelId])
isInitialized.current = true
}, [inputValue, modelIds, setApiConfigurationField, modelIdKey, selectedModelId, defaultModelId])
return (
<>
<div className="font-semibold">Model</div>
<Popover open={open} onOpenChange={setOpen}>
<PopoverTrigger asChild>
<Button variant="combobox" role="combobox" aria-expanded={open} className="w-full justify-between">
{value ?? "Select model..."}
<CaretSortIcon className="opacity-50" />
</Button>
</PopoverTrigger>
<PopoverContent align="start" className="p-0">
<Command>
<CommandInput placeholder="Search model..." className="h-9" />
<CommandList>
<CommandEmpty>No model found.</CommandEmpty>
<CommandGroup>
{modelIds.map((model) => (
<CommandItem key={model} value={model} onSelect={onSelect}>
{model}
<CheckIcon
className={cn("ml-auto", value === model ? "opacity-100" : "opacity-0")}
/>
</CommandItem>
))}
</CommandGroup>
{allowCustomModel && (
<CommandGroup heading="Custom">
<CommandItem
onSelect={() => {
setIsCustomModel(true)
setOpen(false)
}}>
+ Add custom model
</CommandItem>
</CommandGroup>
)}
</CommandList>
</Command>
</PopoverContent>
</Popover>
{selectedModelId && selectedModelInfo && (
<Combobox type="single" inputValue={inputValue} onInputValueChange={onSelect}>
<ComboboxInput placeholder="Search model..." data-testid="model-input" />
<ComboboxContent>
<ComboboxEmpty>No model found.</ComboboxEmpty>
{modelIds.map((model) => (
<ComboboxItem key={model} value={model}>
{model}
</ComboboxItem>
))}
</ComboboxContent>
</Combobox>
<ThinkingBudget
apiConfiguration={apiConfiguration}
setApiConfigurationField={setApiConfigurationField}
modelInfo={selectedModelInfo}
/>
{selectedModelId && selectedModelInfo && selectedModelId === inputValue && (
<ModelInfoView
selectedModelId={selectedModelId}
modelInfo={selectedModelInfo}
@ -194,31 +103,9 @@ export const ModelPicker = ({
{serviceName}.
</VSCodeLink>
If you're unsure which model to choose, Roo Code works best with{" "}
<VSCodeLink onClick={() => onSelect(recommendedModel)}>{recommendedModel}.</VSCodeLink>
<VSCodeLink onClick={() => onSelect(defaultModelId)}>{defaultModelId}.</VSCodeLink>
You can also try searching "free" for no-cost options currently available.
</p>
{allowCustomModel && isCustomModel && (
<div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
<div className="bg-[var(--vscode-editor-background)] p-6 rounded-lg w-96">
<h3 className="text-lg font-semibold mb-4">Add Custom Model</h3>
<input
type="text"
className="w-full p-2 mb-4 bg-[var(--vscode-input-background)] text-[var(--vscode-input-foreground)] border border-[var(--vscode-input-border)] rounded"
placeholder="Enter model ID"
value={customModelId}
onChange={(e) => setCustomModelId(e.target.value)}
/>
<div className="flex justify-end gap-2">
<Button variant="secondary" onClick={() => setIsCustomModel(false)}>
Cancel
</Button>
<Button onClick={() => onSelectCustomModel(customModelId)} disabled={!customModelId.trim()}>
Add
</Button>
</div>
</div>
</div>
)}
</>
)
}

View file

@ -1,27 +0,0 @@
import React from "react"
import { useExtensionState } from "../../context/ExtensionStateContext"
import { ModelPicker } from "./ModelPicker"
const OpenAiModelPicker: React.FC = () => {
const { apiConfiguration } = useExtensionState()
return (
<ModelPicker
defaultModelId={apiConfiguration?.openAiModelId || ""}
modelsKey="openAiModels"
configKey="openAiModelId"
infoKey="openAiModelInfo"
refreshMessageType="refreshOpenAiModels"
refreshValues={{
baseUrl: apiConfiguration?.openAiBaseUrl,
apiKey: apiConfiguration?.openAiApiKey,
}}
serviceName="OpenAI"
serviceUrl="https://platform.openai.com"
recommendedModel="gpt-4-turbo-preview"
allowCustomModel={true}
/>
)
}
export default OpenAiModelPicker

View file

@ -1,15 +0,0 @@
import { ModelPicker } from "./ModelPicker"
import { openRouterDefaultModelId } from "../../../../src/shared/api"
export const OpenRouterModelPicker = () => (
<ModelPicker
defaultModelId={openRouterDefaultModelId}
modelsKey="openRouterModels"
configKey="openRouterModelId"
infoKey="openRouterModelInfo"
refreshMessageType="refreshOpenRouterModels"
serviceName="OpenRouter"
serviceUrl="https://openrouter.ai/models"
recommendedModel="anthropic/claude-3.5-sonnet:beta"
/>
)

View file

@ -1,22 +0,0 @@
import { ModelPicker } from "./ModelPicker"
import { requestyDefaultModelId } from "../../../../src/shared/api"
import { useExtensionState } from "@/context/ExtensionStateContext"
export const RequestyModelPicker = () => {
const { apiConfiguration } = useExtensionState()
return (
<ModelPicker
defaultModelId={requestyDefaultModelId}
modelsKey="requestyModels"
configKey="requestyModelId"
infoKey="requestyModelInfo"
refreshMessageType="refreshRequestyModels"
refreshValues={{
apiKey: apiConfiguration?.requestyApiKey,
}}
serviceName="Requesty"
serviceUrl="https://requesty.ai"
recommendedModel="anthropic/claude-3-5-sonnet-latest"
/>
)
}

View file

@ -1,15 +1,7 @@
import { forwardRef, memo, useCallback, useEffect, useImperativeHandle, useMemo, useRef, useState } from "react"
import { VSCodeButton, VSCodeCheckbox, VSCodeLink, VSCodeTextField } from "@vscode/webview-ui-toolkit/react"
import { forwardRef, memo, useCallback, useEffect, useImperativeHandle, useRef, useState } from "react"
import { ExtensionStateContextType, useExtensionState } from "../../context/ExtensionStateContext"
import { validateApiConfiguration, validateModelId } from "../../utils/validate"
import { vscode } from "../../utils/vscode"
import ApiOptions from "./ApiOptions"
import ExperimentalFeature from "./ExperimentalFeature"
import { EXPERIMENT_IDS, experimentConfigsMap, ExperimentId } from "../../../../src/shared/experiments"
import ApiConfigManager from "./ApiConfigManager"
import { Dropdown } from "vscrui"
import type { DropdownOption } from "vscrui"
import { ApiConfiguration } from "../../../../src/shared/api"
import { Button, Dropdown, type DropdownOption } from "vscrui"
import {
AlertDialog,
AlertDialogContent,
@ -19,7 +11,16 @@ import {
AlertDialogAction,
AlertDialogHeader,
AlertDialogFooter,
} from "../ui/alert-dialog"
} from "@/components/ui"
import { vscode } from "../../utils/vscode"
import { ExtensionStateContextType, useExtensionState } from "../../context/ExtensionStateContext"
import { EXPERIMENT_IDS, experimentConfigsMap, ExperimentId } from "../../../../src/shared/experiments"
import { ApiConfiguration } from "../../../../src/shared/api"
import ExperimentalFeature from "./ExperimentalFeature"
import ApiConfigManager from "./ApiConfigManager"
import ApiOptions from "./ApiOptions"
type SettingsViewProps = {
onDone: () => void
@ -31,19 +32,17 @@ export interface SettingsViewRef {
const SettingsView = forwardRef<SettingsViewRef, SettingsViewProps>(({ onDone }, ref) => {
const extensionState = useExtensionState()
const [apiErrorMessage, setApiErrorMessage] = useState<string | undefined>(undefined)
const [modelIdErrorMessage, setModelIdErrorMessage] = useState<string | undefined>(undefined)
const [commandInput, setCommandInput] = useState("")
const [isDiscardDialogShow, setDiscardDialogShow] = useState(false)
const [cachedState, setCachedState] = useState(extensionState)
const [isChangeDetected, setChangeDetected] = useState(false)
const prevApiConfigName = useRef(extensionState.currentApiConfigName)
const confirmDialogHandler = useRef<() => void>()
const [errorMessage, setErrorMessage] = useState<string | undefined>(undefined)
// TODO: Reduce WebviewMessage/ExtensionState complexity
const { currentApiConfigName } = extensionState
const {
apiConfiguration,
alwaysAllowReadOnly,
allowedCommands,
alwaysAllowBrowser,
@ -68,17 +67,19 @@ const SettingsView = forwardRef<SettingsViewRef, SettingsViewProps>(({ onDone },
writeDelayMs,
} = cachedState
//Make sure apiConfiguration is initialized and managed by SettingsView
const apiConfiguration = useMemo(() => cachedState.apiConfiguration ?? {}, [cachedState.apiConfiguration])
useEffect(() => {
// Update only when currentApiConfigName is changed
// Expected to be triggered by loadApiConfiguration/upsertApiConfiguration
// Update only when currentApiConfigName is changed.
// Expected to be triggered by loadApiConfiguration/upsertApiConfiguration.
if (prevApiConfigName.current === currentApiConfigName) {
return
}
setCachedState((prevCachedState) => ({
...prevCachedState,
...extensionState,
}))
setCachedState((prevCachedState) => ({ ...prevCachedState, ...extensionState }))
prevApiConfigName.current = currentApiConfigName
// console.log("useEffect: currentApiConfigName changed, setChangeDetected -> false")
setChangeDetected(false)
}, [currentApiConfigName, extensionState, isChangeDetected])
@ -88,11 +89,10 @@ const SettingsView = forwardRef<SettingsViewRef, SettingsViewProps>(({ onDone },
if (prevState[field] === value) {
return prevState
}
// console.log(`setCachedStateField(${field} -> ${value}): setChangeDetected -> true`)
setChangeDetected(true)
return {
...prevState,
[field]: value,
}
return { ...prevState, [field]: value }
})
},
[],
@ -104,14 +104,11 @@ const SettingsView = forwardRef<SettingsViewRef, SettingsViewProps>(({ onDone },
if (prevState.apiConfiguration?.[field] === value) {
return prevState
}
// console.log(`setApiConfigurationField(${field} -> ${value}): setChangeDetected -> true`)
setChangeDetected(true)
return {
...prevState,
apiConfiguration: {
...prevState.apiConfiguration,
[field]: value,
},
}
return { ...prevState, apiConfiguration: { ...prevState.apiConfiguration, [field]: value } }
})
},
[],
@ -122,7 +119,10 @@ const SettingsView = forwardRef<SettingsViewRef, SettingsViewProps>(({ onDone },
if (prevState.experiments?.[id] === enabled) {
return prevState
}
// console.log("setExperimentEnabled: setChangeDetected -> true")
setChangeDetected(true)
return {
...prevState,
experiments: { ...prevState.experiments, [id]: enabled },
@ -130,17 +130,10 @@ const SettingsView = forwardRef<SettingsViewRef, SettingsViewProps>(({ onDone },
})
}, [])
const handleSubmit = () => {
const apiValidationResult = validateApiConfiguration(apiConfiguration)
const modelIdValidationResult = validateModelId(
apiConfiguration,
extensionState.glamaModels,
extensionState.openRouterModels,
)
const isSettingValid = !errorMessage
setApiErrorMessage(apiValidationResult)
setModelIdErrorMessage(modelIdValidationResult)
if (!apiValidationResult && !modelIdValidationResult) {
const handleSubmit = () => {
if (isSettingValid) {
vscode.postMessage({ type: "alwaysAllowReadOnly", bool: alwaysAllowReadOnly })
vscode.postMessage({ type: "alwaysAllowWrite", bool: alwaysAllowWrite })
vscode.postMessage({ type: "alwaysAllowExecute", bool: alwaysAllowExecute })
@ -162,39 +155,14 @@ const SettingsView = forwardRef<SettingsViewRef, SettingsViewProps>(({ onDone },
vscode.postMessage({ type: "rateLimitSeconds", value: rateLimitSeconds })
vscode.postMessage({ type: "maxOpenTabsContext", value: maxOpenTabsContext })
vscode.postMessage({ type: "currentApiConfigName", text: currentApiConfigName })
vscode.postMessage({
type: "updateExperimental",
values: experiments,
})
vscode.postMessage({ type: "updateExperimental", values: experiments })
vscode.postMessage({ type: "alwaysAllowModeSwitch", bool: alwaysAllowModeSwitch })
vscode.postMessage({
type: "upsertApiConfiguration",
text: currentApiConfigName,
apiConfiguration,
})
// onDone()
vscode.postMessage({ type: "upsertApiConfiguration", text: currentApiConfigName, apiConfiguration })
// console.log("handleSubmit: setChangeDetected -> false")
setChangeDetected(false)
}
}
useEffect(() => {
setApiErrorMessage(undefined)
setModelIdErrorMessage(undefined)
}, [apiConfiguration])
// Initial validation on mount
useEffect(() => {
const apiValidationResult = validateApiConfiguration(apiConfiguration)
const modelIdValidationResult = validateModelId(
apiConfiguration,
extensionState.glamaModels,
extensionState.openRouterModels,
)
setApiErrorMessage(apiValidationResult)
setModelIdErrorMessage(modelIdValidationResult)
}, [apiConfiguration, extensionState.glamaModels, extensionState.openRouterModels])
const checkUnsaveChanges = useCallback(
(then: () => void) => {
if (isChangeDetected) {
@ -207,13 +175,7 @@ const SettingsView = forwardRef<SettingsViewRef, SettingsViewProps>(({ onDone },
[isChangeDetected],
)
useImperativeHandle(
ref,
() => ({
checkUnsaveChanges,
}),
[checkUnsaveChanges],
)
useImperativeHandle(ref, () => ({ checkUnsaveChanges }), [checkUnsaveChanges])
const onConfirmDialogResult = useCallback((confirm: boolean) => {
if (confirm) {
@ -231,10 +193,7 @@ const SettingsView = forwardRef<SettingsViewRef, SettingsViewProps>(({ onDone },
const newCommands = [...currentCommands, commandInput]
setCachedStateField("allowedCommands", newCommands)
setCommandInput("")
vscode.postMessage({
type: "allowedCommands",
commands: newCommands,
})
vscode.postMessage({ type: "allowedCommands", commands: newCommands })
}
}
@ -288,13 +247,14 @@ const SettingsView = forwardRef<SettingsViewRef, SettingsViewProps>(({ onDone },
justifyContent: "space-between",
gap: "6px",
}}>
<VSCodeButton
appearance="primary"
title={isChangeDetected ? "Save changes" : "Nothing changed"}
<Button
appearance={isSettingValid ? "primary" : "secondary"}
className={!isSettingValid ? "!border-vscode-errorForeground" : ""}
title={!isSettingValid ? errorMessage : isChangeDetected ? "Save changes" : "Nothing changed"}
onClick={handleSubmit}
disabled={!isChangeDetected}>
disabled={!isChangeDetected || !isSettingValid}>
Save
</VSCodeButton>
</Button>
<VSCodeButton
appearance="secondary"
title="Discard unsaved changes and close settings panel"
@ -345,8 +305,8 @@ const SettingsView = forwardRef<SettingsViewRef, SettingsViewProps>(({ onDone },
uriScheme={extensionState.uriScheme}
apiConfiguration={apiConfiguration}
setApiConfigurationField={setApiConfigurationField}
apiErrorMessage={apiErrorMessage}
modelIdErrorMessage={modelIdErrorMessage}
errorMessage={errorMessage}
setErrorMessage={setErrorMessage}
/>
</div>
</div>
@ -765,7 +725,7 @@ const SettingsView = forwardRef<SettingsViewRef, SettingsViewProps>(({ onDone },
color: "var(--vscode-descriptionForeground)",
}}>
When enabled, Roo will be able to edit files more quickly and will automatically reject
truncated full-file writes. Works best with the latest Claude 3.5 Sonnet model.
truncated full-file writes. Works best with the latest Claude 3.7 Sonnet model.
</p>
{diffEnabled && (

View file

@ -1,167 +0,0 @@
import { VSCodeButton } from "@vscode/webview-ui-toolkit/react"
import React, { useState } from "react"
export const TAB_NAVBAR_HEIGHT = 24
const BUTTON_MARGIN_RIGHT = "3px"
const LAST_BUTTON_MARGIN_RIGHT = "13px"
type TabNavbarProps = {
onPlusClick: () => void
onHistoryClick: () => void
onSettingsClick: () => void
}
type TooltipProps = {
text: string
isVisible: boolean
position: { x: number; y: number }
align?: "left" | "center" | "right"
}
const Tooltip: React.FC<TooltipProps> = ({ text, isVisible, position, align = "center" }) => {
let leftPosition = position.x
let triangleStyle: React.CSSProperties = {
left: "50%",
marginLeft: "-5px",
}
if (align === "right") {
leftPosition = position.x - 10 // Adjust this value as needed
triangleStyle = {
right: "10px", // Adjust this value to match the tooltip's right padding
marginLeft: "0",
}
} else if (align === "left") {
leftPosition = position.x + 10 // Adjust this value as needed
triangleStyle = {
left: "10px", // Adjust this value to match the tooltip's left padding
marginLeft: "0",
}
}
return (
<div
style={{
position: "fixed",
top: `${position.y}px`,
left: align === "center" ? leftPosition + "px" : "auto",
right: align === "right" ? "10px" : "auto", // Ensure 10px from screen edge
transform: align === "center" ? "translateX(-50%)" : "none",
opacity: isVisible ? 1 : 0,
visibility: isVisible ? "visible" : "hidden",
transition: "opacity 0.1s ease-out 0.1s, visibility 0.1s ease-out 0.1s",
backgroundColor: "var(--vscode-editorHoverWidget-background)",
color: "var(--vscode-editorHoverWidget-foreground)",
padding: "4px 8px",
borderRadius: "3px",
fontSize: "12px",
pointerEvents: "none",
zIndex: 1000,
boxShadow: "0 2px 8px var(--vscode-widget-shadow)",
border: "1px solid var(--vscode-editorHoverWidget-border)",
textAlign: "center",
whiteSpace: "nowrap",
}}>
<div
style={{
position: "absolute",
top: "-5px",
...triangleStyle,
borderLeft: "5px solid transparent",
borderRight: "5px solid transparent",
borderBottom: "5px solid var(--vscode-editorHoverWidget-border)",
}}
/>
<div
style={{
position: "absolute",
top: "-4px",
...triangleStyle,
borderLeft: "5px solid transparent",
borderRight: "5px solid transparent",
borderBottom: "5px solid var(--vscode-editorHoverWidget-background)",
}}
/>
{text}
</div>
)
}
const TabNavbar = ({ onPlusClick, onHistoryClick, onSettingsClick }: TabNavbarProps) => {
const [tooltip, setTooltip] = useState<TooltipProps>({
text: "",
isVisible: false,
position: { x: 0, y: 0 },
align: "center",
})
const showTooltip = (text: string, event: React.MouseEvent, align: "left" | "center" | "right" = "center") => {
const rect = event.currentTarget.getBoundingClientRect()
setTooltip({
text,
isVisible: true,
position: { x: rect.left + rect.width / 2, y: rect.bottom + 7 },
align,
})
}
const hideTooltip = () => {
setTooltip((prev) => ({ ...prev, isVisible: false }))
}
const buttonStyle = {
marginRight: BUTTON_MARGIN_RIGHT,
}
const lastButtonStyle = {
...buttonStyle,
marginRight: LAST_BUTTON_MARGIN_RIGHT,
}
return (
<>
<div
style={{
position: "absolute",
top: 4,
right: 0,
left: 0,
height: TAB_NAVBAR_HEIGHT,
display: "flex",
justifyContent: "flex-end",
alignItems: "center",
}}>
<VSCodeButton
appearance="icon"
onClick={onPlusClick}
style={buttonStyle}
onMouseEnter={(e) => showTooltip("New Chat", e, "center")}
onMouseLeave={hideTooltip}
onMouseMove={(e) => showTooltip("New Chat", e, "center")}>
<span className="codicon codicon-add"></span>
</VSCodeButton>
<VSCodeButton
appearance="icon"
onClick={onHistoryClick}
style={buttonStyle}
onMouseEnter={(e) => showTooltip("History", e, "center")}
onMouseLeave={hideTooltip}
onMouseMove={(e) => showTooltip("History", e, "center")}>
<span className="codicon codicon-history"></span>
</VSCodeButton>
<VSCodeButton
appearance="icon"
onClick={onSettingsClick}
style={lastButtonStyle}
onMouseEnter={(e) => showTooltip("Settings", e, "right")}
onMouseLeave={hideTooltip}
onMouseMove={(e) => showTooltip("Settings", e, "right")}>
<span className="codicon codicon-settings-gear"></span>
</VSCodeButton>
</div>
<Tooltip {...tooltip} />
</>
)
}
export default TabNavbar

View file

@ -0,0 +1,29 @@
import { Slider } from "@/components/ui"
import { ApiConfiguration, ModelInfo, THINKING_BUDGET } from "../../../../src/shared/api"
interface ThinkingBudgetProps {
apiConfiguration: ApiConfiguration
setApiConfigurationField: <K extends keyof ApiConfiguration>(field: K, value: ApiConfiguration[K]) => void
modelInfo?: ModelInfo
}
export const ThinkingBudget = ({ apiConfiguration, setApiConfigurationField, modelInfo }: ThinkingBudgetProps) => {
const budget = apiConfiguration?.anthropicThinking ?? THINKING_BUDGET.default
return modelInfo && modelInfo.thinking ? (
<div className="flex flex-col gap-1 mt-2">
<div className="font-medium">Thinking Budget</div>
<div className="flex items-center gap-1">
<Slider
min={THINKING_BUDGET.min}
max={(modelInfo.maxTokens ?? THINKING_BUDGET.default) - 1}
step={THINKING_BUDGET.step}
value={[budget]}
onValueChange={(value) => setApiConfigurationField("anthropicThinking", value[0])}
/>
<div className="w-12 text-sm text-center">{budget}</div>
</div>
</div>
) : null
}

View file

@ -1,15 +0,0 @@
import { ModelPicker } from "./ModelPicker"
import { unboundDefaultModelId } from "../../../../src/shared/api"
export const UnboundModelPicker = () => (
<ModelPicker
defaultModelId={unboundDefaultModelId}
modelsKey="unboundModels"
configKey="unboundModelId"
infoKey="unboundModelInfo"
refreshMessageType="refreshUnboundModels"
serviceName="Unbound"
serviceUrl="https://api.getunbound.ai/models"
recommendedModel={unboundDefaultModelId}
/>
)

View file

@ -51,6 +51,8 @@ describe("ApiOptions", () => {
render(
<ExtensionStateContextProvider>
<ApiOptions
errorMessage={undefined}
setErrorMessage={() => {}}
uriScheme={undefined}
apiConfiguration={{}}
setApiConfigurationField={() => {}}
@ -69,4 +71,6 @@ describe("ApiOptions", () => {
renderApiOptions({ fromWelcomeView: true })
expect(screen.queryByTestId("temperature-control")).not.toBeInTheDocument()
})
//TODO: More test cases needed
})

View file

@ -3,7 +3,6 @@
import { screen, fireEvent, render } from "@testing-library/react"
import { act } from "react"
import { ModelPicker } from "../ModelPicker"
import { useExtensionState } from "../../../context/ExtensionStateContext"
jest.mock("../../../context/ExtensionStateContext", () => ({
useExtensionState: jest.fn(),
@ -20,36 +19,40 @@ global.ResizeObserver = MockResizeObserver
Element.prototype.scrollIntoView = jest.fn()
describe("ModelPicker", () => {
const mockOnUpdateApiConfig = jest.fn()
const mockSetApiConfiguration = jest.fn()
const mockSetApiConfigurationField = jest.fn()
const modelInfo = {
maxTokens: 8192,
contextWindow: 200_000,
supportsImages: true,
supportsComputerUse: true,
supportsPromptCache: true,
inputPrice: 3.0,
outputPrice: 15.0,
cacheWritesPrice: 3.75,
cacheReadsPrice: 0.3,
}
const mockModels = {
model1: { name: "Model 1", description: "Test model 1", ...modelInfo },
model2: { name: "Model 2", description: "Test model 2", ...modelInfo },
}
const defaultProps = {
apiConfiguration: {},
defaultModelId: "model1",
modelsKey: "glamaModels" as const,
configKey: "glamaModelId" as const,
infoKey: "glamaModelInfo" as const,
refreshMessageType: "refreshGlamaModels" as const,
defaultModelInfo: modelInfo,
modelIdKey: "glamaModelId" as const,
modelInfoKey: "glamaModelInfo" as const,
serviceName: "Test Service",
serviceUrl: "https://test.service",
recommendedModel: "recommended-model",
}
const mockModels = {
model1: { name: "Model 1", description: "Test model 1" },
model2: { name: "Model 2", description: "Test model 2" },
models: mockModels,
setApiConfigurationField: mockSetApiConfigurationField,
}
beforeEach(() => {
jest.clearAllMocks()
;(useExtensionState as jest.Mock).mockReturnValue({
apiConfiguration: {},
setApiConfiguration: mockSetApiConfiguration,
glamaModels: mockModels,
onUpdateApiConfig: mockOnUpdateApiConfig,
})
})
it("calls onUpdateApiConfig when a model is selected", async () => {
it("calls setApiConfigurationField when a model is selected", async () => {
await act(async () => {
render(<ModelPicker {...defaultProps} />)
})
@ -67,20 +70,12 @@ describe("ModelPicker", () => {
await act(async () => {
// Find and click the model item by its value.
const modelItem = screen.getByRole("option", { name: "model2" })
fireEvent.click(modelItem)
const modelItem = screen.getByTestId("model-input")
fireEvent.input(modelItem, { target: { value: "model2" } })
})
// Verify the API config was updated.
expect(mockSetApiConfiguration).toHaveBeenCalledWith({
glamaModelId: "model2",
glamaModelInfo: mockModels["model2"],
})
// Verify onUpdateApiConfig was called with the new config.
expect(mockOnUpdateApiConfig).toHaveBeenCalledWith({
glamaModelId: "model2",
glamaModelInfo: mockModels["model2"],
})
expect(mockSetApiConfigurationField).toHaveBeenCalledWith(defaultProps.modelIdKey, "model2")
expect(mockSetApiConfigurationField).toHaveBeenCalledWith(defaultProps.modelInfoKey, mockModels.model2)
})
})

View file

@ -4,94 +4,97 @@ import * as AlertDialogPrimitive from "@radix-ui/react-alert-dialog"
import { cn } from "@/lib/utils"
import { buttonVariants } from "@/components/ui/button"
const AlertDialog = AlertDialogPrimitive.Root
function AlertDialog({ ...props }: React.ComponentProps<typeof AlertDialogPrimitive.Root>) {
return <AlertDialogPrimitive.Root data-slot="alert-dialog" {...props} />
}
const AlertDialogTrigger = AlertDialogPrimitive.Trigger
function AlertDialogTrigger({ ...props }: React.ComponentProps<typeof AlertDialogPrimitive.Trigger>) {
return <AlertDialogPrimitive.Trigger data-slot="alert-dialog-trigger" {...props} />
}
const AlertDialogPortal = AlertDialogPrimitive.Portal
function AlertDialogPortal({ ...props }: React.ComponentProps<typeof AlertDialogPrimitive.Portal>) {
return <AlertDialogPrimitive.Portal data-slot="alert-dialog-portal" {...props} />
}
const AlertDialogOverlay = React.forwardRef<
React.ElementRef<typeof AlertDialogPrimitive.Overlay>,
React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Overlay>
>(({ className, ...props }, ref) => (
<AlertDialogPrimitive.Overlay
className={cn(
"fixed inset-0 z-50 bg-black/50 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",
className,
)}
{...props}
ref={ref}
/>
))
AlertDialogOverlay.displayName = AlertDialogPrimitive.Overlay.displayName
const AlertDialogContent = React.forwardRef<
React.ElementRef<typeof AlertDialogPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Content>
>(({ className, ...props }, ref) => (
<AlertDialogPortal>
<AlertDialogOverlay />
<AlertDialogPrimitive.Content
ref={ref}
function AlertDialogOverlay({ className, ...props }: React.ComponentProps<typeof AlertDialogPrimitive.Overlay>) {
return (
<AlertDialogPrimitive.Overlay
data-slot="alert-dialog-overlay"
className={cn(
"fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-vscode-editor-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] rounded-lg",
"data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/50",
className,
)}
{...props}
/>
</AlertDialogPortal>
))
AlertDialogContent.displayName = AlertDialogPrimitive.Content.displayName
)
}
const AlertDialogHeader = ({ className, ...props }: React.HTMLAttributes<HTMLDivElement>) => (
<div className={cn("flex flex-col space-y-2 text-left", className)} {...props} />
)
AlertDialogHeader.displayName = "AlertDialogHeader"
function AlertDialogContent({ className, ...props }: React.ComponentProps<typeof AlertDialogPrimitive.Content>) {
return (
<AlertDialogPortal>
<AlertDialogOverlay />
<AlertDialogPrimitive.Content
data-slot="alert-dialog-content"
className={cn(
"bg-background data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border p-6 shadow-lg duration-200 sm:max-w-lg",
className,
)}
{...props}
/>
</AlertDialogPortal>
)
}
const AlertDialogFooter = ({ className, ...props }: React.HTMLAttributes<HTMLDivElement>) => (
<div className={cn("flex flex-row justify-end space-x-2", className)} {...props} />
)
AlertDialogFooter.displayName = "AlertDialogFooter"
function AlertDialogHeader({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="alert-dialog-header"
className={cn("flex flex-col gap-2 text-center sm:text-left", className)}
{...props}
/>
)
}
const AlertDialogTitle = React.forwardRef<
React.ElementRef<typeof AlertDialogPrimitive.Title>,
React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Title>
>(({ className, ...props }, ref) => (
<AlertDialogPrimitive.Title ref={ref} className={cn("text-lg font-semibold", className)} {...props} />
))
AlertDialogTitle.displayName = AlertDialogPrimitive.Title.displayName
function AlertDialogFooter({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="alert-dialog-footer"
className={cn("flex flex-col-reverse gap-2 sm:flex-row sm:justify-end", className)}
{...props}
/>
)
}
const AlertDialogDescription = React.forwardRef<
React.ElementRef<typeof AlertDialogPrimitive.Description>,
React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Description>
>(({ className, ...props }, ref) => (
<AlertDialogPrimitive.Description
ref={ref}
className={cn("text-base text-muted-foreground", className)}
{...props}
/>
))
AlertDialogDescription.displayName = AlertDialogPrimitive.Description.displayName
function AlertDialogTitle({ className, ...props }: React.ComponentProps<typeof AlertDialogPrimitive.Title>) {
return (
<AlertDialogPrimitive.Title
data-slot="alert-dialog-title"
className={cn("text-lg font-semibold", className)}
{...props}
/>
)
}
const AlertDialogAction = React.forwardRef<
React.ElementRef<typeof AlertDialogPrimitive.Action>,
React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Action>
>(({ className, ...props }, ref) => (
<AlertDialogPrimitive.Action ref={ref} className={cn(buttonVariants(), className)} {...props} />
))
AlertDialogAction.displayName = AlertDialogPrimitive.Action.displayName
function AlertDialogDescription({
className,
...props
}: React.ComponentProps<typeof AlertDialogPrimitive.Description>) {
return (
<AlertDialogPrimitive.Description
data-slot="alert-dialog-description"
className={cn("text-muted-foreground text-sm", className)}
{...props}
/>
)
}
const AlertDialogCancel = React.forwardRef<
React.ElementRef<typeof AlertDialogPrimitive.Cancel>,
React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Cancel>
>(({ className, ...props }, ref) => (
<AlertDialogPrimitive.Cancel
ref={ref}
className={cn(buttonVariants({ variant: "secondary" }), "mt-0", className)}
{...props}
/>
))
AlertDialogCancel.displayName = AlertDialogPrimitive.Cancel.displayName
function AlertDialogAction({ className, ...props }: React.ComponentProps<typeof AlertDialogPrimitive.Action>) {
return <AlertDialogPrimitive.Action className={cn(buttonVariants(), className)} {...props} />
}
function AlertDialogCancel({ className, ...props }: React.ComponentProps<typeof AlertDialogPrimitive.Cancel>) {
return <AlertDialogPrimitive.Cancel className={cn(buttonVariants({ variant: "outline" }), className)} {...props} />
}
export {
AlertDialog,

View file

@ -0,0 +1,522 @@
/* eslint-disable react/jsx-pascal-case */
"use client"
import * as React from "react"
import { composeEventHandlers } from "@radix-ui/primitive"
import { useComposedRefs } from "@radix-ui/react-compose-refs"
import * as PopoverPrimitive from "@radix-ui/react-popover"
import { Primitive } from "@radix-ui/react-primitive"
import * as RovingFocusGroupPrimitive from "@radix-ui/react-roving-focus"
import { useControllableState } from "@radix-ui/react-use-controllable-state"
import { Command as CommandPrimitive } from "cmdk"
export type ComboboxContextProps = {
inputValue: string
onInputValueChange: (inputValue: string, reason: "inputChange" | "itemSelect" | "clearClick") => void
onInputBlur?: (e: React.FocusEvent<HTMLInputElement, Element>) => void
open: boolean
onOpenChange: (open: boolean) => void
currentTabStopId: string | null
onCurrentTabStopIdChange: (currentTabStopId: string | null) => void
inputRef: React.RefObject<HTMLInputElement>
tagGroupRef: React.RefObject<React.ElementRef<typeof RovingFocusGroupPrimitive.Root>>
disabled?: boolean
required?: boolean
} & (
| Required<Pick<ComboboxSingleProps, "type" | "value" | "onValueChange">>
| Required<Pick<ComboboxMultipleProps, "type" | "value" | "onValueChange">>
)
const ComboboxContext = React.createContext<ComboboxContextProps>({
type: "single",
value: "",
onValueChange: () => {},
inputValue: "",
onInputValueChange: () => {},
onInputBlur: () => {},
open: false,
onOpenChange: () => {},
currentTabStopId: null,
onCurrentTabStopIdChange: () => {},
inputRef: { current: null },
tagGroupRef: { current: null },
disabled: false,
required: false,
})
export const useComboboxContext = () => React.useContext(ComboboxContext)
export type ComboboxType = "single" | "multiple"
export interface ComboboxBaseProps
extends React.ComponentProps<typeof PopoverPrimitive.Root>,
Omit<React.ComponentProps<typeof CommandPrimitive>, "value" | "defaultValue" | "onValueChange"> {
type?: ComboboxType | undefined
inputValue?: string
defaultInputValue?: string
onInputValueChange?: (inputValue: string, reason: "inputChange" | "itemSelect" | "clearClick") => void
onInputBlur?: (e: React.FocusEvent<HTMLInputElement, Element>) => void
disabled?: boolean
required?: boolean
}
export type ComboboxValue<T extends ComboboxType = "single"> = T extends "single"
? string
: T extends "multiple"
? string[]
: never
export interface ComboboxSingleProps {
type: "single"
value?: string
defaultValue?: string
onValueChange?: (value: string) => void
}
export interface ComboboxMultipleProps {
type: "multiple"
value?: string[]
defaultValue?: string[]
onValueChange?: (value: string[]) => void
}
export type ComboboxProps = ComboboxBaseProps & (ComboboxSingleProps | ComboboxMultipleProps)
export const Combobox = React.forwardRef(
<T extends ComboboxType = "single">(
{
type = "single" as T,
open: openProp,
onOpenChange,
defaultOpen,
modal,
children,
value: valueProp,
defaultValue,
onValueChange,
inputValue: inputValueProp,
defaultInputValue,
onInputValueChange,
onInputBlur,
disabled,
required,
...props
}: ComboboxProps,
ref: React.ForwardedRef<React.ElementRef<typeof CommandPrimitive>>,
) => {
const [value = type === "multiple" ? [] : "", setValue] = useControllableState<ComboboxValue<T>>({
prop: valueProp as ComboboxValue<T>,
defaultProp: defaultValue as ComboboxValue<T>,
onChange: onValueChange as (value: ComboboxValue<T>) => void,
})
const [inputValue = "", setInputValue] = useControllableState({
prop: inputValueProp,
defaultProp: defaultInputValue,
})
const [open = false, setOpen] = useControllableState({
prop: openProp,
defaultProp: defaultOpen,
onChange: onOpenChange,
})
const [currentTabStopId, setCurrentTabStopId] = React.useState<string | null>(null)
const inputRef = React.useRef<HTMLInputElement>(null)
const tagGroupRef = React.useRef<React.ElementRef<typeof RovingFocusGroupPrimitive.Root>>(null)
const handleInputValueChange: ComboboxContextProps["onInputValueChange"] = React.useCallback(
(inputValue, reason) => {
setInputValue(inputValue)
onInputValueChange?.(inputValue, reason)
},
[setInputValue, onInputValueChange],
)
return (
<ComboboxContext.Provider
value={
{
type,
value,
onValueChange: setValue,
inputValue,
onInputValueChange: handleInputValueChange,
onInputBlur,
open,
onOpenChange: setOpen,
currentTabStopId,
onCurrentTabStopIdChange: setCurrentTabStopId,
inputRef,
tagGroupRef,
disabled,
required,
} as ComboboxContextProps
}>
<PopoverPrimitive.Root open={open} onOpenChange={setOpen} modal={modal}>
<CommandPrimitive ref={ref} {...props}>
{children}
{!open && <CommandPrimitive.List aria-hidden hidden />}
</CommandPrimitive>
</PopoverPrimitive.Root>
</ComboboxContext.Provider>
)
},
)
Combobox.displayName = "Combobox"
export const ComboboxTagGroup = React.forwardRef<
React.ElementRef<typeof RovingFocusGroupPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof RovingFocusGroupPrimitive.Root>
>((props, ref) => {
const { currentTabStopId, onCurrentTabStopIdChange, tagGroupRef, type } = useComboboxContext()
if (type !== "multiple") {
throw new Error('<ComboboxTagGroup> should only be used when type is "multiple"')
}
const composedRefs = useComposedRefs(ref, tagGroupRef)
return (
<RovingFocusGroupPrimitive.Root
ref={composedRefs}
tabIndex={-1}
currentTabStopId={currentTabStopId}
onCurrentTabStopIdChange={onCurrentTabStopIdChange}
onBlur={() => onCurrentTabStopIdChange(null)}
{...props}
/>
)
})
ComboboxTagGroup.displayName = "ComboboxTagGroup"
export interface ComboboxTagGroupItemProps
extends React.ComponentPropsWithoutRef<typeof RovingFocusGroupPrimitive.Item> {
value: string
disabled?: boolean
}
const ComboboxTagGroupItemContext = React.createContext<Pick<ComboboxTagGroupItemProps, "value" | "disabled">>({
value: "",
disabled: false,
})
const useComboboxTagGroupItemContext = () => React.useContext(ComboboxTagGroupItemContext)
export const ComboboxTagGroupItem = React.forwardRef<
React.ElementRef<typeof RovingFocusGroupPrimitive.Item>,
ComboboxTagGroupItemProps
>(({ onClick, onKeyDown, value: valueProp, disabled, ...props }, ref) => {
const { value, onValueChange, inputRef, currentTabStopId, type } = useComboboxContext()
if (type !== "multiple") {
throw new Error('<ComboboxTagGroupItem> should only be used when type is "multiple"')
}
const lastItemValue = value.at(-1)
return (
<ComboboxTagGroupItemContext.Provider value={{ value: valueProp, disabled }}>
<RovingFocusGroupPrimitive.Item
ref={ref}
onKeyDown={composeEventHandlers(onKeyDown, (event) => {
if (event.key === "Escape") {
inputRef.current?.focus()
}
if (event.key === "ArrowUp" || event.key === "ArrowDown") {
event.preventDefault()
inputRef.current?.focus()
}
if (event.key === "ArrowRight" && currentTabStopId === lastItemValue) {
inputRef.current?.focus()
}
if (event.key === "Backspace" || event.key === "Delete") {
onValueChange(value.filter((v) => v !== currentTabStopId))
inputRef.current?.focus()
}
})}
onClick={composeEventHandlers(onClick, () => disabled && inputRef.current?.focus())}
tabStopId={valueProp}
focusable={!disabled}
data-disabled={disabled}
active={valueProp === lastItemValue}
{...props}
/>
</ComboboxTagGroupItemContext.Provider>
)
})
ComboboxTagGroupItem.displayName = "ComboboxTagGroupItem"
export const ComboboxTagGroupItemRemove = React.forwardRef<
React.ElementRef<typeof Primitive.button>,
React.ComponentPropsWithoutRef<typeof Primitive.button>
>(({ onClick, ...props }, ref) => {
const { value, onValueChange, type } = useComboboxContext()
if (type !== "multiple") {
throw new Error('<ComboboxTagGroupItemRemove> should only be used when type is "multiple"')
}
const { value: valueProp, disabled } = useComboboxTagGroupItemContext()
return (
<Primitive.button
ref={ref}
aria-hidden
tabIndex={-1}
disabled={disabled}
onClick={composeEventHandlers(onClick, () => onValueChange(value.filter((v) => v !== valueProp)))}
{...props}
/>
)
})
ComboboxTagGroupItemRemove.displayName = "ComboboxTagGroupItemRemove"
export const ComboboxInput = React.forwardRef<
React.ElementRef<typeof CommandPrimitive.Input>,
Omit<React.ComponentProps<typeof CommandPrimitive.Input>, "value" | "onValueChange">
>(({ onKeyDown, onMouseDown, onFocus, onBlur, ...props }, ref) => {
const {
type,
inputValue,
onInputValueChange,
onInputBlur,
open,
onOpenChange,
value,
onValueChange,
inputRef,
disabled,
required,
tagGroupRef,
} = useComboboxContext()
const composedRefs = useComposedRefs(ref, inputRef)
return (
<CommandPrimitive.Input
ref={composedRefs}
disabled={disabled}
required={required}
value={inputValue}
onValueChange={(search) => {
if (!open) {
onOpenChange(true)
}
// Schedule input value change to the next tick.
setTimeout(() => onInputValueChange(search, "inputChange"))
if (!search && type === "single") {
onValueChange("")
}
}}
onKeyDown={composeEventHandlers(onKeyDown, (event) => {
if (event.key === "ArrowUp" || event.key === "ArrowDown") {
if (!open) {
event.preventDefault()
onOpenChange(true)
}
}
if (type !== "multiple") {
return
}
if (event.key === "ArrowLeft" && !inputValue && value.length) {
tagGroupRef.current?.focus()
}
if (event.key === "Backspace" && !inputValue) {
onValueChange(value.slice(0, -1))
}
})}
onMouseDown={composeEventHandlers(onMouseDown, () => onOpenChange(!!inputValue || !open))}
onFocus={composeEventHandlers(onFocus, () => onOpenChange(true))}
onBlur={composeEventHandlers(onBlur, (event) => {
if (!event.relatedTarget?.hasAttribute("cmdk-list")) {
onInputBlur?.(event)
}
})}
{...props}
/>
)
})
ComboboxInput.displayName = "ComboboxInput"
export const ComboboxClear = React.forwardRef<
React.ElementRef<typeof Primitive.button>,
React.ComponentPropsWithoutRef<typeof Primitive.button>
>(({ onClick, ...props }, ref) => {
const { value, onValueChange, inputValue, onInputValueChange, type } = useComboboxContext()
const isValueEmpty = type === "single" ? !value : !value.length
return (
<Primitive.button
ref={ref}
disabled={isValueEmpty && !inputValue}
onClick={composeEventHandlers(onClick, () => {
if (type === "single") {
onValueChange("")
} else {
onValueChange([])
}
onInputValueChange("", "clearClick")
})}
{...props}
/>
)
})
ComboboxClear.displayName = "ComboboxClear"
export const ComboboxTrigger = PopoverPrimitive.Trigger
export const ComboboxAnchor = PopoverPrimitive.Anchor
export const ComboboxPortal = PopoverPrimitive.Portal
export const ComboboxContent = React.forwardRef<
React.ElementRef<typeof PopoverPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof PopoverPrimitive.Content>
>(({ children, onOpenAutoFocus, onInteractOutside, ...props }, ref) => (
<PopoverPrimitive.Content
asChild
ref={ref}
onOpenAutoFocus={composeEventHandlers(onOpenAutoFocus, (event) => event.preventDefault())}
onCloseAutoFocus={composeEventHandlers(onOpenAutoFocus, (event) => event.preventDefault())}
onInteractOutside={composeEventHandlers(onInteractOutside, (event) => {
if (event.target instanceof Element && event.target.hasAttribute("cmdk-input")) {
event.preventDefault()
}
})}
{...props}>
<CommandPrimitive.List>{children}</CommandPrimitive.List>
</PopoverPrimitive.Content>
))
ComboboxContent.displayName = "ComboboxContent"
export const ComboboxEmpty = CommandPrimitive.Empty
export const ComboboxLoading = CommandPrimitive.Loading
export interface ComboboxItemProps extends Omit<React.ComponentPropsWithoutRef<typeof CommandPrimitive.Item>, "value"> {
value: string
}
const ComboboxItemContext = React.createContext({ isSelected: false })
const useComboboxItemContext = () => React.useContext(ComboboxItemContext)
const findComboboxItemText = (children: React.ReactNode) => {
let text = ""
React.Children.forEach(children, (child) => {
if (text) {
return
}
if (React.isValidElement<{ children: React.ReactNode }>(child)) {
if (child.type === ComboboxItemText) {
text = child.props.children as string
} else {
text = findComboboxItemText(child.props.children)
}
}
})
return text
}
export const ComboboxItem = React.forwardRef<React.ElementRef<typeof CommandPrimitive.Item>, ComboboxItemProps>(
({ value: valueProp, children, onMouseDown, ...props }, ref) => {
const { type, value, onValueChange, onInputValueChange, onOpenChange } = useComboboxContext()
const inputValue = React.useMemo(() => findComboboxItemText(children), [children])
const isSelected = type === "single" ? value === valueProp : value.includes(valueProp)
return (
<ComboboxItemContext.Provider value={{ isSelected }}>
<CommandPrimitive.Item
ref={ref}
onMouseDown={composeEventHandlers(onMouseDown, (event) => event.preventDefault())}
onSelect={() => {
if (type === "multiple") {
onValueChange(
value.includes(valueProp)
? value.filter((v) => v !== valueProp)
: [...value, valueProp],
)
onInputValueChange("", "itemSelect")
} else {
onValueChange(valueProp)
onInputValueChange(inputValue, "itemSelect")
// Schedule open change to the next tick.
setTimeout(() => onOpenChange(false))
}
}}
value={inputValue}
{...props}>
{children}
</CommandPrimitive.Item>
</ComboboxItemContext.Provider>
)
},
)
ComboboxItem.displayName = "ComboboxItem"
export const ComboboxItemIndicator = React.forwardRef<
React.ElementRef<typeof Primitive.span>,
React.ComponentPropsWithoutRef<typeof Primitive.span>
>((props, ref) => {
const { isSelected } = useComboboxItemContext()
if (!isSelected) {
return null
}
return <Primitive.span ref={ref} aria-hidden {...props} />
})
ComboboxItemIndicator.displayName = "ComboboxItemIndicator"
export interface ComboboxItemTextProps extends React.ComponentPropsWithoutRef<typeof React.Fragment> {
children: string
}
export const ComboboxItemText = (props: ComboboxItemTextProps) => <React.Fragment {...props} />
ComboboxItemText.displayName = "ComboboxItemText"
export const ComboboxGroup = CommandPrimitive.Group
export const ComboboxSeparator = CommandPrimitive.Separator
const Root = Combobox
const TagGroup = ComboboxTagGroup
const TagGroupItem = ComboboxTagGroupItem
const TagGroupItemRemove = ComboboxTagGroupItemRemove
const Input = ComboboxInput
const Clear = ComboboxClear
const Trigger = ComboboxTrigger
const Anchor = ComboboxAnchor
const Portal = ComboboxPortal
const Content = ComboboxContent
const Empty = ComboboxEmpty
const Loading = ComboboxLoading
const Item = ComboboxItem
const ItemIndicator = ComboboxItemIndicator
const ItemText = ComboboxItemText
const Group = ComboboxGroup
const Separator = ComboboxSeparator
export {
Root,
TagGroup,
TagGroupItem,
TagGroupItemRemove,
Input,
Clear,
Trigger,
Anchor,
Portal,
Content,
Empty,
Loading,
Item,
ItemIndicator,
ItemText,
Group,
Separator,
}

View file

@ -0,0 +1,177 @@
"use client"
import * as React from "react"
import { Slottable } from "@radix-ui/react-slot"
import { cva } from "class-variance-authority"
import { Check, ChevronsUpDown, Loader, X } from "lucide-react"
import { cn } from "@/lib/utils"
import * as ComboboxPrimitive from "@/components/ui/combobox-primitive"
import { badgeVariants } from "@/components/ui/badge"
// import * as ComboboxPrimitive from "@/registry/default/ui/combobox-primitive"
import {
InputBase,
InputBaseAdornmentButton,
InputBaseControl,
InputBaseFlexWrapper,
InputBaseInput,
} from "@/components/ui/input-base"
export const Combobox = ComboboxPrimitive.Root
const ComboboxInputBase = React.forwardRef<
React.ElementRef<typeof InputBase>,
React.ComponentPropsWithoutRef<typeof InputBase>
>(({ children, ...props }, ref) => (
<ComboboxPrimitive.Anchor asChild>
<InputBase ref={ref} {...props}>
{children}
<ComboboxPrimitive.Clear asChild>
<InputBaseAdornmentButton>
<X />
</InputBaseAdornmentButton>
</ComboboxPrimitive.Clear>
<ComboboxPrimitive.Trigger asChild>
<InputBaseAdornmentButton>
<ChevronsUpDown />
</InputBaseAdornmentButton>
</ComboboxPrimitive.Trigger>
</InputBase>
</ComboboxPrimitive.Anchor>
))
ComboboxInputBase.displayName = "ComboboxInputBase"
export const ComboboxInput = React.forwardRef<
React.ElementRef<typeof ComboboxPrimitive.Input>,
React.ComponentPropsWithoutRef<typeof ComboboxPrimitive.Input>
>((props, ref) => (
<ComboboxInputBase>
<InputBaseControl>
<ComboboxPrimitive.Input asChild>
<InputBaseInput ref={ref} {...props} />
</ComboboxPrimitive.Input>
</InputBaseControl>
</ComboboxInputBase>
))
ComboboxInput.displayName = "ComboboxInput"
export const ComboboxTagsInput = React.forwardRef<
React.ElementRef<typeof ComboboxPrimitive.Input>,
React.ComponentPropsWithoutRef<typeof ComboboxPrimitive.Input>
>(({ children, ...props }, ref) => (
<ComboboxInputBase>
<ComboboxPrimitive.ComboboxTagGroup asChild>
<InputBaseFlexWrapper className="flex items-center gap-2">
{children}
<InputBaseControl>
<ComboboxPrimitive.Input asChild>
<InputBaseInput ref={ref} {...props} />
</ComboboxPrimitive.Input>
</InputBaseControl>
</InputBaseFlexWrapper>
</ComboboxPrimitive.ComboboxTagGroup>
</ComboboxInputBase>
))
ComboboxTagsInput.displayName = "ComboboxTagsInput"
export const ComboboxTag = React.forwardRef<
React.ElementRef<typeof ComboboxPrimitive.ComboboxTagGroupItem>,
React.ComponentPropsWithoutRef<typeof ComboboxPrimitive.ComboboxTagGroupItem>
>(({ children, className, ...props }, ref) => (
<ComboboxPrimitive.ComboboxTagGroupItem
ref={ref}
className={cn(
badgeVariants({ variant: "outline" }),
"group gap-1 pr-1.5 data-[disabled]:opacity-50",
className,
)}
{...props}>
<Slottable>{children}</Slottable>
<ComboboxPrimitive.ComboboxTagGroupItemRemove className="group-data-[disabled]:pointer-events-none">
<X className="size-4" />
<span className="sr-only">Remove</span>
</ComboboxPrimitive.ComboboxTagGroupItemRemove>
</ComboboxPrimitive.ComboboxTagGroupItem>
))
ComboboxTag.displayName = "ComboboxTag"
export const ComboboxContent = React.forwardRef<
React.ElementRef<typeof ComboboxPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof ComboboxPrimitive.Content>
>(({ className, align = "start", alignOffset = 0, ...props }, ref) => (
<ComboboxPrimitive.Portal>
<ComboboxPrimitive.Content
ref={ref}
align={align}
alignOffset={alignOffset}
className={cn(
"min-w-72 border-vscode-dropdown-border relative z-50 left-0 max-h-96 w-[--radix-popover-trigger-width] overflow-y-auto overflow-x-hidden rounded-xs border bg-popover p-1 text-popover-foreground shadow-md data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",
className,
)}
{...props}
/>
</ComboboxPrimitive.Portal>
))
ComboboxContent.displayName = "ComboboxContent"
export const ComboboxEmpty = React.forwardRef<
React.ElementRef<typeof ComboboxPrimitive.Empty>,
React.ComponentPropsWithoutRef<typeof ComboboxPrimitive.Empty>
>(({ className, ...props }, ref) => (
<ComboboxPrimitive.Empty ref={ref} className={cn("py-6 text-center text-sm", className)} {...props} />
))
ComboboxEmpty.displayName = "ComboboxEmpty"
export const ComboboxLoading = React.forwardRef<
React.ElementRef<typeof ComboboxPrimitive.Loading>,
React.ComponentPropsWithoutRef<typeof ComboboxPrimitive.Loading>
>(({ className, ...props }, ref) => (
<ComboboxPrimitive.Loading
ref={ref}
className={cn("flex items-center justify-center px-1.5 py-2", className)}
{...props}>
<Loader className="size-4 animate-spin [mask:conic-gradient(transparent_45deg,_white)]" />
</ComboboxPrimitive.Loading>
))
ComboboxLoading.displayName = "ComboboxLoading"
export const ComboboxGroup = React.forwardRef<
React.ElementRef<typeof ComboboxPrimitive.Group>,
React.ComponentPropsWithoutRef<typeof ComboboxPrimitive.Group>
>(({ className, ...props }, ref) => (
<ComboboxPrimitive.Group
ref={ref}
className={cn(
"[&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:py-1.5 [&_[cmdk-group-heading]]:text-sm [&_[cmdk-group-heading]]:font-semibold",
className,
)}
{...props}
/>
))
ComboboxGroup.displayName = "ComboboxGroup"
const ComboboxSeparator = React.forwardRef<
React.ElementRef<typeof ComboboxPrimitive.Separator>,
React.ComponentPropsWithoutRef<typeof ComboboxPrimitive.Separator>
>(({ className, ...props }, ref) => (
<ComboboxPrimitive.Separator ref={ref} className={cn("-mx-1 my-1 h-px bg-border", className)} {...props} />
))
ComboboxSeparator.displayName = "ComboboxSeparator"
export const comboboxItemStyle = cva(
"relative flex w-full cursor-pointer select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none data-[disabled=true]:pointer-events-none data-[selected=true]:bg-accent data-[selected=true]:text-vscode-dropdown-foreground data-[disabled=true]:opacity-50",
)
export const ComboboxItem = React.forwardRef<
React.ElementRef<typeof ComboboxPrimitive.Item>,
Omit<React.ComponentPropsWithoutRef<typeof ComboboxPrimitive.Item>, "children"> &
Pick<React.ComponentPropsWithoutRef<typeof ComboboxPrimitive.ItemText>, "children">
>(({ className, children, ...props }, ref) => (
<ComboboxPrimitive.Item ref={ref} className={cn(comboboxItemStyle(), className)} {...props}>
<ComboboxPrimitive.ItemText>{children}</ComboboxPrimitive.ItemText>
<ComboboxPrimitive.ItemIndicator className="absolute right-2 flex size-3.5 items-center justify-center">
<Check className="size-4" />
</ComboboxPrimitive.ItemIndicator>
</ComboboxPrimitive.Item>
))
ComboboxItem.displayName = "ComboboxItem"

View file

@ -1,96 +1,108 @@
"use client"
import * as React from "react"
import * as DialogPrimitive from "@radix-ui/react-dialog"
import { Cross2Icon } from "@radix-ui/react-icons"
import { XIcon } from "lucide-react"
import { cn } from "@/lib/utils"
const Dialog = DialogPrimitive.Root
function Dialog({ ...props }: React.ComponentProps<typeof DialogPrimitive.Root>) {
return <DialogPrimitive.Root data-slot="dialog" {...props} />
}
const DialogTrigger = DialogPrimitive.Trigger
function DialogTrigger({ ...props }: React.ComponentProps<typeof DialogPrimitive.Trigger>) {
return <DialogPrimitive.Trigger data-slot="dialog-trigger" {...props} />
}
const DialogPortal = DialogPrimitive.Portal
function DialogPortal({ ...props }: React.ComponentProps<typeof DialogPrimitive.Portal>) {
return <DialogPrimitive.Portal data-slot="dialog-portal" {...props} />
}
const DialogClose = DialogPrimitive.Close
function DialogClose({ ...props }: React.ComponentProps<typeof DialogPrimitive.Close>) {
return <DialogPrimitive.Close data-slot="dialog-close" {...props} />
}
const DialogOverlay = React.forwardRef<
React.ElementRef<typeof DialogPrimitive.Overlay>,
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Overlay>
>(({ className, ...props }, ref) => (
<DialogPrimitive.Overlay
ref={ref}
className={cn(
"fixed inset-0 z-50 bg-black/50 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",
className,
)}
{...props}
/>
))
DialogOverlay.displayName = DialogPrimitive.Overlay.displayName
const DialogContent = React.forwardRef<
React.ElementRef<typeof DialogPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Content>
>(({ className, children, ...props }, ref) => (
<DialogPortal>
<DialogOverlay />
<DialogPrimitive.Content
ref={ref}
function DialogOverlay({ className, ...props }: React.ComponentProps<typeof DialogPrimitive.Overlay>) {
return (
<DialogPrimitive.Overlay
data-slot="dialog-overlay"
className={cn(
"fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-vscode-editor-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] rounded-lg",
"data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/50",
className,
)}
{...props}>
{children}
<DialogPrimitive.Close className="cursor-pointer absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground">
<Cross2Icon className="h-4 w-4" />
<span className="sr-only">Close</span>
</DialogPrimitive.Close>
</DialogPrimitive.Content>
</DialogPortal>
))
DialogContent.displayName = DialogPrimitive.Content.displayName
{...props}
/>
)
}
const DialogHeader = ({ className, ...props }: React.HTMLAttributes<HTMLDivElement>) => (
<div className={cn("flex flex-col space-y-1.5 text-center sm:text-left", className)} {...props} />
)
DialogHeader.displayName = "DialogHeader"
function DialogContent({ className, children, ...props }: React.ComponentProps<typeof DialogPrimitive.Content>) {
return (
<DialogPortal data-slot="dialog-portal">
<DialogOverlay />
<DialogPrimitive.Content
data-slot="dialog-content"
className={cn(
"bg-background data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border p-6 shadow-lg duration-200 sm:max-w-lg",
className,
)}
{...props}>
{children}
<DialogPrimitive.Close className="ring-offset-background focus:ring-ring data-[state=open]:bg-accent data-[state=open]:text-muted-foreground absolute top-4 right-4 rounded-xs opacity-70 transition-opacity hover:opacity-100 focus:ring-2 focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4">
<XIcon />
<span className="sr-only">Close</span>
</DialogPrimitive.Close>
</DialogPrimitive.Content>
</DialogPortal>
)
}
const DialogFooter = ({ className, ...props }: React.HTMLAttributes<HTMLDivElement>) => (
<div className={cn("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2", className)} {...props} />
)
DialogFooter.displayName = "DialogFooter"
function DialogHeader({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="dialog-header"
className={cn("flex flex-col gap-2 text-center sm:text-left", className)}
{...props}
/>
)
}
const DialogTitle = React.forwardRef<
React.ElementRef<typeof DialogPrimitive.Title>,
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Title>
>(({ className, ...props }, ref) => (
<DialogPrimitive.Title
ref={ref}
className={cn("text-lg font-semibold leading-none tracking-tight", className)}
{...props}
/>
))
DialogTitle.displayName = DialogPrimitive.Title.displayName
function DialogFooter({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="dialog-footer"
className={cn("flex flex-col-reverse gap-2 sm:flex-row sm:justify-end", className)}
{...props}
/>
)
}
const DialogDescription = React.forwardRef<
React.ElementRef<typeof DialogPrimitive.Description>,
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Description>
>(({ className, ...props }, ref) => (
<DialogPrimitive.Description ref={ref} className={cn("text-sm text-muted-foreground", className)} {...props} />
))
DialogDescription.displayName = DialogPrimitive.Description.displayName
function DialogTitle({ className, ...props }: React.ComponentProps<typeof DialogPrimitive.Title>) {
return (
<DialogPrimitive.Title
data-slot="dialog-title"
className={cn("text-lg leading-none font-semibold", className)}
{...props}
/>
)
}
function DialogDescription({ className, ...props }: React.ComponentProps<typeof DialogPrimitive.Description>) {
return (
<DialogPrimitive.Description
data-slot="dialog-description"
className={cn("text-muted-foreground text-sm", className)}
{...props}
/>
)
}
export {
Dialog,
DialogPortal,
DialogOverlay,
DialogTrigger,
DialogClose,
DialogContent,
DialogHeader,
DialogFooter,
DialogTitle,
DialogDescription,
DialogFooter,
DialogHeader,
DialogOverlay,
DialogPortal,
DialogTitle,
DialogTrigger,
}

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