mirror of
https://github.com/RooVetGit/Roo-Code.git
synced 2026-08-28 05:27:24 +00:00
Merge branch 'main' of https://github.com/RooVetGit/Roo-Code into sbc_add_subtasks
This commit is contained in:
commit
dcde2e06f8
71 changed files with 3996 additions and 3366 deletions
2
.github/CODEOWNERS
vendored
2
.github/CODEOWNERS
vendored
|
|
@ -1,2 +1,2 @@
|
|||
# These owners will be the default owners for everything in the repo
|
||||
* @stea9499 @ColemanRoo @mrubens @cte
|
||||
* @mrubens @cte
|
||||
|
|
|
|||
2
.github/ISSUE_TEMPLATE/bug_report.yml
vendored
2
.github/ISSUE_TEMPLATE/bug_report.yml
vendored
|
|
@ -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
|
||||
|
|
|
|||
42
.github/workflows/code-qa.yml
vendored
42
.github/workflows/code-qa.yml
vendored
|
|
@ -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
|
||||
|
|
|
|||
28
CHANGELOG.md
28
CHANGELOG.md
|
|
@ -1,5 +1,33 @@
|
|||
# Roo Code Changelog
|
||||
|
||||
## [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
226
README.md
|
|
@ -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**. You’ll 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. Here’s what’s 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 you’re using GPT-4, other APIs, or switching configurations, this gives you total control over how your prompts are optimized.
|
||||
|
||||
As always, we’d 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. Here’s what’s 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. Can’t 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 can’t write code or run commands.
|
||||
|
||||
**Switching Modes:**
|
||||
It’s super simple! There’s a dropdown in the bottom left of the chat input to switch modes. Right next to it, you’ll 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, we’d love to give Cline the ability to suggest mode switches based on context. For now, we’d 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 Code’s 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 editor’s 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 file’s 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 editor’s 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)
|
||||
|
||||
---
|
||||
|
||||
|
|
|
|||
|
|
@ -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
27
knip.json
Normal 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
340
package-lock.json
generated
|
|
@ -1,15 +1,15 @@
|
|||
{
|
||||
"name": "roo-cline",
|
||||
"version": "3.3.23",
|
||||
"version": "3.7.2",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "roo-cline",
|
||||
"version": "3.3.23",
|
||||
"version": "3.7.2",
|
||||
"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"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
11
package.json
11
package.json
|
|
@ -3,7 +3,7 @@
|
|||
"displayName": "Roo Code (prev. Roo Cline)",
|
||||
"description": "An AI-powered autonomous coding agent that lives in your editor.",
|
||||
"publisher": "RooVeterinaryInc",
|
||||
"version": "3.3.23",
|
||||
"version": "3.7.2",
|
||||
"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",
|
||||
|
|
|
|||
17
src/__mocks__/jest.setup.ts
Normal file
17
src/__mocks__/jest.setup.ts
Normal 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(),
|
||||
}),
|
||||
},
|
||||
}))
|
||||
|
|
@ -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()
|
||||
})
|
||||
})
|
||||
|
||||
|
|
|
|||
|
|
@ -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)
|
||||
|
|
|
|||
|
|
@ -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)
|
||||
})
|
||||
|
||||
|
|
|
|||
|
|
@ -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
|
||||
})
|
||||
})
|
||||
})
|
||||
|
|
|
|||
|
|
@ -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,
|
||||
|
|
@ -12,12 +14,15 @@ import { ApiStream } from "../transform/stream"
|
|||
|
||||
const ANTHROPIC_DEFAULT_TEMPERATURE = 0
|
||||
|
||||
const THINKING_MODELS = ["claude-3-7-sonnet-20250219"]
|
||||
|
||||
export class AnthropicHandler implements ApiHandler, SingleCompletionHandler {
|
||||
private options: ApiHandlerOptions
|
||||
private client: Anthropic
|
||||
|
||||
constructor(options: ApiHandlerOptions) {
|
||||
this.options = options
|
||||
|
||||
this.client = new Anthropic({
|
||||
apiKey: this.options.apiKey,
|
||||
baseURL: this.options.anthropicBaseUrl || undefined,
|
||||
|
|
@ -25,45 +30,57 @@ export class AnthropicHandler implements ApiHandler, SingleCompletionHandler {
|
|||
}
|
||||
|
||||
async *createMessage(systemPrompt: string, messages: Anthropic.Messages.MessageParam[]): ApiStream {
|
||||
let stream: AnthropicStream<Anthropic.Beta.PromptCaching.Messages.RawPromptCachingBetaMessageStreamEvent>
|
||||
let stream: AnthropicStream<Anthropic.Messages.RawMessageStreamEvent>
|
||||
const cacheControl: CacheControlEphemeral = { type: "ephemeral" }
|
||||
const modelId = this.getModel().id
|
||||
const maxTokens = this.getModel().info.maxTokens || 8192
|
||||
let temperature = this.options.modelTemperature ?? ANTHROPIC_DEFAULT_TEMPERATURE
|
||||
let thinking: BetaThinkingConfigParam | undefined = undefined
|
||||
|
||||
if (THINKING_MODELS.includes(modelId)) {
|
||||
thinking = this.options.anthropicThinking
|
||||
? { type: "enabled", budget_tokens: this.options.anthropicThinking }
|
||||
: { type: "disabled" }
|
||||
|
||||
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,
|
||||
),
|
||||
}
|
||||
|
|
@ -112,8 +129,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 +139,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 +195,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 +215,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
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
||||
|
|
|
|||
|
|
@ -55,6 +55,7 @@ export class OpenRouterHandler implements ApiHandler, SingleCompletionHandler {
|
|||
// 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.7-sonnet":
|
||||
case "anthropic/claude-3.5-sonnet":
|
||||
case "anthropic/claude-3.5-sonnet:beta":
|
||||
case "anthropic/claude-3.5-sonnet-20240620":
|
||||
|
|
@ -106,6 +107,7 @@ export class OpenRouterHandler implements ApiHandler, SingleCompletionHandler {
|
|||
// (models usually default to max tokens allowed)
|
||||
let maxTokens: number | undefined
|
||||
switch (this.getModel().id) {
|
||||
case "anthropic/claude-3.7-sonnet":
|
||||
case "anthropic/claude-3.5-sonnet":
|
||||
case "anthropic/claude-3.5-sonnet:beta":
|
||||
case "anthropic/claude-3.5-sonnet-20240620":
|
||||
|
|
|
|||
|
|
@ -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" })
|
||||
})
|
||||
})
|
||||
|
|
|
|||
338
src/api/transform/__tests__/gemini-format.test.ts
Normal file
338
src/api/transform/__tests__/gemini-format.test.ts
Normal 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",
|
||||
)
|
||||
})
|
||||
})
|
||||
301
src/api/transform/__tests__/mistral-format.test.ts
Normal file
301
src/api/transform/__tests__/mistral-format.test.ts
Normal 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()
|
||||
})
|
||||
})
|
||||
|
|
@ -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")
|
||||
})
|
||||
})
|
||||
|
|
|
|||
|
|
@ -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()
|
||||
})
|
||||
})
|
||||
|
|
|
|||
|
|
@ -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 {}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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({
|
||||
|
|
|
|||
|
|
@ -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);
|
||||
|
|
@ -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
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -54,7 +54,7 @@ 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 { modes, defaultModeSlug, getModeBySlug, getFullModeDetails } from "../shared/modes"
|
||||
import { truncateConversationIfNeeded } from "./sliding-window"
|
||||
import { ClineProvider, GlobalFileNames } from "./webview/ClineProvider"
|
||||
import { detectCodeOmission } from "../integrations/editor/detect-omission"
|
||||
|
|
@ -63,15 +63,27 @@ 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
|
||||
|
|
@ -123,19 +135,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")
|
||||
}
|
||||
|
||||
|
|
@ -159,13 +172,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]
|
||||
}
|
||||
|
||||
// a helper function to set the private member isSubTask to true
|
||||
// and by that set this Cline instance to be a subtask (on finish return control to parent task)
|
||||
setSubTask() {
|
||||
|
|
@ -801,8 +834,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()
|
||||
|
|
@ -2833,7 +2870,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(
|
||||
|
|
@ -2922,8 +2959,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
|
||||
}
|
||||
|
|
@ -3055,7 +3090,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")
|
||||
}
|
||||
|
||||
|
|
@ -3323,9 +3358,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 (
|
||||
|
|
|
|||
|
|
@ -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("[]")
|
||||
}),
|
||||
|
|
@ -296,93 +311,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")
|
||||
})
|
||||
})
|
||||
|
|
@ -432,7 +456,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)
|
||||
|
||||
|
|
@ -441,11 +469,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()
|
||||
|
|
@ -553,15 +591,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",
|
||||
|
|
@ -575,18 +610,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",
|
||||
|
|
@ -600,6 +633,7 @@ describe("Cline", () => {
|
|||
outputPrice: 0.2,
|
||||
} as ModelInfo,
|
||||
})
|
||||
|
||||
clineWithoutImages.apiConversationHistory = conversationHistory
|
||||
|
||||
// Mock abort state for both instances
|
||||
|
|
@ -608,6 +642,7 @@ describe("Cline", () => {
|
|||
set: () => {},
|
||||
configurable: true,
|
||||
})
|
||||
|
||||
Object.defineProperty(clineWithoutImages, "abort", {
|
||||
get: () => false,
|
||||
set: () => {},
|
||||
|
|
@ -622,6 +657,7 @@ describe("Cline", () => {
|
|||
content,
|
||||
"",
|
||||
])
|
||||
|
||||
// Set up mock streams
|
||||
const mockStreamWithImages = (async function* () {
|
||||
yield { type: "text", text: "test response" }
|
||||
|
|
@ -649,6 +685,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" }])
|
||||
|
|
@ -671,8 +713,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)
|
||||
|
|
@ -786,10 +832,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)
|
||||
|
|
@ -902,19 +955,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}`)
|
||||
|
|
@ -979,6 +1031,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(() => {})
|
||||
})
|
||||
})
|
||||
})
|
||||
|
|
|
|||
|
|
@ -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$"
|
||||
|
|
|
|||
|
|
@ -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")
|
||||
})
|
||||
})
|
||||
|
|
|
|||
|
|
@ -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."
|
||||
|
|
|
|||
|
|
@ -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)
|
||||
|
|
|
|||
|
|
@ -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.
|
||||
|
|
|
|||
130
src/core/sliding-window/__tests__/sliding-window.test.ts
Normal file
130
src/core/sliding-window/__tests__/sliding-window.test.ts
Normal file
|
|
@ -0,0 +1,130 @@
|
|||
// 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"
|
||||
|
||||
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])
|
||||
})
|
||||
})
|
||||
|
||||
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 threshold for prompt caching models", () => {
|
||||
const modelInfo = createModelInfo(200000, true, 50000)
|
||||
const totalTokens = 100000 // Below threshold
|
||||
const result = truncateConversationIfNeeded(messages, totalTokens, modelInfo)
|
||||
expect(result).toEqual(messages)
|
||||
})
|
||||
|
||||
it("should not truncate if tokens are below threshold for non-prompt caching models", () => {
|
||||
const modelInfo = createModelInfo(200000, false)
|
||||
const totalTokens = 100000 // Below threshold
|
||||
const result = truncateConversationIfNeeded(messages, totalTokens, modelInfo)
|
||||
expect(result).toEqual(messages)
|
||||
})
|
||||
|
||||
it("should use 80% of context window as threshold if it's greater than (contextWindow - buffer)", () => {
|
||||
const modelInfo = createModelInfo(50000, true) // Small context window
|
||||
const totalTokens = 40001 // Above 80% threshold (40000)
|
||||
const mockResult = [messages[0], messages[3], messages[4]]
|
||||
const result = truncateConversationIfNeeded(messages, totalTokens, modelInfo)
|
||||
expect(result).toEqual(mockResult)
|
||||
})
|
||||
})
|
||||
|
|
@ -1,4 +1,5 @@
|
|||
import { Anthropic } from "@anthropic-ai/sdk"
|
||||
|
||||
import { ModelInfo } from "../../shared/api"
|
||||
|
||||
/**
|
||||
|
|
@ -55,13 +56,15 @@ export function truncateConversationIfNeeded(
|
|||
/**
|
||||
* 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.
|
||||
* The maximum is computed as the greater of (contextWindow - buffer) 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 prompt caching models.
|
||||
*/
|
||||
function getMaxTokensForPromptCachingModels(modelInfo: ModelInfo): number {
|
||||
return Math.max(modelInfo.contextWindow - 40_000, modelInfo.contextWindow * 0.8)
|
||||
// The buffer needs to be at least as large as `modelInfo.maxTokens`.
|
||||
const buffer = modelInfo.maxTokens ? Math.max(40_000, modelInfo.maxTokens) : 40_000
|
||||
return Math.max(modelInfo.contextWindow - buffer, modelInfo.contextWindow * 0.8)
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
@ -83,7 +86,9 @@ function getTruncFractionForPromptCachingModels(modelInfo: ModelInfo): number {
|
|||
* @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)
|
||||
// The buffer needs to be at least as large as `modelInfo.maxTokens`.
|
||||
const buffer = modelInfo.maxTokens ? Math.max(40_000, modelInfo.maxTokens) : 40_000
|
||||
return Math.max(modelInfo.contextWindow - buffer, modelInfo.contextWindow * 0.8)
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
|
|||
|
|
@ -89,6 +89,7 @@ type GlobalStateKey =
|
|||
| "lmStudioModelId"
|
||||
| "lmStudioBaseUrl"
|
||||
| "anthropicBaseUrl"
|
||||
| "anthropicThinking"
|
||||
| "azureApiVersion"
|
||||
| "openAiStreamingEnabled"
|
||||
| "openRouterModelId"
|
||||
|
|
@ -492,18 +493,17 @@ export class ClineProvider implements vscode.WebviewViewProvider {
|
|||
const modePrompt = customModePrompts?.[mode] as PromptComponent
|
||||
const effectiveInstructions = [globalInstructions, modePrompt?.customInstructions].filter(Boolean).join("\n\n")
|
||||
|
||||
const newCline = new Cline(
|
||||
this,
|
||||
const newCline = new Cline({
|
||||
provider: this,
|
||||
apiConfiguration,
|
||||
effectiveInstructions,
|
||||
diffEnabled,
|
||||
checkpointsEnabled,
|
||||
customInstructions: effectiveInstructions,
|
||||
enableDiff: diffEnabled,
|
||||
enableCheckpoints: checkpointsEnabled,
|
||||
fuzzyMatchThreshold,
|
||||
task,
|
||||
images,
|
||||
undefined,
|
||||
experiments,
|
||||
)
|
||||
})
|
||||
this.addClineToStack(newCline)
|
||||
}
|
||||
|
||||
|
|
@ -524,18 +524,16 @@ export class ClineProvider implements vscode.WebviewViewProvider {
|
|||
const modePrompt = customModePrompts?.[mode] as PromptComponent
|
||||
const effectiveInstructions = [globalInstructions, modePrompt?.customInstructions].filter(Boolean).join("\n\n")
|
||||
|
||||
const newCline = new Cline(
|
||||
this,
|
||||
const newCline = new Cline({
|
||||
provider: this,
|
||||
apiConfiguration,
|
||||
effectiveInstructions,
|
||||
diffEnabled,
|
||||
checkpointsEnabled,
|
||||
customInstructions: effectiveInstructions,
|
||||
enableDiff: diffEnabled,
|
||||
enableCheckpoints: checkpointsEnabled,
|
||||
fuzzyMatchThreshold,
|
||||
undefined,
|
||||
undefined,
|
||||
historyItem,
|
||||
experiments,
|
||||
)
|
||||
})
|
||||
// get this cline task number id from the history item and set it to newCline
|
||||
newCline.setTaskNumber(historyItem.number)
|
||||
this.addClineToStack(newCline)
|
||||
|
|
@ -1751,6 +1749,7 @@ export class ClineProvider implements vscode.WebviewViewProvider {
|
|||
lmStudioModelId,
|
||||
lmStudioBaseUrl,
|
||||
anthropicBaseUrl,
|
||||
anthropicThinking,
|
||||
geminiApiKey,
|
||||
openAiNativeApiKey,
|
||||
deepSeekApiKey,
|
||||
|
|
@ -1798,6 +1797,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),
|
||||
|
|
@ -1997,23 +1997,7 @@ export class ClineProvider implements vscode.WebviewViewProvider {
|
|||
}
|
||||
|
||||
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) => {
|
||||
|
|
@ -2213,34 +2197,10 @@ export class ClineProvider implements vscode.WebviewViewProvider {
|
|||
)
|
||||
|
||||
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) => {
|
||||
|
|
@ -2249,6 +2209,7 @@ export class ClineProvider implements vscode.WebviewViewProvider {
|
|||
}
|
||||
return undefined
|
||||
}
|
||||
|
||||
for (const rawModel of rawModels) {
|
||||
const modelInfo: ModelInfo = {
|
||||
maxTokens: rawModel.top_provider?.max_completion_tokens,
|
||||
|
|
@ -2261,9 +2222,11 @@ export class ClineProvider implements vscode.WebviewViewProvider {
|
|||
}
|
||||
|
||||
switch (rawModel.id) {
|
||||
case "anthropic/claude-3.7-sonnet":
|
||||
case "anthropic/claude-3.7-sonnet:beta":
|
||||
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
|
||||
// NOTE: this needs to be synced with api.ts/openrouter default model info.
|
||||
modelInfo.supportsComputerUse = true
|
||||
modelInfo.supportsPromptCache = true
|
||||
modelInfo.cacheWritesPrice = 3.75
|
||||
|
|
@ -2620,6 +2583,7 @@ export class ClineProvider implements vscode.WebviewViewProvider {
|
|||
lmStudioModelId,
|
||||
lmStudioBaseUrl,
|
||||
anthropicBaseUrl,
|
||||
anthropicThinking,
|
||||
geminiApiKey,
|
||||
openAiNativeApiKey,
|
||||
deepSeekApiKey,
|
||||
|
|
@ -2702,6 +2666,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>,
|
||||
|
|
@ -2801,6 +2766,7 @@ export class ClineProvider implements vscode.WebviewViewProvider {
|
|||
lmStudioModelId,
|
||||
lmStudioBaseUrl,
|
||||
anthropicBaseUrl,
|
||||
anthropicThinking,
|
||||
geminiApiKey,
|
||||
openAiNativeApiKey,
|
||||
deepSeekApiKey,
|
||||
|
|
|
|||
|
|
@ -10,12 +10,41 @@ import { defaultModeSlug } from "../../../shared/modes"
|
|||
import { experimentDefault } from "../../../shared/experiments"
|
||||
import { Cline } from "../../Cline"
|
||||
|
||||
// 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", () => {
|
||||
|
|
@ -690,19 +719,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]
|
||||
|
|
|
|||
|
|
@ -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
|
||||
*/
|
||||
|
|
@ -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
|
||||
|
|
|
|||
|
|
@ -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
|
||||
}
|
||||
}
|
||||
|
|
@ -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 })
|
||||
|
|
|
|||
|
|
@ -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")
|
||||
|
|
|
|||
|
|
@ -32,6 +32,7 @@ describe("checkExistKey", () => {
|
|||
apiKey: "test-key",
|
||||
apiProvider: undefined,
|
||||
anthropicBaseUrl: undefined,
|
||||
anthropicThinking: undefined,
|
||||
}
|
||||
expect(checkExistKey(config)).toBe(true)
|
||||
})
|
||||
|
|
|
|||
47
src/shared/__tests__/experiments.test.ts
Normal file
47
src/shared/__tests__/experiments.test.ts
Normal 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)
|
||||
})
|
||||
})
|
||||
})
|
||||
|
|
@ -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(
|
||||
|
|
|
|||
|
|
@ -21,6 +21,7 @@ export interface ApiHandlerOptions {
|
|||
apiModelId?: string
|
||||
apiKey?: string // anthropic
|
||||
anthropicBaseUrl?: string
|
||||
anthropicThinking?: number
|
||||
vsCodeLmModelSelector?: vscode.LanguageModelChatSelector
|
||||
glamaModelId?: string
|
||||
glamaModelInfo?: ModelInfo
|
||||
|
|
@ -93,8 +94,19 @@ export interface ModelInfo {
|
|||
// 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": {
|
||||
maxTokens: 64_000,
|
||||
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
|
||||
},
|
||||
"claude-3-5-sonnet-20241022": {
|
||||
maxTokens: 8192,
|
||||
contextWindow: 200_000,
|
||||
|
|
@ -162,7 +174,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 +209,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 +228,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 +367,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 +379,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 +396,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 +413,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,
|
||||
|
|
|
|||
|
|
@ -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(
|
||||
|
|
|
|||
|
|
@ -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)
|
||||
|
|
|
|||
|
|
@ -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"],
|
||||
|
|
|
|||
|
|
@ -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) => {
|
||||
|
|
|
|||
|
|
@ -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")
|
||||
})
|
||||
})
|
||||
|
|
|
|||
|
|
@ -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'",
|
||||
)
|
||||
})
|
||||
})
|
||||
|
|
|
|||
|
|
@ -1,3 +1,4 @@
|
|||
{
|
||||
"extends": "react-app"
|
||||
"extends": "react-app",
|
||||
"ignorePatterns": ["!.storybook"]
|
||||
}
|
||||
|
|
|
|||
2117
webview-ui/package-lock.json
generated
2117
webview-ui/package-lock.json
generated
File diff suppressed because it is too large
Load diff
|
|
@ -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"
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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
|
||||
49
webview-ui/src/components/history/DeleteTaskDialog.tsx
Normal file
49
webview-ui/src/components/history/DeleteTaskDialog.tsx
Normal 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>
|
||||
)
|
||||
}
|
||||
|
|
@ -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>
|
||||
)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -137,7 +137,7 @@ describe("HistoryView", () => {
|
|||
})
|
||||
})
|
||||
|
||||
it("handles task deletion", () => {
|
||||
it("handles task deletion", async () => {
|
||||
const onDone = jest.fn()
|
||||
render(<HistoryView onDone={onDone} />)
|
||||
|
||||
|
|
@ -145,9 +145,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",
|
||||
|
|
|
|||
|
|
@ -2,9 +2,10 @@ import { memo, useCallback, 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 { Slider } from "@/components/ui"
|
||||
|
||||
import {
|
||||
ApiConfiguration,
|
||||
ModelInfo,
|
||||
|
|
@ -34,6 +35,7 @@ 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"
|
||||
|
|
@ -43,6 +45,7 @@ import { UnboundModelPicker } from "./UnboundModelPicker"
|
|||
import { ModelInfoView } from "./ModelInfoView"
|
||||
import { DROPDOWN_Z_INDEX } from "./styles"
|
||||
import { RequestyModelPicker } from "./RequestyModelPicker"
|
||||
import { TemperatureControl } from "./TemperatureControl"
|
||||
|
||||
interface ApiOptionsProps {
|
||||
uriScheme: string | undefined
|
||||
|
|
@ -65,6 +68,7 @@ const ApiOptions = ({
|
|||
const [lmStudioModels, setLmStudioModels] = useState<string[]>([])
|
||||
const [vsCodeLmModels, setVsCodeLmModels] = useState<vscodemodels.LanguageModelChatSelector[]>([])
|
||||
const [anthropicBaseUrlSelected, setAnthropicBaseUrlSelected] = useState(!!apiConfiguration?.anthropicBaseUrl)
|
||||
const [anthropicThinkingBudget, setAnthropicThinkingBudget] = useState(apiConfiguration?.anthropicThinking)
|
||||
const [azureApiVersionSelected, setAzureApiVersionSelected] = useState(!!apiConfiguration?.azureApiVersion)
|
||||
const [openRouterBaseUrlSelected, setOpenRouterBaseUrlSelected] = useState(!!apiConfiguration?.openRouterBaseUrl)
|
||||
const [isDescriptionExpanded, setIsDescriptionExpanded] = useState(false)
|
||||
|
|
@ -185,6 +189,7 @@ const ApiOptions = ({
|
|||
checked={anthropicBaseUrlSelected}
|
||||
onChange={(checked: boolean) => {
|
||||
setAnthropicBaseUrlSelected(checked)
|
||||
|
||||
if (!checked) {
|
||||
setApiConfigurationField("anthropicBaseUrl", "")
|
||||
}
|
||||
|
|
@ -384,6 +389,7 @@ const ApiOptions = ({
|
|||
checked={openRouterBaseUrlSelected}
|
||||
onChange={(checked: boolean) => {
|
||||
setOpenRouterBaseUrlSelected(checked)
|
||||
|
||||
if (!checked) {
|
||||
setApiConfigurationField("openRouterBaseUrl", "")
|
||||
}
|
||||
|
|
@ -468,9 +474,7 @@ const ApiOptions = ({
|
|||
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,7 +513,7 @@ const ApiOptions = ({
|
|||
</div>
|
||||
)}
|
||||
|
||||
{apiConfiguration?.apiProvider === "vertex" && (
|
||||
{selectedProvider === "vertex" && (
|
||||
<div style={{ display: "flex", flexDirection: "column", gap: 5 }}>
|
||||
<VSCodeTextField
|
||||
value={apiConfiguration?.vertexProjectId || ""}
|
||||
|
|
@ -623,6 +627,7 @@ const ApiOptions = ({
|
|||
checked={azureApiVersionSelected}
|
||||
onChange={(checked: boolean) => {
|
||||
setAzureApiVersionSelected(checked)
|
||||
|
||||
if (!checked) {
|
||||
setApiConfigurationField("azureApiVersion", "")
|
||||
}
|
||||
|
|
@ -1226,7 +1231,6 @@ const ApiOptions = ({
|
|||
)}
|
||||
|
||||
{selectedProvider === "glama" && <GlamaModelPicker />}
|
||||
|
||||
{selectedProvider === "openrouter" && <OpenRouterModelPicker />}
|
||||
{selectedProvider === "requesty" && <RequestyModelPicker />}
|
||||
|
||||
|
|
@ -1260,8 +1264,43 @@ const ApiOptions = ({
|
|||
</>
|
||||
)}
|
||||
|
||||
{selectedProvider === "anthropic" && selectedModelId === "claude-3-7-sonnet-20250219" && (
|
||||
<div className="flex flex-col gap-2 mt-2">
|
||||
<Checkbox
|
||||
checked={!!anthropicThinkingBudget}
|
||||
onChange={(checked) => {
|
||||
const budget = checked ? 16_384 : undefined
|
||||
setAnthropicThinkingBudget(budget)
|
||||
setApiConfigurationField("anthropicThinking", budget)
|
||||
}}>
|
||||
Thinking?
|
||||
</Checkbox>
|
||||
{anthropicThinkingBudget && (
|
||||
<>
|
||||
<div className="text-muted-foreground text-sm">
|
||||
Number of tokens Claude is allowed to use for its internal reasoning process.
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<Slider
|
||||
min={1024}
|
||||
max={anthropicModels["claude-3-7-sonnet-20250219"].maxTokens - 1}
|
||||
step={1024}
|
||||
value={[anthropicThinkingBudget]}
|
||||
onValueChange={(value) => {
|
||||
const budget = value[0]
|
||||
setAnthropicThinkingBudget(budget)
|
||||
setApiConfigurationField("anthropicThinking", budget)
|
||||
}}
|
||||
/>
|
||||
<div className="w-10">{anthropicThinkingBudget}</div>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{!fromWelcomeView && (
|
||||
<div style={{ marginTop: "10px" }}>
|
||||
<div className="mt-2">
|
||||
<TemperatureControl
|
||||
value={apiConfiguration?.modelTemperature}
|
||||
onChange={handleInputChange("modelTemperature", noTransform)}
|
||||
|
|
|
|||
|
|
@ -10,6 +10,6 @@ export const GlamaModelPicker = () => (
|
|||
refreshMessageType="refreshGlamaModels"
|
||||
serviceName="Glama"
|
||||
serviceUrl="https://glama.ai/models"
|
||||
recommendedModel="anthropic/claude-3-5-sonnet"
|
||||
recommendedModel="anthropic/claude-3-7-sonnet"
|
||||
/>
|
||||
)
|
||||
|
|
|
|||
|
|
@ -10,6 +10,6 @@ export const OpenRouterModelPicker = () => (
|
|||
refreshMessageType="refreshOpenRouterModels"
|
||||
serviceName="OpenRouter"
|
||||
serviceUrl="https://openrouter.ai/models"
|
||||
recommendedModel="anthropic/claude-3.5-sonnet:beta"
|
||||
recommendedModel="anthropic/claude-3.7-sonnet"
|
||||
/>
|
||||
)
|
||||
|
|
|
|||
|
|
@ -16,7 +16,7 @@ export const RequestyModelPicker = () => {
|
|||
}}
|
||||
serviceName="Requesty"
|
||||
serviceUrl="https://requesty.ai"
|
||||
recommendedModel="anthropic/claude-3-5-sonnet-latest"
|
||||
recommendedModel="anthropic/claude-3-7-sonnet-latest"
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,15 +1,7 @@
|
|||
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 { VSCodeButton, VSCodeCheckbox, VSCodeLink, VSCodeTextField } from "@vscode/webview-ui-toolkit/react"
|
||||
import { Dropdown, type DropdownOption } from "vscrui"
|
||||
|
||||
import {
|
||||
AlertDialog,
|
||||
AlertDialogContent,
|
||||
|
|
@ -19,7 +11,17 @@ import {
|
|||
AlertDialogAction,
|
||||
AlertDialogHeader,
|
||||
AlertDialogFooter,
|
||||
} from "../ui/alert-dialog"
|
||||
} from "@/components/ui"
|
||||
|
||||
import { vscode } from "../../utils/vscode"
|
||||
import { validateApiConfiguration, validateModelId } from "../../utils/validate"
|
||||
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
|
||||
|
|
@ -104,7 +106,9 @@ const SettingsView = forwardRef<SettingsViewRef, SettingsViewProps>(({ onDone },
|
|||
if (prevState.apiConfiguration?.[field] === value) {
|
||||
return prevState
|
||||
}
|
||||
|
||||
setChangeDetected(true)
|
||||
|
||||
return {
|
||||
...prevState,
|
||||
apiConfiguration: {
|
||||
|
|
@ -132,6 +136,7 @@ const SettingsView = forwardRef<SettingsViewRef, SettingsViewProps>(({ onDone },
|
|||
|
||||
const handleSubmit = () => {
|
||||
const apiValidationResult = validateApiConfiguration(apiConfiguration)
|
||||
|
||||
const modelIdValidationResult = validateModelId(
|
||||
apiConfiguration,
|
||||
extensionState.glamaModels,
|
||||
|
|
@ -140,6 +145,7 @@ const SettingsView = forwardRef<SettingsViewRef, SettingsViewProps>(({ onDone },
|
|||
|
||||
setApiErrorMessage(apiValidationResult)
|
||||
setModelIdErrorMessage(modelIdValidationResult)
|
||||
|
||||
if (!apiValidationResult && !modelIdValidationResult) {
|
||||
vscode.postMessage({ type: "alwaysAllowReadOnly", bool: alwaysAllowReadOnly })
|
||||
vscode.postMessage({ type: "alwaysAllowWrite", bool: alwaysAllowWrite })
|
||||
|
|
@ -162,18 +168,9 @@ 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 })
|
||||
setChangeDetected(false)
|
||||
}
|
||||
}
|
||||
|
|
@ -765,7 +762,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 && (
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
|
@ -1,3 +1,4 @@
|
|||
export * from "./alert-dialog"
|
||||
export * from "./autosize-textarea"
|
||||
export * from "./badge"
|
||||
export * from "./button"
|
||||
|
|
|
|||
|
|
@ -1,46 +0,0 @@
|
|||
import { vscode } from "../utils/vscode"
|
||||
|
||||
export interface GitCommit {
|
||||
hash: string
|
||||
shortHash: string
|
||||
subject: string
|
||||
author: string
|
||||
date: string
|
||||
}
|
||||
|
||||
class GitService {
|
||||
private commits: GitCommit[] | null = null
|
||||
private lastQuery: string = ""
|
||||
|
||||
async searchCommits(query: string = ""): Promise<GitCommit[]> {
|
||||
if (query === this.lastQuery && this.commits) {
|
||||
return this.commits
|
||||
}
|
||||
|
||||
// Request search from extension
|
||||
vscode.postMessage({ type: "searchCommits", query })
|
||||
|
||||
// Wait for response
|
||||
const response = await new Promise<GitCommit[]>((resolve) => {
|
||||
const handler = (event: MessageEvent) => {
|
||||
const message = event.data
|
||||
if (message.type === "commitSearchResults") {
|
||||
window.removeEventListener("message", handler)
|
||||
resolve(message.commits)
|
||||
}
|
||||
}
|
||||
window.addEventListener("message", handler)
|
||||
})
|
||||
|
||||
this.commits = response
|
||||
this.lastQuery = query
|
||||
return response
|
||||
}
|
||||
|
||||
clearCache() {
|
||||
this.commits = null
|
||||
this.lastQuery = ""
|
||||
}
|
||||
}
|
||||
|
||||
export const gitService = new GitService()
|
||||
Loading…
Add table
Reference in a new issue