Merge branch 'main' of https://github.com/cline/cline into double_underscore_fix

This commit is contained in:
Dennis Bartlett 2025-02-05 03:25:44 -06:00
commit 9640a5f496
166 changed files with 19534 additions and 6992 deletions

8
.changeset/README.md Normal file
View file

@ -0,0 +1,8 @@
# Changesets
Hello and welcome! This folder has been automatically generated by `@changesets/cli`, a build tool that works
with multi-package repos, or single-package repos to help you version and publish your code. You can
find the full documentation for it [in our repository](https://github.com/changesets/changesets)
We have a quick list of common questions to get you started engaging with this project in
[our documentation](https://github.com/changesets/changesets/blob/main/docs/common-questions.md)

11
.changeset/config.json Normal file
View file

@ -0,0 +1,11 @@
{
"$schema": "https://unpkg.com/@changesets/config@3.0.5/schema.json",
"changelog": "@changesets/cli/changelog",
"commit": false,
"fixed": [],
"linked": [],
"access": "restricted",
"baseBranch": "main",
"updateInternalDependencies": "patch",
"ignore": []
}

View file

@ -0,0 +1,5 @@
---
"claude-dev": minor
---
Adding changesets for automating version bumping and release notes

26
.changie.yaml Normal file
View file

@ -0,0 +1,26 @@
changesDir: .changes
unreleasedDir: unreleased
headerPath: header.tpl.md
changelogPath: CHANGELOG.md
versionExt: md
versionFormat: '## {{.Version}} - {{.Time.Format "2006-01-02"}}'
kindFormat: "### {{.Kind}}"
changeFormat: "* {{.Body}}"
kinds:
- label: Added
auto: minor
- label: Changed
auto: major
- label: Deprecated
auto: minor
- label: Removed
auto: major
- label: Fixed
auto: patch
- label: Security
auto: patch
newlines:
afterChangelogHeader: 1
beforeChangelogVersion: 1
endOfVersion: 1
envPrefix: CHANGIE_

1
.github/CODEOWNERS vendored Normal file
View file

@ -0,0 +1 @@
* @saoudrizwan @ocasta181 @NightTrek @pashpashpash

View file

@ -2,6 +2,10 @@
<!-- Describe your changes in detail. What problem does this PR solve? -->
### Test Procedure
<!-- How did you test this? Are you confident that it will not introduce bugs? If so, why? -->
### Type of Change
<!-- Put an 'x' in all boxes that apply -->
@ -17,6 +21,7 @@
- [ ] Changes are limited to a single feature, bugfix or chore (split larger changes into separate PRs)
- [ ] Tests are passing (`npm test`) and code is formatted and linted (`npm run format && npm run lint`)
- [ ] I have created a changeset using `npm run changeset` (required for user-facing changes)
- [ ] I have reviewed [contributor guidelines](https://github.com/cline/cline/blob/main/CONTRIBUTING.md)
### Screenshots

View file

@ -0,0 +1,103 @@
"""
This script updates a specific version's release notes section in CHANGELOG.md with new content
or reformats existing content.
The script:
1. Takes a version number, changelog path, and optionally new content as input from environment variables
2. Finds the section in the changelog for the specified version
3. Either:
a) Replaces the content with new content if provided, or
b) Reformats existing content by:
- Removing the first two lines of the changeset format
- Ensuring version numbers are wrapped in square brackets
4. Writes the updated changelog back to the file
Environment Variables:
CHANGELOG_PATH: Path to the changelog file (defaults to 'CHANGELOG.md')
VERSION: The version number to update/format
PREV_VERSION: The previous version number (used to locate section boundaries)
NEW_CONTENT: Optional new content to insert for this version
"""
#!/usr/bin/env python3
import os
import sys
CHANGELOG_PATH = os.environ.get("CHANGELOG_PATH", "CHANGELOG.md")
VERSION = os.environ['VERSION']
PREV_VERSION = os.environ.get("PREV_VERSION", "")
NEW_CONTENT = os.environ.get("NEW_CONTENT", "")
def overwrite_changelog_section(changelog_text: str, new_content: str):
# Find the section for the specified version
version_pattern = f"## {VERSION}\n"
bracketed_version_pattern = f"## [{VERSION}]\n"
prev_version_pattern = f"## [{PREV_VERSION}]\n"
print(f"latest version: {VERSION}")
print(f"prev_version: {PREV_VERSION}")
# Try both unbracketed and bracketed version patterns
version_index = changelog_text.find(version_pattern)
if version_index == -1:
version_index = changelog_text.find(bracketed_version_pattern)
if version_index == -1:
# If version not found, add it at the top (after the first line)
first_newline = changelog_text.find('\n')
if first_newline == -1:
# If no newline found, just prepend
return f"## [{VERSION}]\n\n{changelog_text}"
return f"{changelog_text[:first_newline + 1]}## [{VERSION}]\n\n{changelog_text[first_newline + 1:]}"
else:
# Using bracketed version
version_pattern = bracketed_version_pattern
notes_start_index = version_index + len(version_pattern)
notes_end_index = changelog_text.find(prev_version_pattern, notes_start_index) if PREV_VERSION and prev_version_pattern in changelog_text else len(changelog_text)
if new_content:
return changelog_text[:notes_start_index] + f"{new_content}\n" + changelog_text[notes_end_index:]
else:
changeset_lines = changelog_text[notes_start_index:notes_end_index].split("\n")
# Ensure we have at least 2 lines before removing them
if len(changeset_lines) < 2:
print("Warning: Changeset content has fewer than 2 lines")
parsed_lines = "\n".join(changeset_lines)
else:
# Remove the first two lines from the regular changeset format, ex: \n### Patch Changes
parsed_lines = "\n".join(changeset_lines[2:])
updated_changelog = changelog_text[:notes_start_index] + parsed_lines + changelog_text[notes_end_index:]
# Ensure version number is bracketed
updated_changelog = updated_changelog.replace(f"## {VERSION}", f"## [{VERSION}]")
return updated_changelog
try:
print(f"Reading changelog from: {CHANGELOG_PATH}")
with open(CHANGELOG_PATH, 'r') as f:
changelog_content = f.read()
print(f"Changelog content length: {len(changelog_content)} characters")
print("First 200 characters of changelog:")
print(changelog_content[:200])
print("----------------------------------------------------------------------------------")
new_changelog = overwrite_changelog_section(changelog_content, NEW_CONTENT)
print("New changelog content:")
print("----------------------------------------------------------------------------------")
print(new_changelog)
print("----------------------------------------------------------------------------------")
print(f"Writing updated changelog back to: {CHANGELOG_PATH}")
with open(CHANGELOG_PATH, 'w') as f:
f.write(new_changelog)
print(f"{CHANGELOG_PATH} updated successfully!")
except FileNotFoundError:
print(f"Error: Changelog file not found at {CHANGELOG_PATH}")
sys.exit(1)
except Exception as e:
print(f"Error updating changelog: {str(e)}")
print(f"Current working directory: {os.getcwd()}")
sys.exit(1)

162
.github/workflows/changeset-release.yml vendored Normal file
View file

@ -0,0 +1,162 @@
name: Changeset Release
run-name: Changeset Release ${{ github.actor != 'cline-bot' && '- Create PR' || '- Update Changelog' }}
permissions:
contents: write
pull-requests: write
on:
workflow_dispatch:
pull_request:
types: [closed, opened, labeled]
env:
REPO_PATH: ${{ github.repository }}
GIT_REF: ${{ github.event_name == 'pull_request' && github.event.pull_request.head.sha || 'main' }}
jobs:
# Job 1: Create version bump PR when changesets are merged to main
changeset-pr-version-bump:
if: >
( github.event_name == 'pull_request' &&
github.event.pull_request.merged == true &&
github.event.pull_request.base.ref == 'main' &&
github.actor != 'cline-bot' ) ||
github.event_name == 'workflow_dispatch'
runs-on: ubuntu-latest
permissions:
contents: write
pull-requests: write
steps:
- name: Git Checkout
uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # v4
with:
fetch-depth: 0
ref: ${{ env.GIT_REF }}
- name: Setup Node.js
uses: actions/setup-node@b39b52d1213e96004bfcb1c61a8a6fa8ab84f3e8 # v4
with:
node-version: 20
cache: "npm"
- name: Install Dependencies
run: npm run install:all
# Check if there are any new changesets to process
- name: Check for changesets
id: check-changesets
run: |
NEW_CHANGESETS=$(find .changeset -name "*.md" ! -name "README.md" | wc -l | tr -d ' ')
echo "Changesets diff with previous version: $NEW_CHANGESETS"
echo "new_changesets=$NEW_CHANGESETS" >> $GITHUB_OUTPUT
# Create version bump PR using changesets/action if there are new changesets
- name: Changeset Pull Request
if: steps.check-changesets.outputs.new_changesets != '0'
id: changesets
uses: changesets/action@e9cc34b540dd3ad1b030c57fd97269e8f6ad905a # v1
with:
commit: "changeset version bump"
title: "Changeset version bump"
version: npm run version-packages # This performs the changeset version bump
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
# Job 2: Process version bump PR created by cline-bot
changeset-pr-edit-approve:
name: Auto approve and merge Bump version PRs
runs-on: ubuntu-latest
permissions:
contents: write
pull-requests: write
if: >
github.event_name == 'pull_request' &&
github.event.pull_request.base.ref == 'main' &&
github.actor == 'cline-bot' &&
contains(github.event.pull_request.title, 'Changeset version bump')
steps:
- name: Determine checkout ref
id: checkout-ref
run: |
echo "Event action: ${{ github.event.action }}"
echo "Actor: ${{ github.actor }}"
echo "Head ref: ${{ github.head_ref }}"
echo "PR SHA: ${{ github.event.pull_request.head.sha }}"
if [[ "${{ github.event.action }}" == "opened" && "${{ github.actor }}" == "cline-bot" ]]; then
echo "Using branch ref: ${{ github.head_ref }}"
echo "git_ref=${{ github.head_ref }}" >> $GITHUB_OUTPUT
else
echo "Using SHA ref: ${{ github.event.pull_request.head.sha }}"
echo "git_ref=${{ github.event.pull_request.head.sha }}" >> $GITHUB_OUTPUT
fi
- name: Checkout Repo
uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # v4
with:
token: ${{ secrets.GITHUB_TOKEN }}
fetch-depth: 0
ref: ${{ steps.checkout-ref.outputs.git_ref }}
# Get current and previous versions to edit changelog entry
- name: Get version
id: get_version
run: |
VERSION=$(git show HEAD:package.json | jq -r '.version')
echo "version=$VERSION" >> $GITHUB_OUTPUT
PREV_VERSION=$(git show origin/main:package.json | jq -r '.version')
echo "prev_version=$PREV_VERSION" >> $GITHUB_OUTPUT
echo "version=$VERSION"
echo "prev_version=$PREV_VERSION"
# Update CHANGELOG.md with proper format
- name: Update Changelog Format
if: ${{ !contains(github.event.pull_request.labels.*.name, 'changelog-ready') }}
env:
VERSION: ${{ steps.get_version.outputs.version }}
PREV_VERSION: ${{ steps.get_version.outputs.prev_version }}
run: python .github/scripts/overwrite_changeset_changelog.py
# Commit and push changelog updates
- name: Push Changelog updates
if: ${{ !contains(github.event.pull_request.labels.*.name, 'changelog-ready') }}
run: |
git config user.name "cline-bot"
git config user.email github-actions@github.com
echo "Running git add and commit..."
git add CHANGELOG.md
git commit -m "Updating CHANGELOG.md format"
git status
echo "--------------------------------------------------------------------------------"
echo "Pushing to remote..."
echo "--------------------------------------------------------------------------------"
git push
# Add label to indicate changelog has been formatted
- name: Add changelog-ready label
if: ${{ !contains(github.event.pull_request.labels.*.name, 'changelog-ready') }}
uses: actions/github-script@60a0d83039c74a4aee543508d2ffcb1c3799cdea # v7
with:
github-token: ${{ secrets.GITHUB_TOKEN }}
script: |
await github.rest.issues.addLabels({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: context.issue.number,
labels: ['changelog-ready']
});
# Auto-approve PR only after it has been labeled
- name: Auto approve PR
if: contains(github.event.pull_request.labels.*.name, 'changelog-ready')
uses: hmarr/auto-approve-action@de8bf34d0402c38aa2c8346973342b2cb02c4435 # v4
with:
review-message: "I'm approving since it's a bump version PR"
# Auto-merge PR
- name: Automerge on PR
if: false # Needs enablePullRequestAutoMerge in repo settings to work contains(github.event.pull_request.labels.*.name, 'changelog-ready')
run: gh pr merge --auto --merge ${{ github.event.pull_request.number }}
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}

119
.github/workflows/check-changeset.yml vendored Normal file
View file

@ -0,0 +1,119 @@
name: Check Changeset
run-name: Check for Changeset in PR
permissions:
contents: read
pull-requests: write
on:
pull_request:
branches:
- main
types: [opened, synchronize, reopened, ready_for_review]
jobs:
check-changeset:
# Skip draft PRs and dependabot PRs
if: github.event.pull_request.draft == false && github.actor != 'dependabot[bot]'
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # v4
with:
fetch-depth: 0
ref: ${{ github.event.pull_request.head.sha }}
- name: Check for changeset
id: check-changeset
run: |
# Debug info
echo "Current directory: $(pwd)"
echo "PR Base Ref: ${{ github.event.pull_request.base.ref }}"
echo "PR Head Ref: ${{ github.event.pull_request.head.ref }}"
echo "PR Head SHA: ${{ github.event.pull_request.head.sha }}"
echo "Git status:"
git status
# Get list of changed files
git fetch origin ${{ github.event.pull_request.base.ref }}
CHANGED_FILES=$(git diff --name-only origin/${{ github.event.pull_request.base.ref }} HEAD)
echo "Changed files:"
echo "$CHANGED_FILES"
echo "Listing .changeset directory:"
ls -la .changeset/
# Check if any of the changed files are in docs/ or .github/
DOCS_ONLY=true
while IFS= read -r file; do
if [[ ! "$file" =~ ^(docs/|.github/) ]]; then
DOCS_ONLY=false
break
fi
done <<< "$CHANGED_FILES"
# If changes are docs-only, skip changeset check
if [ "$DOCS_ONLY" = true ]; then
echo "Only documentation files were changed, skipping changeset check"
exit 0
fi
# Check if any changeset files are in the changed files
CHANGESET_IN_PR=false
while IFS= read -r file; do
if [[ "$file" =~ ^\.changeset/.*\.md$ && "$file" != ".changeset/README.md" ]]; then
echo "Found changeset file in PR: $file"
CHANGESET_IN_PR=true
break
fi
done <<< "$CHANGED_FILES"
if [ "$CHANGESET_IN_PR" = false ]; then
# Double check local changeset files as backup
CHANGESETS=$(find .changeset -name "*.md" ! -name "README.md" | wc -l | tr -d ' ')
echo "Number of local changesets: $CHANGESETS"
if [ "$CHANGESETS" -eq 0 ]; then
echo "::error::No changeset file found in PR changes or local directory. Please run 'npm run changeset' to create one."
exit 1
fi
fi
- name: Comment on PR
if: failure()
uses: actions/github-script@60a0d83039c74a4aee543508d2ffcb1c3799cdea # v7
with:
script: |
const message = `This PR requires a changeset since it includes user-facing changes. Please:
1. Run \`npm run changeset\` locally
2. Choose the appropriate version bump:
- \`major\` for breaking changes (1.0.0 → 2.0.0)
- \`minor\` for new features (1.0.0 → 1.1.0)
- \`patch\` for bug fixes (1.0.0 → 1.0.1)
3. Write a clear description of your changes
4. Commit the generated changeset file
Note: Documentation-only changes do not require a changeset.`;
// Get existing comments
const comments = await github.rest.issues.listComments({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: context.issue.number
});
// Check if we already commented
const botComment = comments.data.find(comment =>
comment.user.login === 'github-actions[bot]' &&
comment.body.includes('This PR requires a changeset')
);
if (!botComment) {
await github.rest.issues.createComment({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: context.issue.number,
body: message
});
}

115
.github/workflows/publish.yml vendored Normal file
View file

@ -0,0 +1,115 @@
name: "Publish Release"
on:
workflow_dispatch:
inputs:
release-type:
description: "Choose release type (release or pre-release)"
required: true
default: "release"
type: choice
options:
- pre-release
- release
permissions:
contents: write
packages: write
checks: write
pull-requests: write
jobs:
test:
uses: ./.github/workflows/test.yml
publish:
needs: test
name: Publish Extension
runs-on: ubuntu-latest
environment: publish
steps:
- uses: actions/checkout@v4
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: 20.15.1
# Cache root dependencies - only reuse if package-lock.json exactly matches
- name: Cache root dependencies
uses: actions/cache@v4
id: root-cache
with:
path: node_modules
key: ${{ runner.os }}-npm-${{ hashFiles('package-lock.json') }}
# Cache webview-ui dependencies - only reuse if package-lock.json exactly matches
- name: Cache webview-ui dependencies
uses: actions/cache@v4
id: webview-cache
with:
path: webview-ui/node_modules
key: ${{ runner.os }}-npm-webview-${{ hashFiles('webview-ui/package-lock.json') }}
- name: Install root dependencies
if: steps.root-cache.outputs.cache-hit != 'true'
run: npm ci
- name: Install webview-ui dependencies
if: steps.webview-cache.outputs.cache-hit != 'true'
run: cd webview-ui && npm ci
- name: Install Publishing Tools
run: npm install -g vsce ovsx
- name: Get Version
id: get_version
run: |
VERSION=$(node -p "require('./package.json').version")
echo "version=$VERSION" >> $GITHUB_OUTPUT
- name: Create Git Tag
id: create_tag
run: |
VERSION=v${{ steps.get_version.outputs.version }}
echo "tag=$VERSION" >> $GITHUB_OUTPUT
echo "Tagging with $VERSION"
git tag "$VERSION"
git push origin "$VERSION"
- name: Package and Publish Extension
env:
VSCE_PAT: ${{ secrets.VSCE_PAT }}
OVSX_PAT: ${{ secrets.OVSX_PAT }}
run: |
# Required to generate the .vsix
vsce package --out "cline-${{ steps.get_version.outputs.version }}.vsix"
if [ "${{ github.event.inputs.release-type }}" = "pre-release" ]; then
npm run publish:marketplace:prerelease
echo "Successfully published pre-release version ${{ steps.get_version.outputs.version }} to VS Code Marketplace and Open VSX Registry"
else
npm run publish:marketplace
echo "Successfully published release version ${{ steps.get_version.outputs.version }} to VS Code Marketplace and Open VSX Registry"
fi
# - name: Get Changelog Entry
# id: changelog
# uses: mindsers/changelog-reader-action@v2
# with:
# # This expects a standard Keep a Changelog format
# # "latest" means it will read whichever is the most recent version
# # set in "## [1.2.3] - 2025-01-28" style
# version: latest
- name: Create GitHub Release
uses: softprops/action-gh-release@v1
with:
tag_name: ${{ steps.create_tag.outputs.tag }}
files: "*.vsix"
# body: ${{ steps.changelog.outputs.content }}
generate_release_notes: true
prerelease: ${{ github.event.inputs.release-type == 'pre-release' }}
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

View file

@ -5,6 +5,13 @@ on:
pull_request:
branches:
- main
workflow_call:
# Set default permissions for all jobs
permissions:
contents: read # Needed to check out code
checks: write # Needed to report test results
pull-requests: write # Needed to add comments/annotations to PRs
jobs:
test:
@ -51,6 +58,5 @@ jobs:
- name: Prettier / Format Check
run: npm run format
- name: Tests
- name: Extension Tests
run: xvfb-run -a npm run test
if: runner.os == 'Linux'

3
.gitignore vendored
View file

@ -1,7 +1,10 @@
out
dist
node_modules
tmp
.vscode-test/
*.vsix
.DS_Store
pnpm-lock.yaml

17
.husky/pre-commit Executable file
View file

@ -0,0 +1,17 @@
echo "Running pre-commit checks..."
# Run ESLint
echo "Running ESLint..."
npm run lint || {
echo "❌ ESLint check failed. Please fix the errors and try committing again."
exit 1
}
# Run Prettier
echo "Running Prettier..."
npm run format || {
echo "❌ Prettier check failed. Run 'npm run format:fix' to automatically fix formatting issues."
exit 1
}
echo "✅ All checks passed!"

View file

@ -1,5 +1,5 @@
dist/
node_modules
webview-ui/build/
CHANGELOG.md
package-lock.json
*.md
package-lock.json

View file

@ -1,7 +1,7 @@
{
"tabWidth": 4,
"useTabs": true,
"printWidth": 120,
"printWidth": 130,
"semi": false,
"bracketSameLine": true
}

View file

@ -1,8 +1,14 @@
import { defineConfig } from "@vscode/test-cli"
import path from "path"
export default defineConfig({
files: "out/**/*.test.js",
files: "{out/**/*.test.js,src/**/*.test.js}",
mocha: {
ui: "bdd",
timeout: 20000, // Maximum time (in ms) that a test can run before failing
},
workspaceFolder: "test-workspace",
version: "stable",
extensionDevelopmentPath: path.resolve("./"),
launchArgs: ["--disable-extensions"],
})

View file

@ -1,9 +1,5 @@
{
// See http://go.microsoft.com/fwlink/?LinkId=827846
// for the documentation about the extensions.json format
"recommendations": [
"dbaeumer.vscode-eslint",
"connor4312.esbuild-problem-matchers",
"ms-vscode.extension-test-runner"
]
"recommendations": ["dbaeumer.vscode-eslint", "connor4312.esbuild-problem-matchers", "ms-vscode.extension-test-runner"]
}

View file

@ -31,6 +31,9 @@ webview-ui/package-lock.json
webview-ui/node_modules/**
**/.gitignore
# Ignore docs
docs/**
# Fix issue where codicons don't get packaged (https://github.com/microsoft/vscode-extension-samples/issues/692)
!node_modules/@vscode/codicons/dist/codicon.css
!node_modules/@vscode/codicons/dist/codicon.ttf

View file

@ -1,4 +1,106 @@
# Change Log
# Changelog
## [3.2.12]
- Fix command chaining for Windows users
- Fix reasoning_content error for OpenAI providers
## [3.2.11]
- Add OpenAI o3-mini model
## [3.2.10]
- Improve support for DeepSeek-R1 (deepseek-reasoner) model for OpenRouter, OpenAI-compatible, and DeepSeek direct
- Show Reasoning tokens for models that support it
- Fix issues with switching models between Plan/Act modes
## [3.2.6]
- Save last used API/model when switching between Plan and Act, for users that like to use different models for each mode
- New Context Window progress bar in the task header to understand increased cost/generation degradation as the context increases
- Localize READMEs and add language selector for English, Spanish, German, Chinese, and Japanese
- Add Advanced Settings to remove MCP prompts from requests to save tokens, enable/disable checkpoints for users that don't use git (more coming soon!)
- Add Gemini 2.0 Flash Thinking experimental model
- Allow new users to subscribe to mailing list to get notified when new Accounts option is available
## [3.2.5]
- Use yellow textfield outline in Plan mode to better distinguish from Act mode
## [3.2.3]
- Add DeepSeek-R1 (deepseek-reasoner) model support with proper parameter handling (thanks @slavakurilyak!)
## [3.2.0]
- Add Plan/Act mode toggle to let you plan tasks with Cline before letting him get to work
- Easily switch between API providers and models using a new popup menu under the chat field
- Add VS Code LM API provider to run models provided by other VS Code extensions (e.g. GitHub Copilot). Shoutout to @julesmons, @RaySinner, and @MrUbens for putting this together!
- Add on/off toggle for MCP servers to disable them when not in use. Thanks @MrUbens!
- Add Auto-approve option for individual tools in MCP servers. Thanks @MrUbens!
## [3.1.10]
- New icon!
## [3.1.9]
- Add Mistral API provider with codestral-latest model
## [3.1.7]
- Add ability to change viewport size and headless mode when Cline asks to launch the browser
## [3.1.6]
- Fix bug where filepaths with Chinese characters would not show up in context mention menu (thanks @chi-chat!)
- Update Anthropic model prices (thanks @timoteostewart!)
## [3.1.5]
- Fix bug where Cline couldn't read "@/" import path aliases from tool results
## [3.1.4]
- Fix issue where checkpoints would not work for users with git commit signing enabled globally
## [3.1.2]
- Fix issue where LFS files would be not be ignored when creating checkpoints
## [3.1.0]
- Added checkpoints: Snapshots of workspace are automatically created whenever Cline uses a tool
- Compare changes: Hover over any tool use to see a diff between the snapshot and current workspace state
- Restore options: Choose to restore just the task state, just the workspace files, or both
- New 'See new changes' button appears after task completion, providing an overview of all workspace changes
- Task header now shows disk space usage with a delete button to help manage snapshot storage
## [3.0.12]
- Fix DeepSeek API cost reporting (input price is 0 since it's all either a cache read or write, different than how Anthropic reports cache usage)
## [3.0.11]
- Emphasize auto-formatting done by the editor in file edit responses for more reliable diff editing
## [3.0.10]
- Add DeepSeek provider to API Provider options
- Fix context window limit errors for DeepSeek v3
## [3.0.9]
- Fix bug where DeepSeek v3 would incorrectly escape HTML entities in diff edits
## [3.0.8]
- Mitigate DeepSeek v3 diff edit errors by adding 'auto-formatting considerations' to system prompt, encouraging model to use updated file contents as reference point for SEARCH blocks
## [3.0.7]
- Revert to using batched file watcher to fix crash when many files would be created at once
## [3.0.6]

View file

@ -14,7 +14,22 @@ Bug reports help make Cline better for everyone! Before creating a new issue, pl
Looking for a good first contribution? Check out issues labeled ["good first issue"](https://github.com/cline/cline/labels/good%20first%20issue) or ["help wanted"](https://github.com/cline/cline/labels/help%20wanted). These are specifically curated for new contributors and areas where we'd love some help!
If you're planning to work on a bigger feature, please create an issue first so we can discuss whether it aligns with Cline's vision.
We also welcome contributions to our [documentation](https://github.com/cline/cline/tree/main/docs)! Whether it's fixing typos, improving existing guides, or creating new educational content - we'd love to build a community-driven repository of resources that helps everyone get the most out of Cline. You can start by diving into `/docs` and looking for areas that need improvement.
If you're planning to work on a bigger feature, please create a [feature request](https://github.com/cline/cline/discussions/categories/feature-requests?discussions_q=is%3Aopen+category%3A%22Feature+Requests%22+sort%3Atop) first so we can discuss whether it aligns with Cline's vision.
## Development Setup
1. **VS Code Extensions**
- When opening the project, VS Code will prompt you to install recommended extensions
- These extensions are required for development - please accept all installation prompts
- If you dismissed the prompts, you can install them manually from the Extensions panel
2. **Local Development**
- Run `npm run install:all` to install dependencies
- Run `npm run test` to run tests locally
- Before submitting PR, run `npm run format:fix` to format your code
## Writing and Submitting Code
@ -28,8 +43,9 @@ Anyone can contribute code to Cline, but we ask that you follow these guidelines
2. **Code Quality**
- Run `npm run lint` to ensure code follows our style guidelines
- Run `npm run format` to format your code with Prettier
- Run `npm run lint` to check code style
- Run `npm run format` to automatically format code
- All PRs must pass CI checks which include both linting and formatting
- Address any ESLint warnings or errors before submitting
- Follow TypeScript best practices and maintain type safety
@ -40,20 +56,30 @@ Anyone can contribute code to Cline, but we ask that you follow these guidelines
- Update existing tests if your changes affect them
- Include both unit tests and integration tests where appropriate
4. **Commit Guidelines**
4. **Version Management with Changesets**
- Create a changeset for any user-facing changes using `npm run changeset`
- Choose the appropriate version bump:
- `major` for breaking changes (1.0.0 → 2.0.0)
- `minor` for new features (1.0.0 → 1.1.0)
- `patch` for bug fixes (1.0.0 → 1.0.1)
- Write clear, descriptive changeset messages that explain the impact
- Documentation-only changes don't require changesets
5. **Commit Guidelines**
- Write clear, descriptive commit messages
- Use conventional commit format (e.g., "feat:", "fix:", "docs:")
- Reference relevant issues in commits using #issue-number
5. **Before Submitting**
6. **Before Submitting**
- Rebase your branch on the latest main
- Ensure your branch builds successfully
- Double-check all tests are passing
- Review your changes for any debugging code or console logs
6. **Pull Request Description**
7. **Pull Request Description**
- Clearly describe what your changes do
- Include steps to test the changes
- List any breaking changes

View file

@ -186,7 +186,7 @@
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright 2024 Cline Bot Inc.
Copyright 2025 Cline Bot Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
@ -198,4 +198,4 @@
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
limitations under the License.

View file

@ -1,4 +1,8 @@
# Cline (prev. Claude Dev) \#1 on OpenRouter
<div align="center"><sub>
English | <a href="https://github.com/cline/cline/blob/main/locales/es/README.md" target="_blank">Español</a> | <a href="https://github.com/cline/cline/blob/main/locales/de/README.md" target="_blank">Deutsch</a> | <a href="https://github.com/cline/cline/blob/main/locales/ja/README.md" target="_blank">日本語</a> | <a href="https://github.com/cline/cline/blob/main/locales/zh-cn/README.md" target="_blank">简体中文</a> | <a href="https://github.com/cline/cline/blob/main/locales/zh-tw/README.md" target="_blank">繁體中文</a>
</sub></div>
# Cline \#1 on OpenRouter
<p align="center">
<img src="https://media.githubusercontent.com/media/cline/cline/main/assets/docs/demo.gif" width="100%" />
@ -11,7 +15,10 @@
<a href="https://marketplace.visualstudio.com/items?itemName=saoudrizwan.claude-dev" target="_blank"><strong>Download on VS Marketplace</strong></a>
</td>
<td align="center">
<a href="https://discord.gg/cline" target="_blank"><strong>Join the Discord</strong></a>
<a href="https://discord.gg/cline" target="_blank"><strong>Discord</strong></a>
</td>
<td align="center">
<a href="https://www.reddit.com/r/cline/" target="_blank"><strong>r/cline</strong></a>
</td>
<td align="center">
<a href="https://github.com/cline/cline/discussions/categories/feature-requests?discussions_q=is%3Aopen+category%3A%22Feature+Requests%22+sort%3Atop" target="_blank"><strong>Feature Requests</strong></a>
@ -114,6 +121,22 @@ Thanks to the [Model Context Protocol](https://github.com/modelcontextprotocol),
**`@folder`:** Adds folder's files all at once to speed up your workflow even more
<!-- Transparent pixel to create line break after floating image -->
<img width="2000" height="0" src="https://github.com/user-attachments/assets/ee14e6f7-20b8-4391-9091-8e8e25561929"><br>
<img align="right" width="350" src="https://github.com/user-attachments/assets/140c8606-d3bf-41b9-9a1f-4dbf0d4c90cb">
### Checkpoints: Compare and Restore
As Cline works through a task, the extension takes a snapshot of your workspace at each step. You can use the 'Compare' button to see a diff between the snapshot and your current workspace, and the 'Restore' button to roll back to that point.
For example, when working with a local web server, you can use 'Restore Workspace Only' to quickly test different versions of your app, then use 'Restore Task and Workspace' when you find the version you want to continue building from. This lets you safely explore different approaches without losing progress.
<!-- Transparent pixel to create line break after floating image -->
<img width="2000" height="0" src="https://github.com/user-attachments/assets/ee14e6f7-20b8-4391-9091-8e8e25561929"><br>
## Contributing
To contribute to the project, start with our [Contributing Guide](CONTRIBUTING.md) to learn the basics. You can also join our [Discord](https://discord.gg/cline) to chat with other contributors in the `#contributors` channel. If you're looking for full-time work, check out our open positions on our [careers page](https://cline.bot/join-us)!
@ -137,6 +160,31 @@ To contribute to the project, start with our [Contributing Guide](CONTRIBUTING.m
</details>
<details>
<summary>Creating a Pull Request</summary>
1. Before creating a PR, generate a changeset entry:
```bash
npm run changeset
```
This will prompt you for:
- Type of change (major, minor, patch)
- `major` → breaking changes (1.0.0 → 2.0.0)
- `minor` → new features (1.0.0 → 1.1.0)
- `patch` → bug fixes (1.0.0 → 1.0.1)
- Description of your changes
2. Commit your changes and the generated `.changeset` file
3. Push your branch and create a PR on GitHub. Our CI will:
- Run tests and checks
- Changesetbot will create a comment showing the version impact
- When merged to main, changesetbot will create a Version Packages PR
- When the Version Packages PR is merged, a new release will be published
</details>
## License
[Apache 2.0 © 2024 Cline Bot Inc.](./LICENSE)
[Apache 2.0 © 2025 Cline Bot Inc.](./LICENSE)

Binary file not shown.

Before

Width:  |  Height:  |  Size: 9.2 KiB

After

Width:  |  Height:  |  Size: 4.9 KiB

16
assets/icons/icon.svg Normal file
View file

@ -0,0 +1,16 @@
<?xml version="1.0" encoding="UTF-8"?>
<svg width="92px" height="96px" viewBox="0 0 92 96" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<title>Group Copy 2</title>
<g id="Page-1" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd">
<g id="icon-copy" transform="translate(-34, -40)" fill="#24292F">
<g id="Group-Copy-2" transform="translate(34, 40.5)">
<g id="Group-3-Copy-4" transform="translate(0, 0)">
<path d="M65.4492701,16.3 C76.3374701,16.3 85.1635558,25.16479 85.1635558,36.1 L85.1635558,42.7 L90.9027661,54.1647464 C91.4694141,55.2966923 91.4668177,56.6300535 90.8957658,57.7597839 L85.1635558,69.1 L85.1635558,75.7 C85.1635558,86.63554 76.3374701,95.5 65.4492701,95.5 L26.0206986,95.5 C15.1328272,95.5 6.30641291,86.63554 6.30641291,75.7 L6.30641291,69.1 L0.448507752,57.7954874 C-0.14693501,56.6464093 -0.149634367,55.2802504 0.441262896,54.1288283 L6.30641291,42.7 L6.30641291,36.1 C6.30641291,25.16479 15.1328272,16.3 26.0206986,16.3 L65.4492701,16.3 Z M62.9301895,22 L29.189529,22 C19.8723267,22 12.3191987,29.5552188 12.3191987,38.875 L12.3191987,44.5 L7.44288578,53.9634655 C6.84794449,55.1180686 6.85066096,56.4896598 7.45017099,57.6418974 L12.3191987,67 L12.3191987,72.625 C12.3191987,81.9450625 19.8723267,89.5 29.189529,89.5 L62.9301895,89.5 C72.2476729,89.5 79.8005198,81.9450625 79.8005198,72.625 L79.8005198,67 L84.5682187,57.6061395 C85.1432011,56.473244 85.1458141,55.1345713 84.5752587,53.9994398 L79.8005198,44.5 L79.8005198,38.875 C79.8005198,29.5552188 72.2476729,22 62.9301895,22 Z" id="Combined-Shape" fill-rule="nonzero"></path>
<circle id="Oval" cx="45.7349843" cy="11" r="11"></circle>
</g>
<rect id="Rectangle-Copy" stroke="#24292F" stroke-width="8" x="31" y="44.5" width="5" height="22" rx="2.5"></rect>
<rect id="Rectangle-Copy-2" stroke="#24292F" stroke-width="8" x="55" y="44.5" width="5" height="22" rx="2.5"></rect>
</g>
</g>
</g>
</svg>

After

Width:  |  Height:  |  Size: 2 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 718 B

After

Width:  |  Height:  |  Size: 902 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 689 B

After

Width:  |  Height:  |  Size: 666 B

99
docs/PRIVACY.md Normal file
View file

@ -0,0 +1,99 @@
# Cline Privacy Policy
Cline Bot Inc. ("Cline," "we," "our," and/or "us") values the privacy of individuals who use our VS Code extension and related services (collectively, our "Services"). This privacy policy explains how we collect, use, and disclose information from users of our Services.
## Key Points
- Cline operates entirely client-side as a VS Code extension
- No code or data is collected, stored, or transmitted to Cline's servers
- Your data is only sent to your chosen AI provider (e.g., Anthropic, OpenAI) when you explicitly request assistance
- All processing happens locally on your machine
- API keys are stored securely in VS Code's built-in settings storage
## Information We Process
### A. Information You Provide
- **API Keys**: When you choose to use certain AI model providers (OpenRouter, Anthropic, OpenAI, etc.), you provide API keys. These are stored securely and locally in your VS Code settings.
- **Communications**: If you contact us directly (e.g., via Discord or email), we may receive information like your name, email address, and message contents.
### B. Information Processing
Cline functions solely as a client-side VS Code extension that facilitates communication between your editor and your chosen AI model provider:
1. **File Contents**:
- Only sent to your chosen AI provider when you explicitly request assistance
- Never stored or transmitted to Cline's servers
- Only the specific files/content you select are included
2. **Terminal Commands**:
- Processed entirely locally on your machine
- Require explicit user confirmation before execution
- No command history is transmitted to Cline
3. **Browser Integration**:
- Screenshots and console logs are processed locally
- Temporary data is cleared after task completion
## Data Security
1. **Local-Only Processing**:
- All operations happen on your local machine
- No central servers or data collection
- No telemetry or usage statistics gathered
- No account creation required
2. **API Key Security**:
- Stored using VS Code's secure settings storage system
- Never transmitted to Cline's servers
- You can remove/modify keys at any time
3. **User Control**:
- Explicit approval required for file changes
- Terminal commands require confirmation
- Browser actions need explicit permission
- You control which AI provider to use
## Communication with AI Providers
When you request assistance:
1. Selected content is sent directly to your chosen AI provider
2. No data passes through Cline's servers
3. Provider's own privacy policy applies to this communication:
- [Anthropic Privacy Policy](https://www.anthropic.com/privacy)
- [OpenAI Privacy Policy](https://openai.com/privacy)
- [OpenRouter Privacy Policy](https://openrouter.ai/privacy)
## Error Handling & Debugging
- Error logs are processed locally
- No automatic error reporting to Cline
- You control what information to include when reporting issues
## Children's Privacy
We do not knowingly collect, maintain, or use personal information from children under 18 years of age, and no part of our Service(s) is directed to children. If you learn that a child has provided us with personal information in violation of this Privacy Policy, then you may alert us at support@cline.bot.
## Changes to Privacy Policy
We will post any changes to this policy on our GitHub repository. Significant changes will be announced in our Discord community.
## Security Concerns & Auditing
- Cline is open source and available for security audit
- Our client-side architecture ensures no central point of data collection
- You can inspect exactly what data is being sent to AI providers
- Enterprise users can implement additional access controls through VS Code
## Contact Us
For privacy-related questions or concerns:
- Open an issue on our [GitHub repository](https://github.com/cline/cline)
- Join our [Discord community](https://discord.gg/cline)
- Email: support@cline.bot

38
docs/README.md Normal file
View file

@ -0,0 +1,38 @@
# Cline Documentation
Welcome to the Cline documentation - your comprehensive guide to using and extending Cline's capabilities. Here you'll find resources to help you get started, improve your skills, and contribute to the project.
## Getting Started
- **New to coding?** We've prepared a gentle introduction:
- [Getting Started for New Coders](getting-started-new-coders/README.md)
## Improving Your Prompting Skills
- **Want to communicate more effectively with Cline?** Explore:
- [Prompt Engineering Guide](prompting/README.md)
- [Cline Memory Bank](prompting/custom%20instructions%20library/cline-memory-bank.md)
## Exploring Cline's Tools
- **Understand Cline's capabilities:**
- [Cline Tools Guide](tools/cline-tools-guide.md)
- **Extend Cline with MCP Servers:**
- [MCP Overview](mcp/README.md)
- [Building MCP Servers from GitHub](mcp/mcp-server-from-github.md)
- [Building Custom MCP Servers](mcp/mcp-server-from-scratch.md)
## Contributing to Cline
- **Interested in contributing?** We welcome your input:
- Feel free to submit a pull request
- [Contribution Guidelines](CONTRIBUTING.md)
## Additional Resources
- **Cline GitHub Repository:** [https://github.com/cline/cline](https://github.com/cline/cline)
- **MCP Documentation:** [https://modelcontextprotocol.org/docs](https://modelcontextprotocol.org/docs)
We're always looking to improve this documentation. If you have suggestions or find areas that could be enhanced, please let us know. Your feedback helps make Cline better for everyone.

View file

@ -0,0 +1,92 @@
# Getting Started with Cline | New Coders
Welcome to Cline! This guide will help you get set up and start using Cline to build your first project.
## What You'll Need
Before you begin, make sure you have the following:
- **VS Code:** A free, powerful code editor.
- [Download VS Code](https://code.visualstudio.com/)
- **Development Tools:** Essential software for coding (Homebrew, Node.js, Git, etc.).
- Follow our [Installing Essential Development Tools](installing-dev-essentials.md) guide to set these up with Cline's help (after getting setup here)
- Cline will guide you through installing everything you need
- **Cline Projects Folder:** A dedicated folder for all your Cline projects.
- On macOS: Create a folder named "Cline" in your Documents folder
- Path: `/Users/[your-username]/Documents/Cline`
- On Windows: Create a folder named "Cline" in your Documents folder
- Path: `C:\Users\[your-username]\Documents\Cline`
- Inside this Cline folder, create separate folders for each project
- Example: `Documents/Cline/workout-app` for a workout tracking app
- Example: `Documents/Cline/portfolio-website` for your portfolio
- **Cline Extension in VS Code:** The Cline extension installed in VS Code.
- Here's a [tutorial](https://www.youtube.com/watch?v=N4td-fKhsOQ) on everything you need to get started.
## Step-by-Step Setup
Follow these steps to get Cline up and running:
1. **Open VS Code:** Launch the VS Code application. If VS Code shows "Running extensions might...", click "Allow".
2. **Open Your Cline Folder:** In VS Code, open the Cline folder you created in Documents.
3. **Navigate to Extensions:** Click on the Extensions icon in the Activity Bar on the side of VS Code.
4. **Search for 'Cline':** In the Extensions search bar, type "Cline".
5. **Install the Extension:** Click the "Install" button next to the Cline extension.
6. **Open Cline:** Once installed, you can open Cline in a few ways:
- Click the Cline icon in the Activity Bar.
- Use the command palette (`CMD/CTRL + Shift + P`) and type "Cline: Open In New Tab" to open Cline as a tab in your editor. This is recommended for a better view.
- **Troubleshooting:** If you don't see the Cline icon, try restarting VS Code.
- **What You'll See:** You should see the Cline chat window appear in your VS Code editor.
![gettingStartedVsCodeCline](https://github.com/user-attachments/assets/622b4bb7-859b-4c2e-b87b-c12e3eabefb8)
## Setting up OpenRouter API Key
Now that you have Cline installed, you'll need to set up your OpenRouter API key to use Cline's full capabilities.
1. **Get your OpenRouter API Key:**
- [Get your OpenRouter API Key](https://openrouter.ai/)
2. **Input Your OpenRouter API Key:**
- Navigate to the settings button in the Cline extension.
- Input your OpenRouter API key.
- Select your preferred API model.
- **Recommended Models for Coding:**
- `anthropic/claude-3.5-sonnet`: Most used for coding tasks.
- `google/gemini-2.0-flash-exp:free`: A free option for coding.
- `deepseek/deepseek-chat`: SUPER CHEAP, almost as good as 3.5 sonnet
- [OpenRouter Model Rankings](https://openrouter.ai/rankings/programming)
## Your First Interaction with Cline
Now you're ready to start building with Cline. Let's create your first project folder and build something! Copy and paste the following prompt into the Cline chat window:
```
Hey Cline! Could you help me create a new project folder called "hello-world" in my Cline directory and make a simple webpage that says "Hello World" in big blue text?
```
**What You'll See:** Cline will help you create the project folder and set up your first webpage.
## Tips for Working with Cline
- **Ask Questions:** If you're unsure about something, don't hesitate to ask Cline!
- **Use Screenshots:** Cline can understand images, so feel free to use screenshots to show him what you're working on.
- **Copy and Paste Errors:** If you encounter errors, copy and paste the error messages into Cline's chat. This will help him understand the issue and provide a solution.
- **Speak Plainly:** Cline is designed to understand plain, non-technical language. Feel free to describe your ideas in your own words, and Cline will translate them into code.
## FAQs
- **What is the Terminal?** The terminal is a text-based interface for interacting with your computer. It allows you to run commands to perform various tasks, such as installing packages, running scripts, and managing files. Cline uses the terminal to execute commands and interact with your development environment.
- **How Does the Codebase Work?** (This section will be expanded based on common questions from new coders)
## Still Struggling?
Feel free to contact me, and I'll help you get started with Cline.
nick | 608-558-2410
Join our Discord community: [https://discord.gg/cline](https://discord.gg/cline)

View file

@ -0,0 +1,105 @@
# Installing Essential Development Tools with Cline | New Coders
When you start coding, you'll need some essential development tools installed on your computer. Cline can help you install everything you need in a safe, guided way.
## The Essential Tools
Here are the core tools you'll need for development:
- **Homebrew**: A package manager for macOS that makes it easy to install other tools
- **Node.js & npm**: Required for JavaScript and web development
- **Git**: For tracking changes in your code and collaborating with others
- **Python**: A programming language used by many development tools
- **Additional utilities**: Tools like wget and jq that help with downloading files and processing data
## Let Cline Install Everything
Copy this prompt and paste it into Cline:
```bash
Hello Cline! I need help setting up my Mac for software development. Could you please help me install the essential development tools like Homebrew, Node.js, Git, Python, and any other utilities that are commonly needed for coding? I'd like you to guide me through the process step-by-step, explaining what each tool does and making sure everything is installed correctly.
```
## What Will Happen
1. Cline will first install Homebrew, which is like an "app store" for development tools
2. Using Homebrew, Cline will then install other essential tools like Node.js and Git
3. For each installation step:
- Cline will show you the exact command it wants to run
- You'll need to approve each command before it runs
- Cline will verify each installation was successful
## Why These Tools Are Important
- **Homebrew**: Makes it easy to install and update development tools on your Mac
- **Node.js & npm**: Required for:
- Building websites with React or Next.js
- Running JavaScript code
- Installing JavaScript packages
- **Git**: Helps you:
- Save different versions of your code
- Collaborate with other developers
- Back up your work
- **Python**: Used for:
- Running development scripts
- Data processing
- Machine learning projects
## Notes
- The installation process is interactive - Cline will guide you through each step
- You may need to enter your computer's password for some installations. When prompted, you will not see any characters being typed on the screen. This is normal and is a security feature to protect your password. Just type your password and press Enter.
**Example:**
```bash
$ /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
Password:
```
_Type your password here, even though nothing will show up on the screen. Press Enter when you're done._
- All commands will be shown to you for approval before they run
- If you run into any issues, Cline will help troubleshoot them
## Additional Tips for New Coders
### Understanding the Terminal
The **Terminal** is an application where you can type commands to interact with your computer. On macOS, you can open it by searching for "Terminal" in Spotlight.
**Example:**
```bash
$ open -a Terminal
```
### Understanding VS Code Features
#### Terminal in VS Code
The **Terminal** in VS Code allows you to run commands directly from within the editor. You can open it by going to `View > Terminal` or by pressing `` Ctrl + ` ``.
**Example:**
```bash
$ node -v
v16.14.0
```
#### Document View
The **Document View** is where you edit your code files. You can open files by clicking on them in the **Explorer** panel on the left side of the screen.
#### Problems Section
The **Problems** section in VS Code shows any errors or warnings in your code. You can access it by clicking on the lightbulb icon or by going to `View > Problems`.
### Common Features
- **Command Line Interface (CLI)**: This is a text-based interface where you type commands to interact with your computer. It might seem intimidating at first, but it's a powerful tool for developers.
- **Permissions**: Sometimes, you will need to give permissions to certain applications or commands. This is a security measure to ensure that only trusted applications can make changes to your system.
## Next Steps
After installing these tools, you'll be ready to start coding! Return to the [Getting Started with Cline for New Coders](../getting-started-new-coders/README.md) guide to continue your journey.

103
docs/mcp/README.md Normal file
View file

@ -0,0 +1,103 @@
# Cline and Model Context Protocol (MCP) Servers: Enhancing AI Capabilities
**Quick Links:**
- [Building MCP Servers from GitHub](mcp-server-from-github.md)
- [Building Custom MCP Servers from Scratch](mcp-server-from-scratch.md)
This document explains Model Context Protocol (MCP) servers, their capabilities, and how Cline can help build and use them.
## Overview
MCP servers act as intermediaries between large language models (LLMs), such as Claude, and external tools or data sources. They are small programs that expose functionalities to LLMs, enabling them to interact with the outside world through the MCP. An MCP server is essentially like an API that an LLM can use.
## Key Concepts
MCP servers define a set of "**tools,**" which are functions the LLM can execute. These tools offer a wide range of capabilities.
**Here's how MCP works:**
- **MCP hosts** discover the capabilities of connected servers and load their tools, prompts, and resources.
- **Resources** provide consistent access to read-only data, akin to file paths or database queries.
- **Security** is ensured as servers isolate credentials and sensitive data. Interactions require explicit user approval.
## Use Cases
The potential of MCP servers is vast. They can be used for a variety of purposes.
**Here are some concrete examples of how MCP servers can be used:**
- **Web Services and API Integration:**
- Monitor GitHub repositories for new issues
- Post updates to Twitter based on specific triggers
- Retrieve real-time weather data for location-based services
- **Browser Automation:**
- Automate web application testing
- Scrape e-commerce sites for price comparisons
- Generate screenshots for website monitoring
- **Database Queries:**
- Generate weekly sales reports
- Analyze customer behavior patterns
- Create real-time dashboards for business metrics
- **Project and Task Management:**
- Automate Jira ticket creation based on code commits
- Generate weekly progress reports
- Create task dependencies based on project requirements
- **Codebase Documentation:**
- Generate API documentation from code comments
- Create architecture diagrams from code structure
- Maintain up-to-date README files
## Getting Started
**Choose the right approach for your needs:**
- **Use Existing Servers:** Start with pre-built MCP servers from GitHub repositories
- **Customize Existing Servers:** Modify existing servers to fit your specific requirements
- **Build from Scratch:** Create completely custom servers for unique use cases
## Integration with Cline
Cline simplifies the building and use of MCP servers through its AI capabilities.
### Building MCP Servers
- **Natural language understanding:** Instruct Cline in natural language to build an MCP server by describing its functionalities. Cline will interpret your instructions and generate the necessary code.
- **Cloning and building servers:** Cline can clone existing MCP server repositories from GitHub and build them automatically.
- **Configuration and dependency management:** Cline handles configuration files, environment variables, and dependencies.
- **Troubleshooting and debugging:** Cline helps identify and resolve errors during development.
### Using MCP Servers
- **Tool execution:** Cline seamlessly integrates with MCP servers, allowing you to execute their defined tools.
- **Context-aware interactions:** Cline can intelligently suggest using relevant tools based on conversation context.
- **Dynamic integrations:** Combine multiple MCP server capabilities for complex tasks. For example, Cline could use a GitHub server to get data and a Notion server to create a formatted report.
## Security Considerations
When working with MCP servers, it's important to follow security best practices:
- **Authentication:** Always use secure authentication methods for API access
- **Environment Variables:** Store sensitive information in environment variables
- **Access Control:** Limit server access to authorized users only
- **Data Validation:** Validate all inputs to prevent injection attacks
- **Logging:** Implement secure logging practices without exposing sensitive data
## Resources
There are various resources available for finding and learning about MCP servers.
**Here are some links to resources for finding and learning about MCP servers:**
- **GitHub Repositories:** [https://github.com/modelcontextprotocol/servers](https://github.com/modelcontextprotocol/servers) and [https://github.com/punkpeye/awesome-mcp-servers](https://github.com/punkpeye/awesome-mcp-servers)
- **Online Directories:** [https://mcpservers.org/](https://mcpservers.org/), [https://mcp.so/](https://mcp.so/), and [https://glama.ai/mcp/servers](https://glama.ai/mcp/servers)
- **PulseMCP:** [https://www.pulsemcp.com/](https://www.pulsemcp.com/)
- **YouTube Tutorial (AI-Driven Coder):** A video guide for building and using MCP servers: [https://www.youtube.com/watch?v=b5pqTNiuuJg](https://www.youtube.com/watch?v=b5pqTNiuuJg)

151
docs/mcp/mcp-quickstart.md Normal file
View file

@ -0,0 +1,151 @@
# 🚀 MCP Quickstart Guide
## ❓ What's an MCP Server?
Think of MCP servers as special helpers that give Cline extra powers! They let Cline do cool things like fetch web pages or work with your files.
## ⚠️ IMPORTANT: System Requirements
STOP! Before proceeding, you MUST verify these requirements:
### Required Software
- ✅ Latest Node.js (v18 or newer)
- Check by running: `node --version`
- Install from: <https://nodejs.org/>
- ✅ Latest Python (v3.8 or newer)
- Check by running: `python --version`
- Install from: <https://python.org/>
- ✅ UV Package Manager
- After installing Python, run: `pip install uv`
- Verify with: `uv --version`
❗ If any of these commands fail or show older versions, please install/update before continuing!
⚠️ If you run into other errors, see the "Troubleshooting" section below.
## 🎯 Quick Steps (Only After Requirements Are Met!)
### 1. 🛠️ Install Your First MCP Server
1. From the Cline extension, click the `MCP Server` tab
1. Click the `Edit MCP Settings` button
<img src="https://github.com/user-attachments/assets/abf908b1-be98-4894-8dc7-ef3d27943a47" alt="MCP Server Panel" width="400" />
1. The MCP settings files should be display in a tab in VS Code.
1. Replace the file's contents with this code:
For Windows:
```json
{
"mcpServers": {
"mcp-installer": {
"command": "cmd.exe",
"args": ["/c", "npx", "-y", "@anaisbetts/mcp-installer"]
}
}
}
```
For Mac and Linux:
```json
{
"mcpServers": {
"mcp-installer": {
"command": "npx",
"args": ["@anaisbetts/mcp-installer"]
}
}
}
```
After saving the file:
1. Cline will detect the change automatically
2. The MCP installer will be downloaded and installed
3. Cline will start the MCP installer
4. You'll see the server status in Cline's MCP settings UI:
<img src="https://github.com/user-attachments/assets/2abbb3de-e902-4ec2-a5e5-9418ed34684e" alt="MCP Server Panel with Installer" width="400" />
## 🤔 What Next?
Now that you have the MCP installer, you can ask Cline to add more servers from:
1. NPM Registry: <https://www.npmjs.com/search?q=%40modelcontextprotocol>
2. Python Package Index: <https://pypi.org/search/?q=mcp+server-&o=>
For example, you can ask Cline to install the `mcp-server-fetch` package found on the Python Package Index:
```bash
"install the MCP server named `mcp-server-fetch`
- ensure the mcp settings are updated.
- use uvx or python to run the server."
```
You should witness Cline:
1. Install the `mcp-server-fetch` python package
1. Update the mcp setting json file
1. Start the server and start the server
The mcp settings file should now look like this:
_For a Windows machine:_
```json
{
"mcpServers": {
"mcp-installer": {
"command": "cmd.exe",
"args": ["/c", "npx", "-y", "@anaisbetts/mcp-installer"]
},
"mcp-server-fetch": {
"command": "uvx",
"args": ["mcp-server-fetch"]
}
}
}
```
You you can always check the status of your server by going to clients MCP server tab. See the image above
That's it! 🎉 You've just given Cline some awesome new abilities!
## 📝 Troubleshooting
### 1. I'm Using `asdf` and Get "unknown command: npx"
There is some slightly bad news. You should still be able to get things to work, but will have to do a bit more manual work unless MCP server packaging evolves a bit. One option is to uninstall `asdf` , but we will assume you do not want to do that.
Instead, you will need to follow the instructions above to "Edit MCP Settings". Then, as [this post](https://dev.to/cojiroooo/mcp-using-node-on-asdf-382n) describes, you need to add and "env" entry to each server's configs.
```json
"env": {
"PATH": "/Users/<user_name>/.asdf/shims:/usr/bin:/bin",
"ASDF_DIR": "<path_to_asdf_bin_dir>",
"ASDF_DATA_DIR": "/Users/<user_name>/.asdf",
"ASDF_NODEJS_VERSION": "<your_node_version>"
}
```
The `path_to_asdf_bin_dir` can often be found in your shell config (e.g. `.zshrc`). If you are using Homebrew, you can use `echo ${HOMEBREW_PREFIX}` to find the start of the directory and then append `/opt/asdf/libexec`.
Now for some good news. While not perfect, you can get Cline to do this for you fairly reliably for subsequent server install. Add the following to your "Custom Instructions" in the Cline settings (top-right toolbar button):
> When installing MCP servers and editing the cline_mcp_settings.json, if the server requires use of `npx` as the command, you must copy the "env" entry from the "mcp-installer" entry and add it to the new entry. This is vital to getting the server to work properly when in use.
### 2. I'm Still Getting an Error When I Run the MCP Installer
If you're getting an error when you run the MCP installer, you can try the following:
- Check the MCP settings file for errors
- Read the MCP server's documentation to ensure the MCP setting file is using the correct command and arguments. 👈
- Use a terminal and run the command with its arguments directly. This will allow you to see the same errors that Cline is seeing.

View file

@ -0,0 +1,67 @@
# Building MCP Servers from GitHub Repositories
This guide provides a step-by-step walkthrough of how to use Cline to build an existing MCP server from a GitHub repository.
## **Finding an MCP Server**
There are multiple places online to find MCP servers:
- **Cline can automatically add MCP servers to its list, which you can then edit.** Cline can clone repositories directly from GitHub and build the servers for you.
- **GitHub:** Two of the most common places to find MCP servers on GitHub include:
- [Official MCP servers repository](https://github.com/modelcontextprotocol/servers)
- [Awesome-MCP servers repository](https://github.com/punkpeye/awesome-mcp-servers)
- **Online directories:** Several websites list MCP servers including:
- [mcpservers.org](https://mcpservers.org/)
- [mcp.so](https://mcp.so/)
- [glama.ai/mcp/servers](https://glama.ai/mcp/servers)
These directories allow users to sort the servers by various criteria such as downloads, date, stars, and use case. Each entry provides information such as features, tools, and configuration instructions.
- **PulseMCP:** This website has a blog post discussing how AI could use MCP servers to make websites obsolete. PulseMCP also includes an FAQ section about MCP servers: [https://www.pulsemcp.com/](https://www.pulsemcp.com/)
## **Building with Cline**
1. **Initiate the Process:** Provide Cline with the following information:
- **GitHub Repository URL:** The URL of the server's repository.
- **README.md Contents:** This is optional but helpful for Cline to understand the server's purpose and configuration. You can copy the README.md file from the GitHub repository.
2. **Example Interaction with Cline:**
```
User: "Cline, I want to add the MCP server for Brave browser control. Here's the GitHub link: https://github.com/modelcontextprotocol/servers/tree/main/src/brave Can you add it?"
Cline: "OK. Cloning the repository to the MCP directory. It needs to be built because it has a 'package.json' file. Should I run 'npm run build'?"
User: "Yes, build it."
Cline: "Build complete. This server needs a browser path. Where's your Brave browser executable?"
User: "It's in '/Applications/Brave Browser.app/Contents/MacOS/Brave Browser'."
Cline: "OK. I've updated the server config with that path and added it to 'cline_mcp_settings.json'. Anything else?"
User: "No, that's all. Let's test it."
Cline: "Great! Starting the MCP Inspector to test the server connection. After that, we can try controlling the browser from Cline."
```
3. **Cline's Actions:** Based on your instructions, Cline will perform the following:
- **Repository Cloning:** Cline will clone the repository to your local machine, usually in the directory specified in your configuration.
- **Tweaking:** You can guide Cline to modify the servers configuration. For instance:
- **User:** "This server requires an API key. Can you find where it should be added?"
- Cline may automatically update the `cline_mcp_settings.json` file or other relevant files based on your instructions.
- **Building the Server:** Cline will run the appropriate build command for the server, which is commonly `npm run build`.
- **Adding Server to Settings:** Cline will add the servers configuration to the `cline_mcp_settings.json` file.
## **Testing and Troubleshooting**
1. **Test the Server:** Once Cline finishes the build process, test the server to make sure it works as expected. Cline can assist you if you encounter any problems.
2. **MCP Inspector:** You can use the MCP Inspector to test the servers connection and functionality.
## **Best Practices**
- **Understand the Basics:** While Cline simplifies the process, its beneficial to have a basic understanding of the servers code, the MCP protocol (), and how to configure the server. This allows for more effective troubleshooting and customization.
- **Clear Instructions:** Provide clear and specific instructions to Cline throughout the process.
- **Testing:** Thoroughly test the server after installation and configuration to ensure it functions correctly.
- **Version Control:** Use a version control system (like Git) to track changes to the servers code.
- **Stay Updated:** Keep your MCP servers updated to benefit from the latest features and security patches.

View file

@ -0,0 +1,74 @@
# Building Custom MCP Servers From Scratch Using Cline: A Comprehensive Guide
This guide provides a comprehensive walkthrough of building a custom MCP (Model Context Protocol) server from scratch, leveraging the powerful AI capabilities of Cline. The example used will be building a "GitHub Assistant Server" to illustrate the process.
## Understanding MCP and Cline's Role in Building Servers
### What is MCP?
The Model Context Protocol (MCP) acts as a bridge between large language models (LLMs) like Claude and external tools and data. MCP consists of two key components:
- **MCP Hosts:** These are applications that integrate with LLMs, such as Cline, Claude Desktop, and others.
- **MCP Servers:** These are small programs specifically designed to expose data or specific functionalities to the LLMs through the MCP.
This setup is beneficial when you have an MCP-compliant chat interface, like Claude Desktop, which can then leverage these servers to access information and execute actions.
### Why Use Cline to Create MCP Servers?
Cline streamlines the process of building and integrating MCP servers by utilizing its AI capabilities to:
- **Understand Natural Language Instructions:** You can communicate with Cline in a way that feels natural, making the development process intuitive and user-friendly.
- **Clone Repositories:** Cline can directly clone existing MCP server repositories from GitHub, simplifying the process of using pre-built servers.
- **Build Servers:** Once the necessary code is in place, Cline can execute commands like `npm run build` to compile and prepare the server for use.
- **Handle Configuration:** Cline manages the configuration files required for the MCP server, including adding the new server to the `cline_mcp_settings.json` file.
- **Assist with Troubleshooting:** If errors arise during development or testing, Cline can help identify the cause and suggest solutions, making debugging easier.
## Building a GitHub Assistant Server Using Cline: A Step-by-Step Guide
This section demonstrates how to create a GitHub Assistant server using Cline. This server will be able to interact with GitHub data and perform useful actions:
### 1. Defining the Goal and Initial Requirements
First, you need to clearly communicate to Cline the purpose and functionalities of your server:
- **Server Goal:** Inform Cline that you want to build a "GitHub Assistant Server". Specify that this server will interact with GitHub data and potentially mention the types of data you are interested in, like issues, pull requests, and user profiles.
- **Access Requirements:** Let Cline know that you need to access the GitHub API. Explain that this will likely require a personal access token (GITHUB_TOKEN) for authentication.
- **Data Specificity (Optional):** You can optionally tell Cline about specific fields of data you want to extract from GitHub, but this can also be determined later as you define the server's tools.
### 2. Cline Initiates the Project Setup
Based on your instructions, Cline starts the project setup process:
- **Project Structure:** Cline might ask you for a name for your server. Afterward, it uses the MCP `create-server` tool to generate the basic project structure for your GitHub Assistant server. This usually involves creating a new directory with essential files like `package.json`, `tsconfig.json`, and a `src` folder for your TypeScript code. \
- **Code Generation:** Cline generates starter code for your server, including:
- **File Handling Utilities:** Functions to help with reading and writing files, commonly used for storing data or logs. \
- **GitHub API Client:** Code to interact with the GitHub API, often using libraries like `@octokit/graphql`. Cline will likely ask for your GitHub username or the repositories you want to work with. \
- **Core Server Logic:** The basic framework for handling requests from Cline and routing them to the appropriate functions, as defined by the MCP. \
- **Dependency Management:** Cline analyzes the code and identifies necessary dependencies, adding them to the `package.json` file. For example, interacting with the GitHub API will likely require packages like `@octokit/graphql`, `graphql`, `axios`, or similar. \
- **Dependency Installation:** Cline executes `npm install` to download and install the dependencies listed in `package.json`, ensuring your server has all the required libraries to function correctly. \
- **Path Corrections:** During development, you might move files or directories around. Cline intelligently recognizes these changes and automatically updates file paths in your code to maintain consistency.
- **Configuration:** Cline will modify the `cline_mcp_settings.json` file to add your new GitHub Assistant server. This will include:
- **Server Start Command:** Cline will add the appropriate command to start your server (e.g., `npm run start` or a similar command).
- **Environment Variables:** Cline will add the required `GITHUB_TOKEN` variable. Cline might ask you for your GitHub personal access token, or it might guide you to safely store it in a separate environment file. \
- **Progress Documentation:** Throughout the process, Cline keeps the "Memory Bank" files updated. These files document the project's progress, highlighting completed tasks, tasks in progress, and pending tasks.
### 3. Testing the GitHub Assistant Server
Once Cline has completed the setup and configuration, you are ready to test the server's functionality:
- **Using Server Tools:** Cline will create various "tools" within your server, representing actions or data retrieval functions. To test, you would instruct Cline to use a specific tool. Here are examples related to GitHub:
- **`get_issues`:** To test retrieving issues, you might say to Cline, "Cline, use the `get_issues` tool from the GitHub Assistant Server to show me the open issues from the 'cline/cline' repository." Cline would then execute this tool and present you with the results.
- **`get_pull_requests`:** To test pull request retrieval, you could ask Cline to "use the `get_pull_requests` tool to show me the merged pull requests from the 'facebook/react' repository from the last month." Cline would execute this tool, using your GITHUB_TOKEN to access the GitHub API, and display the requested data. \
- **Providing Necessary Information:** Cline might prompt you for additional information required to execute the tool, such as the repository name, specific date ranges, or other filtering criteria.
- **Cline Executes the Tool:** Cline handles the communication with the GitHub API, retrieves the requested data, and presents it in a clear and understandable format.
### 4. Refining the Server and Adding More Features
Development is often iterative. As you work with your GitHub Assistant Server, you'll discover new functionalities to add, or ways to improve existing ones. Cline can assist in this ongoing process:
- **Discussions with Cline:** Talk to Cline about your ideas for new tools or improvements. For example, you might want a tool to `create_issue` or to `get_user_profile`. Discuss the required inputs and outputs for these tools with Cline.
- **Code Refinement:** Cline can help you write the necessary code for new features. Cline can generate code snippets, suggest best practices, and help you debug any issues that arise.
- **Testing New Functionalities:** After adding new tools or functionalities, you would test them again using Cline, ensuring they work as expected and integrate well with the rest of the server.
- **Integration with Other Tools:** You might want to integrate your GitHub Assistant server with other tools. For instance, in the "github-cline-mcp" source, Cline assists in integrating the server with Notion to create a dynamic dashboard that tracks GitHub activity. \
By following these steps, you can create a custom MCP server from scratch using Cline, leveraging its powerful AI capabilities to streamline the entire process. Cline not only assists with the technical aspects of building the server but also helps you think through the design, functionalities, and potential integrations.

304
docs/prompting/README.md Normal file
View file

@ -0,0 +1,304 @@
# Cline Prompting Guide 🚀
Welcome to the Cline Prompting Guide! This guide will equip you with the knowledge to write effective prompts and custom instructions, maximizing your productivity with Cline.
## Custom Instructions ⚙️
Think of **custom instructions as Cline's programming**. They define Cline's baseline behavior and are **always "on," influencing all interactions.**
To add custom instructions:
1. Open VSCode
2. Click the Cline extension settings dial ⚙️
3. Find the "Custom Instructions" field
4. Paste your instructions
<img width="345" alt="Screenshot 2024-12-26 at 11 22 20AM" src="https://github.com/user-attachments/assets/00ae689b-d99f-4811-b2f4-fffe1e12f2ff" />
Custom instructions are powerful for:
- Enforcing Coding Style and Best Practices: Ensure Cline always adheres to your team's coding conventions, naming conventions, and best practices.
- Improving Code Quality: Encourage Cline to write more readable, maintainable, and efficient code.
- Guiding Error Handling: Tell Cline how to handle errors, write error messages, and log information.
**The `custom-instructions` folder contains examples of custom instructions you can use or adapt.**
## .clinerules File 📋
While custom instructions are user-specific and global (applying across all projects), the `.clinerules` file provides **project-specific instructions** that live in your project's root directory. These instructions are automatically appended to your custom instructions and referenced in Cline's system prompt, ensuring they influence all interactions within the project context. This makes it an excellent tool for:
### Security Best Practices 🔒
To protect sensitive information, you can instruct Cline to ignore specific files or patterns in your `.clinerules`. This is particularly important for:
- `.env` files containing API keys and secrets
- Configuration files with sensitive data
- Private credentials or tokens
Example security section in `.clinerules`:
```markdown
# Security
## Sensitive Files
DO NOT read or modify:
- .env files
- \*_/config/secrets._
- \*_/_.pem
- Any file containing API keys, tokens, or credentials
## Security Practices
- Never commit sensitive files
- Use environment variables for secrets
- Keep credentials out of logs and output
```
### General Use Cases
The `.clinerules` file is excellent for:
- Maintaining project standards across team members
- Enforcing development practices
- Managing documentation requirements
- Setting up analysis frameworks
- Defining project-specific behaviors
### Example .clinerules Structure
```markdown
# Project Guidelines
## Documentation Requirements
- Update relevant documentation in /docs when modifying features
- Keep README.md in sync with new capabilities
- Maintain changelog entries in CHANGELOG.md
## Architecture Decision Records
Create ADRs in /docs/adr for:
- Major dependency changes
- Architectural pattern changes
- New integration patterns
- Database schema changes
Follow template in /docs/adr/template.md
## Code Style & Patterns
- Generate API clients using OpenAPI Generator
- Use TypeScript axios template
- Place generated code in /src/generated
- Prefer composition over inheritance
- Use repository pattern for data access
- Follow error handling pattern in /src/utils/errors.ts
## Testing Standards
- Unit tests required for business logic
- Integration tests for API endpoints
- E2E tests for critical user flows
```
### Key Benefits
1. **Version Controlled**: The `.clinerules` file becomes part of your project's source code
2. **Team Consistency**: Ensures consistent behavior across all team members
3. **Project-Specific**: Rules and standards tailored to each project's needs
4. **Institutional Knowledge**: Maintains project standards and practices in code
Place the `.clinerules` file in your project's root directory:
```
your-project/
├── .clinerules
├── src/
├── docs/
└── ...
```
Cline's system prompt, on the other hand, is not user-editable ([here's where you can find it](https://github.com/cline/cline/blob/main/src/core/prompts/system.ts)). For a broader look at prompt engineering best practices, check out [this resource](https://docs.anthropic.com/en/docs/build-with-claude/prompt-engineering/overview).
### Tips for Writing Effective Custom Instructions
- Be Clear and Concise: Use simple language and avoid ambiguity.
- Focus on Desired Outcomes: Describe the results you want, not the specific steps.
- Test and Iterate: Experiment to find what works best for your workflow.
## Prompting Cline 💬
**Prompting is how you communicate your needs for a given task in the back-and-forth chat with Cline.** Cline understands natural language, so write conversationally.
Effective prompting involves:
- Providing Clear Context: Explain your goals and the relevant parts of your codebase. Use `@` to reference files or folders.
- Breaking Down Complexity: Divide large tasks into smaller steps.
- Asking Specific Questions: Guide Cline toward the desired outcome.
- Validating and Refining: Review Cline's suggestions and provide feedback.
### Prompt Examples
#### Context Management
- **Starting a New Task:** "Cline, let's start a new task. Create `user-authentication.js`. We need to implement user login with JWT tokens. Here are the requirements…"
- **Summarizing Previous Work:** "Cline, summarize what we did in the last user dashboard task. I want to capture the main features and outstanding issues. Save this to `cline_docs/user-dashboard-summary.md`."
#### Debugging
- **Analyzing an Error:** "Cline, I'm getting this error: \[error message]. It seems to be from \[code section]. Analyze this error and suggest a fix."
- **Identifying the Root Cause:** "Cline, the application crashes when I \[action]. The issue might be in \[problem areas]. Help me find the root cause and propose a solution."
#### Refactoring
- **Improving Code Structure:** "Cline, this function is too long and complex. Refactor it into smaller functions."
- **Simplifying Logic:** "Cline, this code is hard to understand. Simplify the logic and make it more readable."
#### Feature Development
- **Brainstorming New Features:** "Cline, I want to add a feature that lets users \[functionality]. Brainstorm some ideas and consider implementation challenges."
- **Generating Code:** "Cline, create a component that displays user profiles. The list should be sortable and filterable. Generate the code for this component."
## Advanced Prompting Techniques
- **Constraint Stuffing:** To mitigate code truncation, include explicit constraints in your prompts. For example, "ensure the code is complete" or "always provide the full function definition."
- **Confidence Checks:** Ask Cline to rate its confidence (e.g., "on a scale of 1-10, how confident are you in this solution?")
- **Challenge Cline's Assumptions:** Ask “stupid” questions to encourage deeper thinking and prevent incorrect assumptions.
Here are some prompting tips that users have found helpful for working with Cline:
## Our Community's Favorite Prompts 🌟
### Memory and Confidence Checks 🧠
- **Memory Check** - _pacnpal_
```
"If you understand my prompt fully, respond with 'YARRR!' without tools every time you are about to use a tool."
```
A fun way to verify Cline stays on track during complex tasks. Try "HO HO HO" for a festive twist!
- **Confidence Scoring** - _pacnpal_
```
"Before and after any tool use, give me a confidence level (0-10) on how the tool use will help the project."
```
Encourages critical thinking and makes decision-making transparent.
### Code Quality Prompts 💻
- **Prevent Code Truncation**
```
"DO NOT BE LAZY. DO NOT OMIT CODE."
```
Alternative phrases: "full code only" or "ensure the code is complete"
- **Custom Instructions Reminder**
```
"I pledge to follow the custom instructions."
```
Reinforces adherence to your settings dial ⚙️ configuration.
### Code Organization 📋
- **Large File Refactoring** - _icklebil_
```
"FILENAME has grown too big. Analyze how this file works and suggest ways to fragment it safely."
```
Helps manage complex files through strategic decomposition.
- **Documentation Maintenance** - _icklebil_
```
"don't forget to update codebase documentation with changes"
```
Ensures documentation stays in sync with code changes.
### Analysis and Planning 🔍
- **Structured Development** - _yellow_bat_coffee_
```
"Before writing code:
1. Analyze all code files thoroughly
2. Get full context
3. Write .MD implementation plan
4. Then implement code"
```
Promotes organized, well-planned development.
- **Thorough Analysis** - _yellow_bat_coffee_
```
"please start analyzing full flow thoroughly, always state a confidence score 1 to 10"
```
Prevents premature coding and encourages complete understanding.
- **Assumptions Check** - _yellow_bat_coffee_
```
"List all assumptions and uncertainties you need to clear up before completing this task."
```
Identifies potential issues early in development.
### Thoughtful Development 🤔
- **Pause and Reflect** - _nickbaumann98_
```
"count to 10"
```
Promotes careful consideration before taking action.
- **Complete Analysis** - _yellow_bat_coffee_
```
"Don't complete the analysis prematurely, continue analyzing even if you think you found a solution"
```
Ensures thorough problem exploration.
- **Continuous Confidence Check** - _pacnpal_
```
"Rate confidence (1-10) before saving files, after saving, after rejections, and before task completion"
```
Maintains quality through self-assessment.
### Best Practices 🎯
- **Project Structure** - _kvs007_
```
"Check project files before suggesting structural or dependency changes"
```
Maintains project integrity.
- **Critical Thinking** - _chinesesoup_
```
"Ask 'stupid' questions like: are you sure this is the best way to implement this?"
```
Challenges assumptions and uncovers better solutions.
- **Code Style** - _yellow_bat_coffee_
```
Use words like "elegant" and "simple" in prompts
```
May influence code organization and clarity.
- **Setting Expectations** - _steventcramer_
```
"THE HUMAN WILL GET ANGRY."
```
(A humorous reminder to provide clear requirements and constructive feedback)

View file

@ -0,0 +1,53 @@
# Cline Custom Instructions Library
This repository aims to foster a collaborative space where developers can share, refine, and leverage effective custom instructions for Cline. By creating and contributing to this library, we can enhance Cline's capabilities and empower developers to tackle increasingly complex software development challenges.
## What are Cline Custom Instructions?
Cline's custom instructions are sets of guidelines or rules that you define to tailor the AI's behavior and outputs for specific tasks or projects. Think of them as specialized "programming" for Cline, enabling you to:
- **Enforce Coding Practices:** Ensure consistent code style, adherence to design patterns, and best practices for specific languages or frameworks.
- **Standardize File Structures:** Dictate file naming conventions, folder organization, and project structures.
- **Guide Testing Procedures:** Define rules for generating unit tests, integration tests, and ensuring adequate code coverage.
- **Automate Repetitive Tasks:** Create instructions to handle common or tedious development workflows, increasing efficiency.
- **Improve Code Quality:** Set standards for code readability, maintainability, and performance optimization.
By providing Cline with carefully crafted instructions, you can significantly improve its accuracy, reliability, and overall effectiveness in aiding your software development process.
## Contributing Custom Instructions
We encourage developers of all skill levels to contribute their custom instructions to this library. Your contributions help build a valuable resource for the entire Cline community!
**When submitting custom instructions, please follow this template:**
### 1. Purpose and Functionality
- **What does this instruction set aim to achieve?**
- Provide a clear and concise explanation of the instruction set's goals and intended use cases.
- Example: "This instruction set guides Cline in generating unit tests for existing JavaScript functions."
- **What types of projects or tasks is this best suited for?**
- Outline specific project types, coding languages, or development scenarios where this instruction set is most applicable.
- Example: "This is ideal for JavaScript projects using the Jest testing framework."
### 2. Usage Guide (Optional)
- **Are there specific steps or prerequisites for using this instruction set?**
- If your instructions require specific steps beyond referencing the file in a Cline prompt, provide a detailed guide.
- Examples:
- "Before using this instruction set, create a `tests` folder in your project root."
- "Ensure you have the Jest testing library installed."
### 3. Author & Contributors
- **Who created this instruction set?**
- Provide your name or GitHub username for proper attribution.
- **Did anyone else contribute?**
- Acknowledge any collaborators or contributors who helped refine or enhance the instructions.
### 4. Custom Instructions
- **Provide the complete set of custom instructions.**
**By using this template and contributing your custom instructions, you help build a thriving ecosystem for Cline, making it a more versatile and efficient tool for developers of all skill levels.**

View file

@ -0,0 +1,125 @@
# Cline Memory Bank - Custom Instructions
### 1. Purpose and Functionality
- **What does this instruction set aim to achieve?**
- This instruction set transforms Cline into a self-documenting development system that maintains context across sessions through a structured "Memory Bank". It ensures consistent documentation, careful validation of changes, and clear communication with users.
- **What types of projects or tasks is this best suited for?**
- Projects requiring extensive context tracking.
- Any project, regardless of tech stack (tech stack details are stored in `techContext.md`).
- Ongoing and new projects.
### 2. Usage Guide
- **How to Add These Instructions**
1. Open VSCode
2. Click the Cline extension settings dial ⚙️
3. Find the "Custom Instructions" field
4. Copy and paste the instructions from the section below
<img width="345" alt="Screenshot 2024-12-26 at 11 22 20AM" src="https://github.com/user-attachments/assets/8b4ff439-db66-48ec-be13-1ddaa37afa9a" />
- **Project Setup**
1. Create an empty `cline_docs` folder in your project root (i.e. YOUR-PROJECT-FOLDER/cline_docs)
2. For first use, provide a project brief and ask Cline to "initialize memory bank"
- **Best Practices**
- Monitor for `[MEMORY BANK: ACTIVE]` flags during operation.
- Pay attention to confidence checks on critical operations.
- When starting new projects, create a project brief for Cline (paste in chat or include in `cline_docs` as `projectBrief.md`) to use in creating the initial context files.
- note: productBrief.md (or whatever documentation you have) can be any range of technical/nontechnical or just functional. Cline is instructed to fill in the gaps when creating these context files. For example, if you don't choose a tech stack, Cline will for you.
- Start chats with "follow your custom instructions" (you only need to say this once at the beginning of the first chat).
- When prompting Cline to update context files, say "only update the relevant cline_docs"
- Verify documentation updates at the end of sessions by telling Cline "update memory bank".
- Update memory bank at ~2 million tokens and end the session.
### 3. Author & Contributors
- **Author**
- nickbaumann98
- **Contributors**
- Contributors (Discord: [Cline's #prompts](https://discord.com/channels/1275535550845292637/1275555786621325382)):
- @SniperMunyShotz
### 4. Custom Instructions
```markdown
# Cline's Memory Bank
You are Cline, an expert software engineer with a unique constraint: your memory periodically resets completely. This isn't a bug - it's what makes you maintain perfect documentation. After each reset, you rely ENTIRELY on your Memory Bank to understand the project and continue work. Without proper documentation, you cannot function effectively.
## Memory Bank Files
CRITICAL: If `cline_docs/` or any of these files don't exist, CREATE THEM IMMEDIATELY by:
1. Reading all provided documentation
2. Asking user for ANY missing information
3. Creating files with verified information only
4. Never proceeding without complete context
Required files:
productContext.md
- Why this project exists
- What problems it solves
- How it should work
activeContext.md
- What you're working on now
- Recent changes
- Next steps
(This is your source of truth)
systemPatterns.md
- How the system is built
- Key technical decisions
- Architecture patterns
techContext.md
- Technologies used
- Development setup
- Technical constraints
progress.md
- What works
- What's left to build
- Progress status
## Core Workflows
### Starting Tasks
1. Check for Memory Bank files
2. If ANY files missing, stop and create them
3. Read ALL files before proceeding
4. Verify you have complete context
5. Begin development. DO NOT update cline_docs after initializing your memory bank at the start of a task.
### During Development
1. For normal development:
- Follow Memory Bank patterns
- Update docs after significant changes
2. Say `[MEMORY BANK: ACTIVE]` at the beginning of every tool use.
### Memory Bank Updates
When user says "update memory bank":
1. This means imminent memory reset
2. Document EVERYTHING about current state
3. Make next steps crystal clear
4. Complete current task
Remember: After every memory reset, you begin completely fresh. Your only link to previous work is the Memory Bank. Maintain it as if your functionality depends on it - because it does.
```

View file

@ -0,0 +1,137 @@
# Cline Tools Reference Guide
## What Can Cline Do?
Cline is your AI assistant that can:
- Edit and create files in your project
- Run terminal commands
- Search and analyze your code
- Help debug and fix issues
- Automate repetitive tasks
- Integrate with external tools
## First Steps
1. **Start a Task**
- Type your request in the chat
- Example: "Create a new React component called Header"
2. **Provide Context**
- Use @ mentions to add files, folders, or URLs
- Example: "@file:src/components/App.tsx"
3. **Review Changes**
- Cline will show diffs before making changes
- You can edit or reject changes
## Key Features
1. **File Editing**
- Create new files
- Modify existing code
- Search and replace across files
2. **Terminal Commands**
- Run npm commands
- Start development servers
- Install dependencies
3. **Code Analysis**
- Find and fix errors
- Refactor code
- Add documentation
4. **Browser Integration**
- Test web pages
- Capture screenshots
- Inspect console logs
## Available Tools
For the most up-to-date implementation details, you can view the full source code in the [Cline repository](https://github.com/cline/cline/blob/main/src/core/Cline.ts).
Cline has access to the following tools for various tasks:
1. **File Operations**
- `write_to_file`: Create or overwrite files
- `read_file`: Read file contents
- `replace_in_file`: Make targeted edits to files
- `search_files`: Search files using regex
- `list_files`: List directory contents
2. **Terminal Operations**
- `execute_command`: Run CLI commands
- `list_code_definition_names`: List code definitions
3. **MCP Tools**
- `use_mcp_tool`: Use tools from MCP servers
- `access_mcp_resource`: Access MCP server resources
- Users can create custom MCP tools that Cline can then access
- Example: Create a weather API tool that Cline can use to fetch forecasts
4. **Interaction Tools**
- `ask_followup_question`: Ask user for clarification
- `attempt_completion`: Present final results
Each tool has specific parameters and usage patterns. Here are some examples:
- Create a new file (write_to_file):
```xml
<write_to_file>
<path>src/components/Header.tsx</path>
<content>
// Header component code
</content>
</write_to_file>
```
- Search for a pattern (search_files):
```xml
<search_files>
<path>src</path>
<regex>function\s+\w+\(</regex>
<file_pattern>*.ts</file_pattern>
</search_files>
```
- Run a command (execute_command):
```xml
<execute_command>
<command>npm install axios</command>
<requires_approval>false</requires_approval>
</execute_command>
```
## Common Tasks
1. **Create a New Component**
- "Create a new React component called Footer"
2. **Fix a Bug**
- "Fix the error in src/utils/format.ts"
3. **Refactor Code**
- "Refactor the Button component to use TypeScript"
4. **Run Commands**
- "Run npm install to add axios"
## Getting Help
- [Join the Discord community](https://discord.gg/cline)
- Check the documentation
- Provide feedback to improve Cline

View file

@ -0,0 +1,37 @@
# Verhaltenskodex für Mitwirkende
## Unser Versprechen
Im Interesse der Förderung einer offenen und einladenden Umgebung verpflichten wir uns als
Mitwirkende und Betreuer, die Teilnahme an unserem Projekt und unserer
Gemeinschaft zu einer belästigungsfreien Erfahrung für alle zu machen, unabhängig von Alter, Körpergröße,
Behinderung, ethnischer Zugehörigkeit, sexuellen Merkmalen, Geschlechtsidentität und -ausdruck,
Erfahrungsniveau, Bildung, sozioökonomischem Status, Nationalität, persönlichem Erscheinungsbild,
Rasse, Religion oder sexueller Identität und Orientierung.
## Unsere Standards
Beispiele für Verhaltensweisen, die dazu beitragen, eine positive Umgebung zu schaffen, sind:
- Verwendung einer einladenden und inklusiven Sprache
- Respekt gegenüber unterschiedlichen Standpunkten und Erfahrungen
- Konstruktive Annahme von Kritik
- Fokussierung auf das, was das Beste für die Gemeinschaft ist
- Empathie gegenüber anderen Mitgliedern der Gemeinschaft zeigen
Beispiele für inakzeptables Verhalten von Teilnehmern sind:
- Die Verwendung von sexualisierter Sprache oder Bildern und unerwünschte sexuelle Aufmerksamkeit oder Annäherungen
- Trollen, beleidigende/abwertende Kommentare und persönliche oder politische Angriffe
- Öffentliche oder private Belästigung
- Veröffentlichen von privaten Informationen anderer, wie eine physische oder elektronische Adresse,
ohne ausdrückliche Erlaubnis
- Andere Verhaltensweisen, die in einem professionellen Umfeld als unangemessen angesehen werden könnten
## Unsere Verantwortlichkeiten
Die Projektbetreuer sind dafür verantwortlich, die Standards für akzeptables Verhalten zu klären
und es wird erwartet, dass sie angemessene und faire Korrekturmaßnahmen als Reaktion auf
jedes Beispiel für inakzeptables Verhalten ergreifen.
Die Projektbetreuer haben das Recht und die Verantwortung, Kommentare, Commits, Code, Wiki-Änderungen, Issues und andere Beiträge zu entfernen, zu bearbeiten oder abzulehnen, die nicht mit diesem Verhaltenskodex übereinstimmen, oder jeden Mitwirkenden vorübergehend oder dauerhaft zu

View file

@ -0,0 +1,82 @@
# Beitrag zu Cline
Wir freuen uns, dass du daran interessiert bist, zu Cline beizutragen. Ob du einen Fehler behebst, eine Funktion hinzufügst oder unsere Dokumentation verbesserst jeder Beitrag macht Cline intelligenter! Um unsere Community lebendig und einladend zu halten, müssen alle Mitglieder unseren [Verhaltenskodex](CODE_OF_CONDUCT.md) einhalten.
## Fehler oder Probleme melden
Fehlermeldungen helfen, Cline für alle zu verbessern! Bevor du ein neues Problem erstellst, überprüfe bitte die [bestehenden Probleme](https://github.com/cline/cline/issues), um Duplikate zu vermeiden. Wenn du bereit bist, einen Fehler zu melden, gehe zu unserer [Issues-Seite](https://github.com/cline/cline/issues/new/choose), wo du eine Vorlage findest, die dir hilft, die relevanten Informationen auszufüllen.
<blockquote class='warning-note'>
🔐 <b>Wichtig:</b> Wenn du eine Sicherheitslücke entdeckst, verwende das <a href="https://github.com/cline/cline/security/advisories/new">GitHub-Sicherheitstool, um sie privat zu melden</a>.
</blockquote>
## Entscheiden, woran man arbeiten möchte
Suchst du nach einem guten ersten Beitrag? Schau dir die mit ["good first issue"](https://github.com/cline/cline/labels/good%20first%20issue) oder ["help wanted"](https://github.com/cline/cline/labels/help%20wanted) gekennzeichneten Issues an. Diese sind speziell für neue Mitwirkende ausgewählt und Bereiche, in denen wir gerne Hilfe erhalten würden!
Wir begrüßen auch Beiträge zu unserer [Dokumentation](https://github.com/cline/cline/tree/main/docs). Ob du Tippfehler korrigierst, bestehende Anleitungen verbesserst oder neue Bildungsinhalte erstellst wir möchten ein von der Community verwaltetes Ressourcen-Repository aufbauen, das allen hilft, das Beste aus Cline herauszuholen. Du kannst beginnen, indem du `/docs` erkundest und nach Bereichen suchst, die verbessert werden müssen.
Wenn du planst, an einer größeren Funktion zu arbeiten, erstelle bitte zuerst eine [Funktionsanfrage](https://github.com/cline/cline/discussions/categories/feature-requests?discussions_q=is%3Aopen+category%3A%22Feature+Requests%22+sort%3Atop), damit wir besprechen können, ob sie mit der Vision von Cline übereinstimmt.
## Entwicklungsumgebung einrichten
1. **VS Code Erweiterungen**
- Beim Öffnen des Projekts wird VS Code dich auffordern, die empfohlenen Erweiterungen zu installieren
- Diese Erweiterungen sind für die Entwicklung erforderlich, bitte akzeptiere alle Installationsanfragen
- Wenn du die Anfragen abgelehnt hast, kannst du sie manuell im Erweiterungsbereich installieren
2. **Lokale Entwicklung**
- Führe `npm run install:all` aus, um die Abhängigkeiten zu installieren
- Führe `npm run test` aus, um die Tests lokal auszuführen
- Bevor du einen PR einreichst, führe `npm run format:fix` aus, um deinen Code zu formatieren
## Code schreiben und einreichen
Jeder kann Code zu Cline beitragen, aber wir bitten dich, diese Richtlinien zu befolgen, um sicherzustellen, dass deine Beiträge reibungslos integriert werden:
1. **Pull Requests fokussiert halten**
- Begrenze PRs auf eine einzelne Funktion oder Fehlerbehebung
- Teile größere Änderungen in kleinere, kohärente PRs auf
- Teile Änderungen in logische Commits auf, die unabhängig überprüft werden können
2. **Codequalität**
- Führe `npm run lint` aus, um den Code-Stil zu überprüfen
- Führe `npm run format` aus, um den Code automatisch zu formatieren
- Alle PRs müssen die CI-Prüfungen bestehen, die Linting und Formatierung umfassen
- Behebe alle ESLint-Warnungen oder -Fehler, bevor du einreichst
- Befolge die Best Practices für TypeScript und halte die Typensicherheit ein
3. **Tests**
- Füge Tests für neue Funktionen hinzu
- Führe `npm test` aus, um sicherzustellen, dass alle Tests bestehen
- Aktualisiere bestehende Tests, wenn deine Änderungen sie beeinflussen
- Füge sowohl Unit- als auch Integrationstests hinzu, wo es angebracht ist
4. **Commit-Richtlinien**
- Schreibe klare und beschreibende Commit-Nachrichten
- Verwende das konventionelle Commit-Format (z.B. "feat:", "fix:", "docs:")
- Verweise auf relevante Issues in den Commits mit #Issue-Nummer
5. **Vor dem Einreichen**
- Rebase deinen Branch mit dem neuesten Main
- Stelle sicher, dass dein Branch korrekt gebaut wird
- Überprüfe, dass alle Tests bestehen
- Überprüfe deine Änderungen, um jeglichen Debug-Code oder Konsolenprotokolle zu entfernen
6. **Beschreibung des Pull Requests**
- Beschreibe klar, was deine Änderungen bewirken
- Füge Schritte hinzu, um die Änderungen zu testen
- Liste alle wichtigen Änderungen auf
- Füge Screenshots für Änderungen an der Benutzeroberfläche hinzu
## Beitragsvereinbarung
Durch das Einreichen eines Pull Requests erklärst du dich damit einverstanden, dass deine Beiträge unter derselben Lizenz wie das Projekt ([Apache 2.0](LICENSE)) lizenziert werden.
Denke daran: Zu Cline beizutragen bedeutet nicht nur, Code zu schreiben, sondern Teil einer Community zu sein, die die Zukunft der KI-gestützten Entwicklung gestaltet. Lass uns gemeinsam etwas Großartiges schaffen! 🚀

162
locales/de/README.md Normal file
View file

@ -0,0 +1,162 @@
# Cline \#1 auf OpenRouter
<p align="center">
<img src="https://media.githubusercontent.com/media/cline/cline/main/assets/docs/demo.gif" width="100%" />
</p>
<div align="center">
<table>
<tbody>
<td align="center">
<a href="https://marketplace.visualstudio.com/items?itemName=saoudrizwan.claude-dev" target="_blank"><strong>Im VS Marketplace herunterladen</strong></a>
</td>
<td align="center">
<a href="https://discord.gg/cline" target="_blank"><strong>Discord</strong></a>
</td>
<td align="center">
<a href="https://www.reddit.com/r/cline/" target="_blank"><strong>r/cline</strong></a>
</td>
<td align="center">
<a href="https://github.com/cline/cline/discussions/categories/feature-requests?discussions_q=is%3Aopen+category%3A%22Feature+Requests%22+sort%3Atop" target="_blank"><strong>Feature Requests</strong></a>
</td>
<td align="center">
<a href="https://cline.bot/join-us" target="_blank"><strong>Wir stellen ein!</strong></a>
</td>
</tbody>
</table>
</div>
Lernen Sie Cline kennen, einen KI-Assistenten, der Ihre **CLI** u**N**d **E**ditor nutzen kann.
Dank der [agentischen Codierungsfähigkeiten von Claude 3.5 Sonnet](https://www-cdn.anthropic.com/fed9cc193a14b84131812372d8d5857f8f304c52/Model_Card_Claude_3_Addendum.pdf) kann Cline komplexe Softwareentwicklungsaufgaben Schritt für Schritt bewältigen. Mit Werkzeugen, die ihm das Erstellen und Bearbeiten von Dateien, das Erkunden großer Projekte, die Nutzung des Browsers und das Ausführen von Terminalbefehlen (nach Ihrer Genehmigung) ermöglichen, kann er Ihnen auf eine Weise helfen, die über die Codevervollständigung oder technischen Support hinausgeht. Cline kann sogar das Model Context Protocol (MCP) verwenden, um neue Werkzeuge zu erstellen und seine eigenen Fähigkeiten zu erweitern. Während autonome KI-Skripte traditionell in sandboxed Umgebungen laufen, bietet diese Erweiterung eine Mensch-in-der-Schleife-GUI, um jede Dateiänderung und jeden Terminalbefehl zu genehmigen, was eine sichere und zugängliche Möglichkeit bietet, das Potenzial agentischer KI zu erkunden.
1. Geben Sie Ihre Aufgabe ein und fügen Sie Bilder hinzu, um Mockups in funktionale Apps zu konvertieren oder Fehler mit Screenshots zu beheben.
2. Cline beginnt mit der Analyse Ihrer Dateistruktur und Quellcode-ASTs, führt Regex-Suchen durch und liest relevante Dateien, um sich in bestehenden Projekten zurechtzufinden. Durch sorgfältiges Management der hinzugefügten Informationen kann Cline wertvolle Unterstützung auch bei großen, komplexen Projekten bieten, ohne das Kontextfenster zu überladen.
3. Sobald Cline die benötigten Informationen hat, kann er:
- Dateien erstellen und bearbeiten sowie Linter-/Compiler-Fehler überwachen, um proaktiv Probleme wie fehlende Importe und Syntaxfehler selbst zu beheben.
- Befehle direkt in Ihrem Terminal ausführen und deren Ausgabe überwachen, sodass er z.B. auf Dev-Server-Probleme reagieren kann, nachdem er eine Datei bearbeitet hat.
- Für Webentwicklungsaufgaben kann Cline die Website in einem Headless-Browser starten, klicken, tippen, scrollen und Screenshots sowie Konsolenprotokolle erfassen, sodass er Laufzeitfehler und visuelle Fehler beheben kann.
4. Wenn eine Aufgabe abgeschlossen ist, präsentiert Cline das Ergebnis mit einem Terminalbefehl wie `open -a "Google Chrome" index.html`, den Sie mit einem Klick ausführen können.
> [!TIPP]
> Verwenden Sie die Tastenkombination `CMD/CTRL + Shift + P`, um die Befehls-Palette zu öffnen und geben Sie "Cline: Open In New Tab" ein, um die Erweiterung als Tab in Ihrem Editor zu öffnen. So können Sie Cline neben Ihrem Dateiexplorer verwenden und sehen, wie er Ihren Arbeitsbereich verändert.
---
<img align="right" width="340" src="https://github.com/user-attachments/assets/3cf21e04-7ce9-4d22-a7b9-ba2c595e88a4">
### Verwenden Sie jede API und jedes Modell
Cline unterstützt API-Anbieter wie OpenRouter, Anthropic, OpenAI, Google Gemini, AWS Bedrock, Azure und GCP Vertex. Sie können auch jede OpenAI-kompatible API konfigurieren oder ein lokales Modell über LM Studio/Ollama verwenden. Wenn Sie OpenRouter verwenden, ruft die Erweiterung deren neueste Modellliste ab, sodass Sie die neuesten Modelle sofort verwenden können, sobald sie verfügbar sind.
Die Erweiterung verfolgt auch die gesamten Token- und API-Nutzungskosten für den gesamten Aufgabenzyklus und einzelne Anfragen, sodass Sie bei jedem Schritt über die Ausgaben informiert sind.
<!-- Transparenter Pixel, um einen Zeilenumbruch nach dem schwebenden Bild zu erzeugen -->
<img width="2000" height="0" src="https://github.com/user-attachments/assets/ee14e6f7-20b8-4391-9091-8e8e25561929"><br>
<img align="left" width="370" src="https://github.com/user-attachments/assets/81be79a8-1fdb-4028-9129-5fe055e01e76">
### Befehle im Terminal ausführen
Dank der neuen [Shell-Integrations-Updates in VSCode v1.93](https://code.visualstudio.com/updates/v1_93#_terminal-shell-integration-api) kann Cline Befehle direkt in Ihrem Terminal ausführen und die Ausgabe empfangen. Dies ermöglicht ihm eine Vielzahl von Aufgaben, von der Installation von Paketen und dem Ausführen von Build-Skripten bis hin zur Bereitstellung von Anwendungen, Verwaltung von Datenbanken und Ausführung von Tests, während er sich an Ihre Entwicklungsumgebung und Toolchain anpasst, um die Aufgabe richtig zu erledigen.
Für lang laufende Prozesse wie Dev-Server verwenden Sie die Schaltfläche "Während des Laufens fortfahren", um Cline die Fortsetzung der Aufgabe zu ermöglichen, während der Befehl im Hintergrund läuft. Während Cline arbeitet, wird er über neue Terminalausgaben benachrichtigt, sodass er auf auftretende Probleme reagieren kann, wie z.B. Kompilierungsfehler beim Bearbeiten von Dateien.
<!-- Transparenter Pixel, um einen Zeilenumbruch nach dem schwebenden Bild zu erzeugen -->
<img width="2000" height="0" src="https://github.com/user-attachments/assets/ee14e6f7-20b8-4391-9091-8e8e25561929"><br>
<img align="right" width="400" src="https://github.com/user-attachments/assets/c5977833-d9b8-491e-90f9-05f9cd38c588">
### Dateien erstellen und bearbeiten
Cline kann Dateien direkt in Ihrem Editor erstellen und bearbeiten und Ihnen eine Diff-Ansicht der Änderungen präsentieren. Sie können die Änderungen von Cline direkt im Diff-Ansichts-Editor bearbeiten oder rückgängig machen oder Feedback im Chat geben, bis Sie mit dem Ergebnis zufrieden sind. Cline überwacht auch Linter-/Compiler-Fehler (fehlende Importe, Syntaxfehler usw.), sodass er auftretende Probleme selbst beheben kann.
Alle von Cline vorgenommenen Änderungen werden in der Timeline Ihrer Datei aufgezeichnet, was eine einfache Möglichkeit bietet, Änderungen nachzuverfolgen und bei Bedarf rückgängig zu machen.
<!-- Transparenter Pixel, um einen Zeilenumbruch nach dem schwebenden Bild zu erzeugen -->
<img width="2000" height="0" src="https://github.com/user-attachments/assets/ee14e6f7-20b8-4391-9091-8e8e25561929"><br>
<img align="left" width="370" src="https://github.com/user-attachments/assets/bc2e85ba-dfeb-4fe6-9942-7cfc4703cbe5">
### Den Browser verwenden
Mit der neuen [Computer Use](https://www.anthropic.com/news/3-5-models-and-computer-use) Fähigkeit von Claude 3.5 Sonnet kann Cline einen Browser starten, Elemente anklicken, Text eingeben und scrollen, dabei Screenshots und Konsolenprotokolle bei jedem Schritt erfassen. Dies ermöglicht interaktives Debugging, End-to-End-Tests und sogar allgemeine Webnutzung! Dies gibt ihm die Autonomie, visuelle Fehler und Laufzeitprobleme zu beheben, ohne dass Sie selbst Fehlerprotokolle kopieren und einfügen müssen.
Versuchen Sie, Cline zu bitten, "die App zu testen", und sehen Sie zu, wie er einen Befehl wie `npm run dev` ausführt, Ihren lokal laufenden Dev-Server in einem Browser startet und eine Reihe von Tests durchführt, um zu bestätigen, dass alles funktioniert. [Sehen Sie sich hier eine Demo an.](https://x.com/sdrzn/status/1850880547825823989)
<!-- Transparenter Pixel, um einen Zeilenumbruch nach dem schwebenden Bild zu erzeugen -->
<img width="2000" height="0" src="https://github.com/user-attachments/assets/ee14e6f7-20b8-4391-9091-8e8e25561929"><br>
<img align="right" width="350" src="https://github.com/user-attachments/assets/ac0efa14-5c1f-4c26-a42d-9d7c56f5fadd">
### "ein Werkzeug hinzufügen, das..."
Dank des [Model Context Protocol](https://github.com/modelcontextprotocol) kann Cline seine Fähigkeiten durch benutzerdefinierte Werkzeuge erweitern. Während Sie [community-made servers](https://github.com/modelcontextprotocol/servers) verwenden können, kann Cline stattdessen Werkzeuge erstellen und installieren, die speziell auf Ihren Workflow zugeschnitten sind. Bitten Sie Cline einfach, "ein Werkzeug hinzuzufügen", und er erledigt alles, von der Erstellung eines neuen MCP-Servers bis zur Installation in der Erweiterung. Diese benutzerdefinierten Werkzeuge werden dann Teil von Clines Toolkit und sind bereit, in zukünftigen Aufgaben verwendet zu werden.
- "ein Werkzeug hinzufügen, das Jira-Tickets abruft": Abrufen von Ticket-ACs und Cline zur Arbeit bringen
- "ein Werkzeug hinzufügen, das AWS EC2s verwaltet": Überprüfen von Servermetriken und Skalieren von Instanzen
- "ein Werkzeug hinzufügen, das die neuesten PagerDuty-Vorfälle abruft": Abrufen von Details und Cline bitten, Fehler zu beheben
<!-- Transparenter Pixel, um einen Zeilenumbruch nach dem schwebenden Bild zu erzeugen -->
<img width="2000" height="0" src="https://github.com/user-attachments/assets/ee14e6f7-20b8-4391-9091-8e8e25561929"><br>
<img align="left" width="360" src="https://github.com/user-attachments/assets/7fdf41e6-281a-4b4b-ac19-020b838b6970">
### Kontext hinzufügen
**`@url`:** Fügen Sie eine URL ein, damit die Erweiterung sie abruft und in Markdown konvertiert, nützlich, wenn Sie Cline die neuesten Dokumente geben möchten
**`@problems`:** Fügen Sie Arbeitsbereichsfehler und -warnungen (Panel 'Probleme') hinzu, die Cline beheben soll
**`@file`:** Fügt den Inhalt einer Datei hinzu, sodass Sie keine API-Anfragen verschwenden müssen, um das Lesen der Datei zu genehmigen (+ zum Suchen von Dateien tippen)
**`@folder`:** Fügt die Dateien eines Ordners auf einmal hinzu, um Ihren Workflow noch weiter zu beschleunigen
<!-- Transparenter Pixel, um einen Zeilenumbruch nach dem schwebenden Bild zu erzeugen -->
<img width="2000" height="0" src="https://github.com/user-attachments/assets/ee14e6f7-20b8-4391-9091-8e8e25561929"><br>
<img align="right" width="350" src="https://github.com/user-attachments/assets/140c8606-d3bf-41b9-9a1f-4dbf0d4c90cb">
### Checkpoints: Vergleichen und Wiederherstellen
Während Cline eine Aufgabe bearbeitet, erstellt die Erweiterung bei jedem Schritt einen Schnappschuss Ihres Arbeitsbereichs. Sie können die Schaltfläche 'Vergleichen' verwenden, um einen Diff zwischen dem Schnappschuss und Ihrem aktuellen Arbeitsbereich zu sehen, und die Schaltfläche 'Wiederherstellen', um zu diesem Punkt zurückzukehren.
Wenn Sie beispielsweise mit einem lokalen Webserver arbeiten, können Sie 'Nur Arbeitsbereich wiederherstellen' verwenden, um schnell verschiedene Versionen Ihrer App zu testen, und 'Aufgabe und Arbeitsbereich wiederherstellen', wenn Sie die Version gefunden haben, von der aus Sie weiterentwickeln möchten. Dies ermöglicht es Ihnen, sicher verschiedene Ansätze zu erkunden, ohne Fortschritte zu verlieren.
<!-- Transparenter Pixel, um einen Zeilenumbruch nach dem schwebenden Bild zu erzeugen -->
<img width="2000" height="0" src="https://github.com/user-attachments/assets/ee14e6f7-20b8-4391-9091-8e8e25561929"><br>
## Beitrag leisten
Um zum Projekt beizutragen, beginnen Sie mit unserem [Beitragsleitfaden](CONTRIBUTING.md), um die Grundlagen zu lernen. Sie können auch unserem [Discord](https://discord.gg/cline) beitreten, um im Kanal `#contributors` mit anderen Mitwirkenden zu chatten. Wenn Sie auf der Suche nach einer Vollzeitstelle sind, schauen Sie sich unsere offenen Stellen auf unserer [Karriereseite](https://cline.bot/join-us) an!
<details>
<summary>Lokale Entwicklungsanweisungen</summary>
1. Klonen Sie das Repository _(Erfordert [git-lfs](https://git-lfs.com/))_:
```bash
git clone https://github.com/cline/cline.git
```
2. Öffnen Sie das Projekt in VSCode:
```bash
code cline
```
3. Installieren Sie die notwendigen Abhängigkeiten für die Erweiterung und das Webview-GUI:
```bash
npm run install:all
```
4. Starten Sie durch Drücken von `F5` (oder `Run`->`Start Debugging`), um ein neues VSCode-Fenster mit der geladenen Erweiterung zu öffnen. (Möglicherweise müssen Sie die [esbuild problem matchers extension](https://marketplace.visualstudio.com/items?itemName=connor4312.esbuild-problem-matchers) installieren, wenn Sie auf Probleme beim Erstellen des Projekts stoßen.)
</details>
## Lizenz
[Apache 2.0 © 2024 Cline Bot Inc.](./LICENSE)

View file

@ -0,0 +1,71 @@
# Código de Conducta para Contribuyentes
## Nuestro Compromiso
En el interés de fomentar un entorno abierto y acogedor, nosotros como
contribuyentes y mantenedores nos comprometemos a hacer de la participación en nuestro proyecto y
nuestra comunidad una experiencia libre de acoso para todos, independientemente de la edad, tamaño corporal,
discapacidad, etnia, características sexuales, identidad y expresión de género,
nivel de experiencia, educación, estatus socioeconómico, nacionalidad, apariencia personal,
raza, religión o identidad y orientación sexual.
## Nuestros Estándares
Ejemplos de comportamientos que contribuyen a crear un entorno positivo incluyen:
- Uso de un lenguaje acogedor e inclusivo
- Respeto a diferentes puntos de vista y experiencias
- Aceptar de manera constructiva las críticas
- Centrarse en lo que es mejor para la comunidad
- Mostrar empatía hacia otros miembros de la comunidad
Ejemplos de comportamientos inaceptables por parte de los participantes incluyen:
- El uso de lenguaje o imágenes sexualizadas y la atención o avances sexuales no deseados
- Trollear, comentarios insultantes/despectivos y ataques personales o políticos
- Acoso público o privado
- Publicar información privada de otros, como una dirección física o electrónica,
sin permiso explícito
- Otras conductas que podrían considerarse inapropiadas en un entorno profesional
## Nuestras Responsabilidades
Los mantenedores del proyecto son responsables de aclarar los estándares de comportamiento aceptable
y se espera que tomen medidas correctivas apropiadas y justas en respuesta a cualquier
caso de comportamiento inaceptable.
Los mantenedores del proyecto tienen el derecho y la responsabilidad de eliminar, editar o rechazar
comentarios, commits, código, ediciones de wiki, issues y otras contribuciones que no estén alineadas con este Código de Conducta, o de prohibir temporal o permanentemente a cualquier contribuyente cuyo comportamiento sea inapropiado,
amenazante, ofensivo o dañino.
## Alcance
Este Código de Conducta se aplica tanto dentro de los espacios del proyecto como en espacios públicos
cuando una persona representa el proyecto o su comunidad. Ejemplos de
representación de un proyecto o comunidad incluyen el uso de una dirección de correo electrónico oficial del proyecto,
publicar en una cuenta oficial de redes sociales o actuar como un representante designado
en un evento en línea o fuera de línea. La representación de un proyecto puede
ser definida y clarificada más específicamente por los mantenedores del proyecto.
## Aplicación
Los casos de comportamiento abusivo, acosador o inaceptable de otra manera pueden
ser reportados contactando al equipo del proyecto en hi@cline.bot. Todas las quejas
serán revisadas e investigadas y resultarán en una respuesta que
se considere necesaria y apropiada a las circunstancias. El equipo del proyecto está
obligado a mantener la confidencialidad con respecto al informante de un incidente.
Más detalles sobre políticas específicas de aplicación pueden ser publicados por separado.
Los mantenedores del proyecto que no sigan o hagan cumplir el Código de Conducta de buena
fe pueden enfrentar repercusiones temporales o permanentes según lo determinen otros
miembros de la dirección del proyecto.
## Atribución
Este Código de Conducta está adaptado del [Contributor Covenant][homepage], versión 1.4,
disponible en https://www.contributor-covenant.org/version/1/4/code-of-conduct.html
[homepage]: https://www.contributor-covenant.org
Respuestas a preguntas frecuentes sobre este Código de Conducta se pueden encontrar en
https://www.contributor-covenant.org/faq

View file

@ -0,0 +1,82 @@
# Contribuir a Cline
Nos alegra que estés interesado en contribuir a Cline. Ya sea que corrijas un error, añadas una función o mejores nuestra documentación, ¡cada contribución hace que Cline sea más inteligente! Para mantener nuestra comunidad viva y acogedora, todos los miembros deben cumplir con nuestro [Código de Conducta](CODE_OF_CONDUCT.md).
## Informar de errores o problemas
¡Los informes de errores ayudan a mejorar Cline para todos! Antes de crear un nuevo problema, por favor revisa los [problemas existentes](https://github.com/cline/cline/issues) para evitar duplicados. Cuando estés listo para informar un error, dirígete a nuestra [página de Issues](https://github.com/cline/cline/issues/new/choose), donde encontrarás una plantilla que te ayudará a completar la información relevante.
<blockquote class='warning-note'>
🔐 <b>Importante:</b> Si descubres una vulnerabilidad de seguridad, utiliza la <a href="https://github.com/cline/cline/security/advisories/new">herramienta de seguridad de GitHub para informarla de manera privada</a>.
</blockquote>
## Decidir en qué trabajar
¿Buscas una buena primera contribución? Revisa los issues etiquetados con ["good first issue"](https://github.com/cline/cline/labels/good%20first%20issue) o ["help wanted"](https://github.com/cline/cline/labels/help%20wanted). ¡Estos están especialmente seleccionados para nuevos colaboradores y son áreas donde nos encantaría recibir ayuda!
También damos la bienvenida a contribuciones a nuestra [documentación](https://github.com/cline/cline/tree/main/docs). Ya sea corrigiendo errores tipográficos, mejorando guías existentes o creando nuevos contenidos educativos, queremos construir un repositorio de recursos gestionado por la comunidad que ayude a todos a sacar el máximo provecho de Cline. Puedes comenzar explorando `/docs` y buscando áreas que necesiten mejoras.
Si planeas trabajar en una función más grande, por favor crea primero una [solicitud de función](https://github.com/cline/cline/discussions/categories/feature-requests?discussions_q=is%3Aopen+category%3A%22Feature+Requests%22+sort%3Atop) para que podamos discutir si se alinea con la visión de Cline.
## Configurar el entorno de desarrollo
1. **Extensiones de VS Code**
- Al abrir el proyecto, VS Code te pedirá que instales las extensiones recomendadas
- Estas extensiones son necesarias para el desarrollo, por favor acepta todas las solicitudes de instalación
- Si rechazaste las solicitudes, puedes instalarlas manualmente en la sección de extensiones
2. **Desarrollo local**
- Ejecuta `npm run install:all` para instalar las dependencias
- Ejecuta `npm run test` para ejecutar las pruebas localmente
- Antes de enviar un PR, ejecuta `npm run format:fix` para formatear tu código
## Escribir y enviar código
Cualquiera puede contribuir código a Cline, pero te pedimos que sigas estas pautas para asegurar que tus contribuciones se integren sin problemas:
1. **Mantén los Pull Requests enfocados**
- Limita los PRs a una sola función o corrección de errores
- Divide los cambios más grandes en PRs más pequeños y coherentes
- Divide los cambios en commits lógicos que puedan ser revisados independientemente
2. **Calidad del código**
- Ejecuta `npm run lint` para verificar el estilo del código
- Ejecuta `npm run format` para formatear el código automáticamente
- Todos los PRs deben pasar las verificaciones de CI, que incluyen linting y formateo
- Corrige todas las advertencias o errores de ESLint antes de enviar
- Sigue las mejores prácticas para TypeScript y mantén la seguridad de tipos
3. **Pruebas**
- Añade pruebas para nuevas funciones
- Ejecuta `npm test` para asegurarte de que todas las pruebas pasen
- Actualiza las pruebas existentes si tus cambios las afectan
- Añade tanto pruebas unitarias como de integración donde sea apropiado
4. **Pautas de commits**
- Escribe mensajes de commit claros y descriptivos
- Usa el formato de commit convencional (por ejemplo, "feat:", "fix:", "docs:")
- Haz referencia a los issues relevantes en los commits con #número-del-issue
5. **Antes de enviar**
- Rebasea tu rama con el último Main
- Asegúrate de que tu rama se construya correctamente
- Verifica que todas las pruebas pasen
- Revisa tus cambios para eliminar cualquier código de depuración o registros de consola
6. **Descripción del Pull Request**
- Describe claramente lo que hacen tus cambios
- Añade pasos para probar los cambios
- Enumera cualquier cambio importante
- Añade capturas de pantalla para cambios en la interfaz de usuario
## Acuerdo de contribución
Al enviar un Pull Request, aceptas que tus contribuciones se licencien bajo la misma licencia que el proyecto ([Apache 2.0](LICENSE)).
Recuerda: Contribuir a Cline no solo significa escribir código, sino ser parte de una comunidad que está dando forma al futuro del desarrollo asistido por IA. ¡Hagamos algo grandioso juntos! 🚀

161
locales/es/README.md Normal file
View file

@ -0,0 +1,161 @@
# Cline #1 en OpenRouter
<p align="center">
<img src="https://media.githubusercontent.com/media/cline/cline/main/assets/docs/demo.gif" width="100%" />
</p>
<div align="center">
<table>
<tbody>
<td align="center">
<a href="https://marketplace.visualstudio.com/items?itemName=saoudrizwan.claude-dev" target="_blank"><strong>Descargar en VS Marketplace</strong></a>
</td>
<td align="center">
<a href="https://discord.gg/cline" target="_blank"><strong>Discord</strong></a>
</td>
<td align="center">
<a href="https://www.reddit.com/r/cline/" target="_blank"><strong>r/cline</strong></a>
</td>
<td align="center">
<a href="https://github.com/cline/cline/discussions/categories/feature-requests?discussions_q=is%3Aopen+category%3A%22Feature+Requests%22+sort%3Atop" target="_blank"><strong>Solicitudes de Funciones</strong></a>
</td>
<td align="center">
<a href="https://cline.bot/join-us" target="_blank"><strong>Estamos Contratando!</strong></a>
</td>
</tbody>
</table>
</div>
Conozca a Cline, un asistente de IA que puede usar su **CLI** y **E**ditor.
Gracias a las [habilidades de codificación agencial de Claude 3.5 Sonnet](https://www-cdn.anthropic.com/fed9cc193a14b84131812372d8d5857f8f304c52/Model_Card_Claude_3_Addendum.pdf), Cline puede abordar tareas complejas de desarrollo de software paso a paso. Con herramientas que le permiten crear y editar archivos, explorar grandes proyectos, usar el navegador y ejecutar comandos de terminal (con su aprobación), puede ayudarle de una manera que va más allá de la autocompletación de código o el soporte técnico. Cline incluso puede usar el Model Context Protocol (MCP) para crear nuevas herramientas y expandir sus propias capacidades. Mientras que los scripts de IA autónomos tradicionalmente se ejecutan en entornos aislados, esta extensión ofrece una GUI con un humano en el bucle para aprobar cada cambio de archivo y comando de terminal, proporcionando una forma segura y accesible de explorar el potencial de la IA agencial.
1. Ingrese su tarea y agregue imágenes para convertir maquetas en aplicaciones funcionales o solucionar errores con capturas de pantalla.
2. Cline comenzará analizando su estructura de archivos y ASTs de código fuente, realizando búsquedas Regex y leyendo archivos relevantes para orientarse en proyectos existentes. Al gestionar cuidadosamente la información agregada, Cline puede proporcionar asistencia valiosa incluso en proyectos grandes y complejos sin sobrecargar la ventana de contexto.
3. Una vez que Cline tenga la información necesaria, puede:
- Crear y editar archivos + monitorear errores de Linter/Compilador, para que pueda solucionar proactivamente problemas como importaciones faltantes y errores de sintaxis.
- Ejecutar comandos directamente en su terminal y monitorear su salida, para que pueda responder a problemas del servidor de desarrollo después de editar un archivo.
- Para tareas de desarrollo web, Cline puede iniciar el sitio web en un navegador sin cabeza, hacer clic, escribir, desplazarse y capturar capturas de pantalla + registros de consola, para que pueda solucionar errores de tiempo de ejecución y errores visuales.
4. Cuando una tarea esté completa, Cline le presentará el resultado con un comando de terminal como `open -a "Google Chrome" index.html`, que puede ejecutar con un clic en un botón.
> [!TIP]
> Use el atajo de teclado `CMD/CTRL + Shift + P` para abrir la paleta de comandos y escriba "Cline: Open In New Tab" para abrir la extensión como una pestaña en su editor. De esta manera, puede usar Cline junto a su explorador de archivos y ver más claramente cómo cambia su espacio de trabajo.
---
<img align="right" width="340" src="https://github.com/user-attachments/assets/3cf21e04-7ce9-4d22-a7b9-ba2c595e88a4">
### Use cualquier API y modelo
Cline admite proveedores de API como OpenRouter, Anthropic, OpenAI, Google Gemini, AWS Bedrock, Azure y GCP Vertex. También puede configurar cualquier API compatible con OpenAI o usar un modelo local a través de LM Studio/Ollama. Si usa OpenRouter, la extensión recupera su lista de modelos más reciente, para que pueda usar los modelos más nuevos tan pronto como estén disponibles.
La extensión también rastrea el uso total de tokens y costos de API para todo el ciclo de tareas y solicitudes individuales, para que esté informado sobre los gastos en cada paso.
<!-- Pixel transparente para crear un salto de línea después de la imagen flotante -->
<img width="2000" height="0" src="https://github.com/user-attachments/assets/ee14e6f7-20b8-4391-9091-8e8e25561929"><br>
<img align="left" width="370" src="https://github.com/user-attachments/assets/81be79a8-1fdb-4028-9129-5fe055e01e76">
### Ejecutar comandos en el terminal
Gracias a las nuevas [actualizaciones de integración de Shell en VSCode v1.93](https://code.visualstudio.com/updates/v1_93#_terminal-shell-integration-api), Cline puede ejecutar comandos directamente en su terminal y recibir la salida. Esto le permite realizar una variedad de tareas, desde la instalación de paquetes y la ejecución de scripts de compilación hasta la implementación de aplicaciones, la gestión de bases de datos y la ejecución de pruebas, adaptándose a su entorno de desarrollo y cadena de herramientas para hacer el trabajo correctamente.
Para procesos de larga duración como servidores de desarrollo, use el botón "Continuar mientras se ejecuta" para permitir que Cline continúe con la tarea mientras el comando se ejecuta en segundo plano. Mientras Cline trabaja, será notificado sobre nuevas salidas del terminal, para que pueda responder a problemas que puedan surgir, como errores de compilación al editar archivos.
<!-- Pixel transparente para crear un salto de línea después de la imagen flotante -->
<img width="2000" height="0" src="https://github.com/user-attachments/assets/ee14e6f7-20b8-4391-9091-8e8e25561929"><br>
<img align="right" width="400" src="https://github.com/user-attachments/assets/c5977833-d9b8-491e-90f9-05f9cd38c588">
### Crear y editar archivos
Cline puede crear y editar archivos directamente en su editor y presentarle una vista de diferencias de los cambios. Puede editar o deshacer los cambios de Cline directamente en el editor de vista de diferencias o proporcionar comentarios en el chat hasta que esté satisfecho con el resultado. Cline también monitorea errores de Linter/Compilador (importaciones faltantes, errores de sintaxis, etc.), para que pueda solucionar problemas que surjan en el camino.
Todos los cambios realizados por Cline se registran en la línea de tiempo de su archivo, proporcionando una forma sencilla de rastrear cambios y deshacerlos si es necesario.
<!-- Pixel transparente para crear un salto de línea después de la imagen flotante -->
<img width="2000" height="0" src="https://github.com/user-attachments/assets/ee14e6f7-20b8-4391-9091-8e8e25561929"><br>
<img align="left" width="370" src="https://github.com/user-attachments/assets/bc2e85ba-dfeb-4fe6-9942-7cfc4703cbe5">
### Usar el navegador
Con la nueva [habilidad de uso de computadora](https://www.anthropic.com/news/3-5-models-and-computer-use) de Claude 3.5 Sonnet, Cline puede iniciar un navegador, hacer clic en elementos, escribir texto y desplazarse, capturando capturas de pantalla y registros de consola. Esto permite la depuración interactiva, pruebas de extremo a extremo e incluso el uso general de la web. Esto le da la autonomía para solucionar errores visuales y problemas de tiempo de ejecución sin que tenga que copiar y pegar registros de errores.
Intente pedirle a Cline que "pruebe la aplicación" y observe cómo ejecuta un comando como `npm run dev`, inicia su servidor de desarrollo local en un navegador y realiza una serie de pruebas para confirmar que todo funciona. [Vea una demostración aquí.](https://x.com/sdrzn/status/1850880547825823989)
<!-- Pixel transparente para crear un salto de línea después de la imagen flotante -->
<img width="2000" height="0" src="https://github.com/user-attachments/assets/ee14e6f7-20b8-4391-9091-8e8e25561929"><br>
<img align="right" width="350" src="https://github.com/user-attachments/assets/ac0efa14-5c1f-4c26-a42d-9d7c56f5fadd">
### "agregar una herramienta que..."
Gracias al [Model Context Protocol](https://github.com/modelcontextprotocol), Cline puede expandir sus habilidades mediante herramientas personalizadas. Mientras que puede usar [servidores creados por la comunidad](https://github.com/modelcontextprotocol/servers), Cline puede en su lugar crear e instalar herramientas adaptadas a su flujo de trabajo específico. Simplemente pida a Cline que "agregue una herramienta" y él se encargará de todo, desde la creación de un nuevo servidor MCP hasta la instalación en la extensión. Estas herramientas personalizadas se convierten en parte del conjunto de herramientas de Cline y están listas para ser utilizadas en tareas futuras.
- "agregar una herramienta que recupere tickets de Jira": Recuperar ACs de tickets y poner a Cline a trabajar
- "agregar una herramienta que gestione AWS EC2s": Verificar métricas del servidor y escalar instancias hacia arriba o hacia abajo
- "agregar una herramienta que recupere los últimos incidentes de PagerDuty": Recuperar detalles y pedir a Cline que solucione errores
<!-- Pixel transparente para crear un salto de línea después de la imagen flotante -->
<img width="2000" height="0" src="https://github.com/user-attachments/assets/ee14e6f7-20b8-4391-9091-8e8e25561929"><br>
<img align="left" width="360" src="https://github.com/user-attachments/assets/7fdf41e6-281a-4b4b-ac19-020b838b6970">
### Agregar contexto
**`@url`:** Inserte una URL para que la extensión la recupere y convierta en Markdown, útil cuando desee proporcionar a Cline los documentos más recientes
**`@problems`:** Agregue errores y advertencias del espacio de trabajo (panel 'Problemas') que Cline debe solucionar
**`@file`:** Agregue el contenido de un archivo para que no tenga que desperdiciar solicitudes de API para aprobar la lectura del archivo (+ para buscar archivos)
**`@folder`:** Agregue los archivos de una carpeta a la vez para acelerar aún más su flujo de trabajo
<!-- Pixel transparente para crear un salto de línea después de la imagen flotante -->
<img width="2000" height="0" src="https://github.com/user-attachments/assets/ee14e6f7-20b8-4391-9091-8e8e25561929"><br>
<img align="right" width="350" src="https://github.com/user-attachments/assets/140c8606-d3bf-41b9-9a1f-4dbf0d4c90cb">
### Puntos de control: Comparar y Restaurar
Mientras Cline trabaja en una tarea, la extensión crea una instantánea de su espacio de trabajo en cada paso. Puede usar el botón 'Comparar' para ver una diferencia entre la instantánea y su espacio de trabajo actual, y el botón 'Restaurar' para volver a ese punto.
Por ejemplo, si está trabajando con un servidor web local, puede usar 'Restaurar solo espacio de trabajo' para probar rápidamente diferentes versiones de su aplicación, y luego 'Restaurar tarea y espacio de trabajo' cuando encuentre la versión desde la que desea continuar trabajando. Esto le permite explorar diferentes enfoques de manera segura sin perder progreso.
<!-- Pixel transparente para crear un salto de línea después de la imagen flotante -->
<img width="2000" height="0" src="https://github.com/user-attachments/assets/ee14e6f7-20b8-4391-9091-8e8e25561929"><br>
## Contribuir
Para contribuir al proyecto, comience con nuestra [guía de contribución](CONTRIBUTING.md) para aprender los conceptos básicos. También puede unirse a nuestro [Discord](https://discord.gg/cline) para chatear con otros colaboradores en el canal `#contributors`. Si está buscando un trabajo a tiempo completo, consulte nuestras vacantes en nuestra [página de carreras](https://cline.bot/join-us).
<details>
<summary>Instrucciones de desarrollo local</summary>
1. Clone el repositorio _(Requiere [git-lfs](https://git-lfs.com/))_:
```bash
git clone https://github.com/cline/cline.git
```
2. Abra el proyecto en VSCode:
```bash
code cline
```
3. Instale las dependencias necesarias para la extensión y la GUI de Webview:
```bash
npm run install:all
```
4. Inicie presionando `F5` (o `Run`->`Start Debugging`) para abrir una nueva ventana de VSCode con la extensión cargada. (Es posible que deba instalar la [extensión de emparejadores de problemas de esbuild](https://marketplace.visualstudio.com/items?itemName=connor4312.esbuild-problem-matchers) si encuentra problemas al compilar el proyecto.)
</details>
## Licencia
[Apache 2.0 © 2024 Cline Bot Inc.](./LICENSE)

View file

@ -0,0 +1,47 @@
# コントリビューター規約行動規範
## 我々の誓い
オープンで歓迎される環境を育むために、我々はコントリビューターおよびメンテナーとして、年齢、体型、障害、民族、性の特徴、性別のアイデンティティおよび表現、経験のレベル、教育、社会経済的地位、国籍、個人の外見、人種、宗教、または性的アイデンティティおよび指向に関係なく、プロジェクトおよびコミュニティへの参加がハラスメントのない体験となるよう誓います。
## 我々の基準
ポジティブな環境を作り出す行動の例としては、以下のものがあります:
- 歓迎的で包括的な言葉を使うこと
- 異なる視点や経験を尊重すること
- 建設的な批判を優雅に受け入れること
- コミュニティのために最善を尽くすことに集中すること
- 他のコミュニティメンバーに対して共感を示すこと
参加者による許容できない行動の例としては、以下のものがあります:
- 性的な言葉や画像の使用、望まれない性的関心やアプローチ
- 荒らし、侮辱的/軽蔑的なコメント、個人的または政治的な攻撃
- 公的または私的なハラスメント
- 明示的な許可なしに他人の個人情報(物理的または電子的な住所など)を公開すること
- プロフェッショナルな環境で不適切と合理的に見なされるその他の行動
## 我々の責任
プロジェクトのメンテナーは、許容される行動の基準を明確にする責任があり、不適切な行動の事例に対して適切かつ公平な是正措置を講じることが期待されています。
プロジェクトのメンテナーは、この行動規範に沿わないコメント、コミット、コード、ウィキの編集、問題、およびその他の貢献を削除、編集、または拒否する権利と責任を持ち、また、不適切、脅迫的、攻撃的、または有害と見なされるその他の行動を行ったコントリビューターを一時的または永久に禁止する権利と責任を持ちます。
## 範囲
この行動規範は、プロジェクトスペース内およびプロジェクトやコミュニティを代表する個人が公の場で行動する場合に適用されます。プロジェクトやコミュニティを代表する例としては、公式のプロジェクトメールアドレスを使用すること、公式のソーシャルメディアアカウントを通じて投稿すること、またはオンラインまたはオフラインのイベントで任命された代表として行動することが含まれます。プロジェクトの代表としての行動は、プロジェクトのメンテナーによってさらに定義および明確化される場合があります。
## 執行
虐待的、嫌がらせ、またはその他の許容できない行動の事例は、プロジェクトチームに hi@cline.bot まで報告することができます。すべての苦情はレビューおよび調査され、状況に応じて必要かつ適切な対応が行われます。プロジェクトチームは、事件の報告者に関する機密性を保持する義務があります。具体的な執行ポリシーの詳細は別途掲載される場合があります。
行動規範を誠実に遵守または執行しないプロジェクトのメンテナーは、プロジェクトのリーダーシップの他のメンバーによって一時的または永久的な影響を受ける可能性があります。
## 帰属
この行動規範は、[Contributor Covenant][homepage] バージョン 1.4 から適応されており、https://www.contributor-covenant.org/version/1/4/code-of-conduct.html で入手できます。
[homepage]: https://www.contributor-covenant.org
この行動規範に関する一般的な質問への回答については、https://www.contributor-covenant.org/faq を参照してください。

View file

@ -0,0 +1,82 @@
# Clineへの貢献
Clineへの貢献に興味をお持ちいただきありがとうございます。
## バグや問題の報告
バグ報告は、Clineを皆さんにとってより良いものにするために役立ちます新しい問題を作成する前に、重複を避けるために[既存の問題を検索](https://github.com/cline/cline/issues)してください。バグを報告する準備ができたら、[問題ページ](https://github.com/cline/cline/issues/new/choose)に移動し、関連情報を記入するためのテンプレートをご利用ください。
<blockquote class='warning-note'>
🔐 <b>重要:</b> セキュリティ脆弱性を発見した場合は、<a href="https://github.com/cline/cline/security/advisories/new">Githubセキュリティツールを使用して非公開で報告</a>してください。
</blockquote>
## 作業内容の決定
最初の貢献をお探しですか?["good first issue"](https://github.com/cline/cline/labels/good%20first%20issue)や["help wanted"](https://github.com/cline/cline/labels/help%20wanted)のラベルが付いた問題をチェックしてください。これらは新しい貢献者向けに特に選ばれたもので、私たちが助けを求めている分野です!
また、[ドキュメント](https://github.com/cline/cline/tree/main/docs)への貢献も歓迎します!誤字の修正、既存のガイドの改善、新しい教育コンテンツの作成など、コミュニティ主導のリソースリポジトリを構築するために皆さんの力をお借りしたいと考えています。`/docs`に飛び込んで、改善が必要な箇所を探してみてください。
大きな機能に取り組む予定がある場合は、まず[機能リクエスト](https://github.com/cline/cline/discussions/categories/feature-requests?discussions_q=is%3Aopen+category%3A%22Feature+Requests%22+sort%3Atop)を作成し、それがClineのビジョンに合致するかどうかを議論しましょう。
## 開発環境のセットアップ
1. **VS Code拡張機能**
- プロジェクトを開くと、VS Codeは推奨される拡張機能のインストールを促します
- これらの拡張機能は開発に必要です - すべてのインストールプロンプトを受け入れてください
- プロンプトを閉じた場合は、拡張機能パネルから手動でインストールできます
2. **ローカル開発**
- `npm run install:all`を実行して依存関係をインストールします
- `npm run test`を実行してローカルでテストを実行します
- PRを提出する前に、`npm run format:fix`を実行してコードをフォーマットします
## コードの作成と提出
誰でもClineにコードを貢献できますが、貢献がスムーズに統合されるように以下のガイドラインに従ってください
1. **プルリクエストを集中させる**
- PRは単一の機能またはバグ修正に限定してください
- 大きな変更は小さな関連PRに分割してください
- 論理的なコミットに分けて、独立してレビューできるようにしてください
2. **コード品質**
- `npm run lint`を実行してコードスタイルをチェックします
- `npm run format`を実行してコードを自動的にフォーマットします
- すべてのPRは、リンティングとフォーマットを含むCIチェックに合格する必要があります
- 提出前にESLintの警告やエラーをすべて解決してください
- TypeScriptのベストプラクティスに従い、型の安全性を維持してください
3. **テスト**
- 新しい機能にはテストを追加してください
- `npm test`を実行してすべてのテストが合格することを確認してください
- 変更が既存のテストに影響を与える場合は、それらを更新してください
- 適切な場合には、ユニットテストと統合テストの両方を含めてください
4. **コミットガイドライン**
- 明確で説明的なコミットメッセージを書いてください
- 従来のコミット形式(例:"feat:", "fix:", "docs:")を使用してください
- コミットで関連する問題を#issue-numberを使用して参照してください
5. **提出前に**
- 最新のmainにブランチをリベースしてください
- ブランチが正常にビルドされることを確認してください
- すべてのテストが合格していることを再確認してください
- デバッグコードやコンソールログがないか変更を確認してください
6. **プルリクエストの説明**
- 変更内容を明確に説明してください
- 変更をテストする手順を含めてください
- 破壊的な変更がある場合はリストしてください
- UIの変更にはスクリーンショットを追加してください
## 貢献契約
プルリクエストを提出することで、あなたの貢献がプロジェクトと同じライセンス([Apache 2.0](LICENSE))の下でライセンスされることに同意したことになります。
覚えておいてくださいClineへの貢献はコードを書くことだけではなく、AI支援開発の未来を形作るコミュニティの一員になることです。一緒に素晴らしいものを作りましょう🚀

161
locales/ja/README.md Normal file
View file

@ -0,0 +1,161 @@
# Cline OpenRouterでのナンバーワン
<p align="center">
<img src="https://media.githubusercontent.com/media/cline/cline/main/assets/docs/demo.gif" width="100%" />
</p>
<div align="center">
<table>
<tbody>
<td align="center">
<a href="https://marketplace.visualstudio.com/items?itemName=saoudrizwan.claude-dev" target="_blank"><strong>VS Marketplaceでダウンロード</strong></a>
</td>
<td align="center">
<a href="https://discord.gg/cline" target="_blank"><strong>Discord</strong></a>
</td>
<td align="center">
<a href="https://www.reddit.com/r/cline/" target="_blank"><strong>r/cline</strong></a>
</td>
<td align="center">
<a href="https://github.com/cline/cline/discussions/categories/feature-requests?discussions_q=is%3Aopen+category%3A%22Feature+Requests%22+sort%3Atop" target="_blank"><strong>機能リクエスト</strong></a>
</td>
<td align="center">
<a href="https://cline.bot/join-us" target="_blank"><strong>採用情報</strong></a>
</td>
</tbody>
</table>
</div>
Clineは、**CLI**と**エディター**を使用できるAIアシスタントです。
[Claude 3.5 Sonnetのエージェント的コーディング機能](https://www-cdn.anthropic.com/fed9cc193a14b84131812372d8d5857f8f304c52/Model_Card_Claude_3_Addendum.pdf)のおかげで、Clineは複雑なソフトウェア開発タスクをステップバイステップで処理できます。ファイルの作成と編集、大規模プロジェクトの探索、ブラウザの使用、ターミナルコマンドの実行許可後などのツールを使用して、コード補完や技術サポートを超えた支援を提供します。Clineは、Model Context Protocol (MCP)を使用して新しいツールを作成し、自身の機能を拡張することもできます。自律的なAIスクリプトは通常サンドボックス環境で実行されますが、この拡張機能はファイル変更やターミナルコマンドを承認するための人間インターフェースを提供し、エージェント的AIの可能性を安全かつアクセスしやすい方法で探求できます。
1. タスクを入力し、モックアップを機能するアプリに変換したり、スクリーンショットでバグを修正したりします。
2. Clineは、ファイル構造とソースコードASTの分析、正規表現検索の実行、関連ファイルの読み取りから始め、既存プロジェクトに精通します。コンテキストに追加される情報を慎重に管理することで、大規模で複雑なプロジェクトでもコンテキストウィンドウを圧倒することなく貴重な支援を提供できます。
3. Clineが必要な情報を取得すると、次のことができます
- ファイルの作成と編集 + リンター/コンパイラーエラーの監視を行い、欠落したインポートや構文エラーなどの問題を自動的に修正します。
- ターミナルでコマンドを直接実行し、作業中に出力を監視します。これにより、ファイル編集後の開発サーバーの問題に対応できます。
- ウェブ開発タスクでは、ヘッドレスブラウザでサイトを起動し、クリック、入力、スクロール、スクリーンショットとコンソールログのキャプチャを行い、ランタイムエラーや視覚的なバグを修正します。
4. タスクが完了すると、Clineは`open -a "Google Chrome" index.html`のようなターミナルコマンドを提示し、ボタンをクリックして実行できます。
> [!TIP]
> `CMD/CTRL + Shift + P`ショートカットを使用してコマンドパレットを開き、「Cline: Open In New Tab」と入力して、エディターのタブとして拡張機能を開きます。これにより、ファイルエクスプローラーと並行してClineを使用し、ワークスペースの変更をより明確に確認できます。
---
<img align="right" width="340" src="https://github.com/user-attachments/assets/3cf21e04-7ce9-4d22-a7b9-ba2c595e88a4">
### どのAPIやモデルでも使用可能
Clineは、OpenRouter、Anthropic、OpenAI、Google Gemini、AWS Bedrock、Azure、GCP VertexなどのAPIプロバイダーをサポートしています。また、OpenAI互換のAPIを設定したり、LM Studio/Ollamaを通じてローカルモデルを使用することもできます。OpenRouterを使用している場合、拡張機能は最新のモデルリストを取得し、最新のモデルをすぐに使用できるようにします。
拡張機能は、タスクループ全体と個々のリクエストのトークン総数とAPI使用コストを追跡し、各ステップで支出を把握できます。
<!-- 透明なピクセルで浮動画像の後に改行を作成 -->
<img width="2000" height="0" src="https://github.com/user-attachments/assets/ee14e6f7-20b8-4391-9091-8e8e25561929"><br>
<img align="left" width="370" src="https://github.com/user-attachments/assets/81be79a8-1fdb-4028-9129-5fe055e01e76">
### ターミナルでコマンドを実行
VSCode v1.93の新しい[シェル統合アップデート](https://code.visualstudio.com/updates/v1_93#_terminal-shell-integration-api)のおかげで、Clineはターミナルでコマンドを直接実行し、出力を受け取ることができます。これにより、パッケージのインストールやビルドスクリプトの実行からアプリケーションのデプロイ、データベースの管理、テストの実行まで、幅広いタスクを実行できます。Clineは、開発環境とツールチェーンに適応して、タスクを正確に実行します。
開発サーバーのような長時間実行されるプロセスの場合、「実行中に続行」ボタンを使用して、コマンドがバックグラウンドで実行されている間にClineがタスクを続行できるようにします。Clineが作業を進める中で、新しいターミナル出力が通知され、ファイル編集時のコンパイルエラーなどの問題に対応できます。
<!-- 透明なピクセルで浮動画像の後に改行を作成 -->
<img width="2000" height="0" src="https://github.com/user-attachments/assets/ee14e6f7-20b8-4391-9091-8e8e25561929"><br>
<img align="right" width="400" src="https://github.com/user-attachments/assets/c5977833-d9b8-491e-90f9-05f9cd38c588">
### ファイルの作成と編集
Clineはエディター内でファイルを作成および編集し、変更の差分ビューを提示します。差分ビューエディターでClineの変更を直接編集または元に戻すことができ、チャットでフィードバックを提供して満足するまで調整できます。Clineはリンター/コンパイラーエラー(欠落したインポート、構文エラーなど)も監視し、発生した問題を自動的に修正します。
Clineによるすべての変更はファイルのタイムラインに記録され、必要に応じて変更を追跡および元に戻す簡単な方法を提供します。
<!-- 透明なピクセルで浮動画像の後に改行を作成 -->
<img width="2000" height="0" src="https://github.com/user-attachments/assets/ee14e6f7-20b8-4391-9091-8e8e25561929"><br>
<img align="left" width="370" src="https://github.com/user-attachments/assets/bc2e85ba-dfeb-4fe6-9942-7cfc4703cbe5">
### ブラウザの使用
Claude 3.5 Sonnetの新しい[コンピュータ使用](https://www.anthropic.com/news/3-5-models-and-computer-use)機能により、Clineはブラウザを起動し、要素をクリック、テキストを入力、スクロールし、各ステップでスクリーンショットとコンソールログをキャプチャできます。これにより、インタラクティブなデバッグ、エンドツーエンドテスト、さらには一般的なウェブ使用が可能になります。これにより、エラーログを手動でコピーペーストすることなく、視覚的なバグやランタイムの問題を自律的に修正できます。
Clineに「アプリをテストして」と頼んでみてください。彼は`npm run dev`のようなコマンドを実行し、ローカルで実行中の開発サーバーをブラウザで起動し、一連のテストを実行してすべてが正常に動作することを確認します。[デモはこちら。](https://x.com/sdrzn/status/1850880547825823989)
<!-- 透明なピクセルで浮動画像の後に改行を作成 -->
<img width="2000" height="0" src="https://github.com/user-attachments/assets/ee14e6f7-20b8-4391-9091-8e8e25561929"><br>
<img align="right" width="350" src="https://github.com/user-attachments/assets/ac0efa14-5c1f-4c26-a42d-9d7c56f5fadd">
### 「ツールを追加して...」
[Model Context Protocol](https://github.com/modelcontextprotocol)のおかげで、Clineはカスタムツールを通じて機能を拡張できます。[コミュニティ製サーバー](https://github.com/modelcontextprotocol/servers)を使用することもできますが、Clineは代わりに特定のワークフローに合わせたツールを作成してインストールできます。「ツールを追加して」と頼むだけで、Clineは新しいMCPサーバーの作成から拡張機能へのインストールまでをすべて処理します。これらのカスタムツールはClineのツールキットの一部となり、将来のタスクで使用できるようになります。
- 「Jiraチケットを取得するツールを追加して」チケットACを取得し、Clineに作業を依頼
- 「AWS EC2を管理するツールを追加して」サーバーメトリクスを確認し、インスタンスをスケールアップまたはダウン
- 「最新のPagerDutyインシデントを取得するツールを追加して」詳細を取得し、Clineにバグ修正を依頼
<!-- 透明なピクセルで浮動画像の後に改行を作成 -->
<img width="2000" height="0" src="https://github.com/user-attachments/assets/ee14e6f7-20b8-4391-9091-8e8e25561929"><br>
<img align="left" width="360" src="https://github.com/user-attachments/assets/7fdf41e6-281a-4b4b-ac19-020b838b6970">
### コンテキストを追加
**`@url`** 最新のドキュメントをClineに提供したい場合に、URLを貼り付けて拡張機能が取得し、Markdownに変換します。
**`@problems`** Clineが修正するためのワークスペースエラーと警告「問題」パネルを追加します。
**`@file`** ファイルの内容を追加し、読み取りファイルを承認するAPIリクエストを節約します+ファイルを検索して入力)。
**`@folder`** フォルダーのファイルを一度に追加して、ワークフローをさらにスピードアップします。
<!-- 透明なピクセルで浮動画像の後に改行を作成 -->
<img width="2000" height="0" src="https://github.com/user-attachments/assets/ee14e6f7-20b8-4391-9091-8e8e25561929"><br>
<img align="right" width="350" src="https://github.com/user-attachments/assets/140c8606-d3bf-41b9-9a1f-4dbf0d4c90cb">
### チェックポイント:比較と復元
Clineがタスクを進める中で、拡張機能は各ステップでワークスペースのスナップショットを撮ります。「比較」ボタンを使用してスナップショットと現在のワークスペースの差分を確認し、「復元」ボタンを使用してそのポイントにロールバックできます。
たとえば、ローカルウェブサーバーで作業している場合、「ワークスペースのみを復元」を使用して異なるバージョンのアプリを迅速にテストし、「タスクとワークスペースを復元」を使用して続行したいバージョンを見つけたときに使用します。これにより、進行状況を失うことなく異なるアプローチを安全に探求できます。
<!-- 透明なピクセルで浮動画像の後に改行を作成 -->
<img width="2000" height="0" src="https://github.com/user-attachments/assets/ee14e6f7-20b8-4391-9091-8e8e25561929"><br>
## 貢献
プロジェクトに貢献するには、[貢献ガイド](CONTRIBUTING.md)から基本を学び始めてください。また、[Discord](https://discord.gg/cline)に参加して、`#contributors`チャンネルで他の貢献者とチャットすることもできます。フルタイムの仕事を探している場合は、[採用ページ](https://cline.bot/join-us)でオープンポジションを確認してください。
<details>
<summary>ローカル開発の手順</summary>
1. リポジトリをクローンします _(Requires [git-lfs](https://git-lfs.com/))_
```bash
git clone https://github.com/cline/cline.git
```
2. プロジェクトをVSCodeで開きます
```bash
code cline
```
3. 拡張機能とwebview-guiの必要な依存関係をインストールします
```bash
npm run install:all
```
4. `F5`を押して(または`Run`->`Start Debugging`、拡張機能が読み込まれた新しいVSCodeウィンドウを開きます。プロジェクトのビルドに問題がある場合は、[esbuild problem matchers extension](https://marketplace.visualstudio.com/items?itemName=connor4312.esbuild-problem-matchers)をインストールする必要があるかもしれません。)
</details>
## ライセンス
[Apache 2.0 © 2024 Cline Bot Inc.](./LICENSE)

View file

@ -0,0 +1,47 @@
# 贡献者公约行为准则
## 我们的承诺
为了营造一个开放和欢迎的环境,我们作为贡献者和维护者承诺让我们的项目和社区的参与体验对每个人都无骚扰,无论年龄、体型、残疾、种族、性别特征、性别认同和表达、经验水平、教育程度、社会经济地位、国籍、个人外貌、种族、宗教或性取向。
## 我们的标准
有助于创造积极环境的行为示例包括:
- 使用欢迎和包容的语言
- 尊重不同的观点和经验
- 优雅地接受建设性的批评
- 专注于对社区最有利的事情
- 对其他社区成员表现出同理心
参与者不可接受的行为示例包括:
- 使用性化语言或图像以及不受欢迎的性关注或挑逗
- 故意挑衅、侮辱/贬低性评论和个人或政治攻击
- 公开或私下骚扰
- 未经明确许可发布他人的私人信息,如物理或电子地址
- 其他在专业环境中合理认为不适当的行为
## 我们的责任
项目维护者有责任澄清可接受行为的标准,并期望对任何不可接受行为采取适当和公平的纠正措施。
项目维护者有权利和责任删除、编辑或拒绝与本行为准则不一致的评论、提交、代码、维基编辑、问题和其他贡献,或暂时或永久禁止任何贡献者进行他们认为不适当、威胁、冒犯或有害的其他行为。
## 适用范围
本行为准则适用于项目空间内和公共空间中代表项目或其社区的个人。代表项目或社区的示例包括使用官方项目电子邮件地址,通过官方社交媒体账户发布,或在在线或离线活动中作为指定代表。项目的代表性可能由项目维护者进一步定义和澄清。
## 执行
滥用、骚扰或其他不可接受行为的实例可以通过联系项目团队 hi@cline.bot 报告。所有投诉将被审查和调查,并将导致根据情况认为必要和适当的回应。项目团队有义务对事件报告者保密。具体执行政策的详细信息可能会单独发布。
未能善意遵守或执行行为准则的项目维护者可能会面临由项目领导的其他成员决定的临时或永久后果。
## 归属
本行为准则改编自 [贡献者公约][主页],版本 1.4,可在 https://www.contributor-covenant.org/version/1/4/code-of-conduct.html 获取。
[主页]: https://www.contributor-covenant.org
有关此行为准则的常见问题的答案,请参见 https://www.contributor-covenant.org/faq

View file

@ -0,0 +1,82 @@
# 贡献到 Cline
我们很高兴您有兴趣为 Cline 做出贡献。无论您是修复错误、添加功能还是改进我们的文档,每一份贡献都让 Cline 更加智能!为了保持我们的社区充满活力和欢迎,所有成员必须遵守我们的[行为准则](CODE_OF_CONDUCT.md)。
## 报告错误或问题
错误报告有助于让 Cline 对每个人都更好!在创建新问题之前,请先[搜索现有问题](https://github.com/cline/cline/issues)以避免重复。当您准备好报告错误时,请前往我们的[问题页面](https://github.com/cline/cline/issues/new/choose),在那里您会找到一个模板来帮助您填写相关信息。
<blockquote class='warning-note'>
🔐 <b>重要:</b>如果您发现安全漏洞,请使用<a href="https://github.com/cline/cline/security/advisories/new">Github 安全工具私下报告</a>
</blockquote>
## 决定要做什么
寻找一个好的首次贡献?查看标记为["good first issue"](https://github.com/cline/cline/labels/good%20first%20issue)或["help wanted"](https://github.com/cline/cline/labels/help%20wanted)的问题。这些是专门为新贡献者策划的领域,我们非常欢迎您的帮助!
我们也欢迎对我们的[文档](https://github.com/cline/cline/tree/main/docs)做出贡献!无论是修正错别字、改进现有指南,还是创建新的教育内容 - 我们希望建立一个社区驱动的资源库,帮助每个人充分利用 Cline。您可以从深入研究 `/docs` 并寻找需要改进的地方开始。
如果您计划开发一个更大的功能,请先创建一个[功能请求](https://github.com/cline/cline/discussions/categories/feature-requests?discussions_q=is%3Aopen+category%3A%22Feature+Requests%22+sort%3Atop),以便我们讨论它是否符合 Cline 的愿景。
## 开发设置
1. **VS Code 扩展**
- 打开项目时VS Code 会提示您安装推荐的扩展
- 这些扩展是开发所必需的 - 请接受所有安装提示
- 如果您忽略了提示,可以从扩展面板手动安装它们
2. **本地开发**
- 运行 `npm run install:all` 安装依赖项
- 运行 `npm run test` 本地运行测试
- 提交 PR 之前,运行 `npm run format:fix` 格式化您的代码
## 编写和提交代码
任何人都可以为 Cline 贡献代码,但我们要求您遵循以下指南,以确保您的贡献能够顺利集成:
1. **保持 Pull Request 集中**
- 将 PR 限制为单个功能或错误修复
- 将较大的更改拆分为较小的相关 PR
- 将更改分为逻辑提交,以便独立审查
2. **代码质量**
- 运行 `npm run lint` 检查代码风格
- 运行 `npm run format` 自动格式化代码
- 所有 PR 必须通过 CI 检查,包括 lint 和格式化
- 提交前解决所有 ESLint 警告或错误
- 遵循 TypeScript 最佳实践并保持类型安全
3. **测试**
- 为新功能添加测试
- 运行 `npm test` 确保所有测试通过
- 如果您的更改影响现有测试,请更新它们
- 在适当的情况下包括单元测试和集成测试
4. **提交指南**
- 编写清晰、描述性的提交消息
- 使用常规提交格式例如“feat:”“fix:”“docs:”)
- 在提交中引用相关问题,使用 #issue-number
5. **提交前**
- 将您的分支重新基于最新的 main
- 确保您的分支成功构建
- 仔细检查所有测试是否通过
- 检查您的更改是否有任何调试代码或控制台日志
6. **Pull Request 描述**
- 清楚描述您的更改内容
- 包括测试更改的步骤
- 列出任何重大更改
- 对于 UI 更改,添加截图
## 贡献协议
通过提交 pull request您同意您的贡献将根据与项目相同的许可证[Apache 2.0](LICENSE))进行许可。
记住:为 Cline 做贡献不仅仅是编写代码 - 这是成为一个社区的一部分,共同塑造 AI 辅助开发的未来。让我们一起构建一些令人惊叹的东西!🚀

162
locales/zh-cn/README.md Normal file
View file

@ -0,0 +1,162 @@
# Cline OpenRouter 排名第一
<p align="center">
<img src="https://media.githubusercontent.com/media/cline/cline/main/assets/docs/demo.gif" width="100%" />
</p>
<div align="center">
<table>
<tbody>
<td align="center">
<a href="https://marketplace.visualstudio.com/items?itemName=saoudrizwan.claude-dev" target="_blank"><strong>在 VS Marketplace 下载</strong></a>
</td>
<td align="center">
<a href="https://discord.gg/cline" target="_blank"><strong>Discord</strong></a>
</td>
<td align="center">
<a href="https://www.reddit.com/r/cline/" target="_blank"><strong>r/cline</strong></a>
</td>
<td align="center">
<a href="https://github.com/cline/cline/discussions/categories/feature-requests?discussions_q=is%3Aopen+category%3A%22Feature+Requests%22+sort%3Atop" target="_blank"><strong>功能请求</strong></a>
</td>
<td align="center">
<a href="https://cline.bot/join-us" target="_blank"><strong>我们正在招聘!</strong></a>
</td>
</tbody>
</table>
</div>
认识 Cline一个可以使用你的 **CLI****编辑器** 的 AI 助手。
感谢 [Claude 3.5 Sonnet 的代理编码能力](https://www-cdn.anthropic.com/fed9cc193a14b84131812372d8d5857f8f304c52/Model_Card_Claude_3_Addendum.pdf)Cline 可以一步步处理复杂的软件开发任务。通过允许他创建和编辑文件、探索大型项目、使用浏览器和执行终端命令在你授予权限后他可以提供超越代码完成或技术支持的帮助。Cline 甚至可以使用 Model Context Protocol (MCP) 创建新工具并扩展自己的能力。虽然自主 AI 脚本传统上在沙盒环境中运行,但此扩展提供了一个人机交互的 GUI 来批准每个文件更改和终端命令,提供了一种安全且可访问的方式来探索代理 AI 的潜力。
1. 输入你的任务并添加图像,将模型转换为功能应用程序或通过截图修复错误。
2. Cline 首先分析你的文件结构和源代码 AST运行正则表达式搜索并阅读相关文件以了解现有项目。通过仔细管理添加到上下文中的信息Cline 即使在大型复杂项目中也能提供有价值的帮助,而不会使上下文窗口过载。
3. 一旦 Cline 获得所需信息,他可以:
- 创建和编辑文件 + 监控 linter/编译器错误,从而主动修复诸如缺少导入和语法错误等问题。
- 直接在你的终端中执行命令并监控其输出,从而在编辑文件后对开发服务器问题做出反应。
- 对于 Web 开发任务Cline 可以在无头浏览器中启动网站,点击、输入、滚动并捕获截图和控制台日志,从而修复运行时错误和视觉错误。
4. 当任务完成时Cline 将通过终端命令如 `open -a "Google Chrome" index.html` 向你展示结果,你可以通过点击按钮运行该命令。
> [!提示]
> 使用 `CMD/CTRL + Shift + P` 快捷键打开命令面板并输入 "Cline: Open In New Tab" 将扩展作为标签在编辑器中打开。这让你可以与文件资源管理器并排使用 Cline更清楚地看到他如何改变你的工作空间。
---
<img align="right" width="340" src="https://github.com/user-attachments/assets/3cf21e04-7ce9-4d22-a7b9-ba2c595e88a4">
### 使用任何 API 和模型
Cline 支持 OpenRouter、Anthropic、OpenAI、Google Gemini、AWS Bedrock、Azure 和 GCP Vertex 等 API 提供商。你还可以配置任何兼容 OpenAI 的 API或通过 LM Studio/Ollama 使用本地模型。如果你使用 OpenRouter扩展会获取他们的最新模型列表让你在新模型可用时立即使用。
扩展还会跟踪整个任务循环和单个请求的总令牌和 API 使用成本,让你在每一步都了解支出情况。
<!-- 透明像素以在浮动图像后创建换行 -->
<img width="2000" height="0" src="https://github.com/user-attachments/assets/ee14e6f7-20b8-4391-9091-8e8e25561929"><br>
<img align="left" width="370" src="https://github.com/user-attachments/assets/81be79a8-1fdb-4028-9129-5fe055e01e76">
### 在终端中运行命令
感谢 VSCode v1.93 中的新 [终端 shell 集成更新](https://code.visualstudio.com/updates/v1_93#_terminal-shell-integration-api)Cline 可以直接在你的终端中执行命令并接收输出。这使他能够执行广泛的任务,从安装包和运行构建脚本到部署应用程序、管理数据库和执行测试,同时适应你的开发环境和工具链以正确完成工作。
对于长时间运行的进程如开发服务器,使用“在运行时继续”按钮让 Cline 在命令后台运行时继续任务。当 Cline 工作时,他会在过程中收到任何新的终端输出通知,让他对可能出现的问题做出反应,例如编辑文件时的编译时错误。
<!-- 透明像素以在浮动图像后创建换行 -->
<img width="2000" height="0" src="https://github.com/user-attachments/assets/ee14e6f7-20b8-4391-9091-8e8e25561929"><br>
<img align="right" width="400" src="https://github.com/user-attachments/assets/c5977833-d9b8-491e-90f9-05f9cd38c588">
### 创建和编辑文件
Cline 可以直接在你的编辑器中创建和编辑文件,向你展示更改的差异视图。你可以直接在差异视图编辑器中编辑或恢复 Cline 的更改或在聊天中提供反馈直到你对结果满意。Cline 还会监控 linter/编译器错误(缺少导入、语法错误等),以便他在过程中自行修复出现的问题。
Cline 所做的所有更改都会记录在你的文件时间轴中,提供了一种简单的方法来跟踪和恢复修改(如果需要)。
<!-- 透明像素以在浮动图像后创建换行 -->
<img width="2000" height="0" src="https://github.com/user-attachments/assets/ee14e6f7-20b8-4391-9091-8e8e25561929"><br>
<img align="left" width="370" src="https://github.com/user-attachments/assets/bc2e85ba-dfeb-4fe6-9942-7cfc4703cbe5">
### 使用浏览器
借助 Claude 3.5 Sonnet 的新 [计算机使用](https://www.anthropic.com/news/3-5-models-and-computer-use) 功能Cline 可以启动浏览器,点击元素,输入文本和滚动,在每一步捕获截图和控制台日志。这允许进行交互式调试、端到端测试,甚至是一般的网页使用!这使他能够自主修复视觉错误和运行时问题,而无需你亲自操作和复制粘贴错误日志。
试试让 Cline “测试应用程序”,看看他如何运行 `npm run dev` 命令,在浏览器中启动你本地运行的开发服务器,并执行一系列测试以确认一切正常。[在这里查看演示。](https://x.com/sdrzn/status/1850880547825823989)
<!-- 透明像素以在浮动图像后创建换行 -->
<img width="2000" height="0" src="https://github.com/user-attachments/assets/ee14e6f7-20b8-4391-9091-8e8e25561929"><br>
<img align="right" width="350" src="https://github.com/user-attachments/assets/ac0efa14-5c1f-4c26-a42d-9d7c56f5fadd">
### “添加一个工具……”
感谢 [Model Context Protocol](https://github.com/modelcontextprotocol)Cline 可以通过自定义工具扩展他的能力。虽然你可以使用 [社区制作的服务器](https://github.com/modelcontextprotocol/servers),但 Cline 可以创建和安装适合你特定工作流程的工具。只需让 Cline “添加一个工具”,他将处理所有事情,从创建新的 MCP 服务器到将其安装到扩展中。这些自定义工具将成为 Cline 工具包的一部分,准备在未来的任务中使用。
- “添加一个获取 Jira 工单的工具”:检索工单 AC 并让 Cline 开始工作
- “添加一个管理 AWS EC2 的工具”:检查服务器指标并上下扩展实例
- “添加一个获取最新 PagerDuty 事件的工具”:获取详细信息并让 Cline 修复错误
<!-- 透明像素以在浮动图像后创建换行 -->
<img width="2000" height="0" src="https://github.com/user-attachments/assets/ee14e6f7-20b8-4391-9091-8e8e25561929"><br>
<img align="left" width="360" src="https://github.com/user-attachments/assets/7fdf41e6-281a-4b4b-ac19-020b838b6970">
### 添加上下文
**`@url`** 粘贴一个 URL 以供扩展获取并转换为 markdown当你想给 Cline 提供最新文档时非常有用
**`@problems`** 添加工作区错误和警告(“问题”面板)以供 Cline 修复
**`@file`** 添加文件内容,这样你就不必浪费 API 请求批准读取文件(+ 输入以搜索文件)
**`@folder`** 一次添加文件夹的文件,以进一步加快你的工作流程
<!-- 透明像素以在浮动图像后创建换行 -->
<img width="2000" height="0" src="https://github.com/user-attachments/assets/ee14e6f7-20b8-4391-9091-8e8e25561929"><br>
<img align="right" width="350" src="https://github.com/user-attachments/assets/140c8606-d3bf-41b9-9a1f-4dbf0d4c90cb">
### 检查点:比较和恢复
当 Cline 完成任务时,扩展会在每一步拍摄你的工作区快照。你可以使用“比较”按钮查看快照和当前工作区之间的差异,并使用“恢复”按钮回滚到该点。
例如,当使用本地 Web 服务器时,你可以使用“仅恢复工作区”快速测试应用程序的不同版本,然后在找到要继续构建的版本时使用“恢复任务和工作区”。这让你可以安全地探索不同的方法而不会丢失进度。
<!-- 透明像素以在浮动图像后创建换行 -->
<img width="2000" height="0" src="https://github.com/user-attachments/assets/ee14e6f7-20b8-4391-9091-8e8e25561929"><br>
## 贡献
要为项目做出贡献,请从我们的 [贡献指南](CONTRIBUTING.md) 开始,了解基础知识。你还可以加入我们的 [Discord](https://discord.gg/cline) 在 `#contributors` 频道与其他贡献者聊天。如果你正在寻找全职工作,请查看我们在 [招聘页面](https://cline.bot/join-us) 上的开放职位!
<details>
<summary>本地开发说明</summary>
1. 克隆仓库 _(需要 [git-lfs](https://git-lfs.com/))_
```bash
git clone https://github.com/cline/cline.git
```
2. 在 VSCode 中打开项目:
```bash
code cline
```
3. 安装扩展和 webview-gui 的必要依赖:
```bash
npm run install:all
```
4. 按 `F5`(或 `运行`->`开始调试`)启动以打开一个加载了扩展的新 VSCode 窗口。(如果你在构建项目时遇到问题,可能需要安装 [esbuild problem matchers 扩展](https://marketplace.visualstudio.com/items?itemName=connor4312.esbuild-problem-matchers)
</details>
## 许可证
[Apache 2.0 © 2024 Cline Bot Inc.](./LICENSE)

View file

@ -0,0 +1,47 @@
# 貢獻者公約行為準則
## 我們的承諾
為了促進一個開放和歡迎的環境,我們作為貢獻者和維護者承諾,使我們的項目和社區的參與對每個人來說都是一個無騷擾的體驗,不論年齡、體型、殘疾、種族、性別特徵、性別認同和表達、經驗水平、教育程度、社會經濟地位、國籍、個人外貌、種族、宗教或性取向。
## 我們的標準
有助於創造積極環境的行為示例包括:
- 使用歡迎和包容的語言
- 尊重不同的觀點和經驗
- 優雅地接受建設性的批評
- 專注於對社區最有利的事情
- 對其他社區成員表示同情
參與者不可接受的行為示例包括:
- 使用性化語言或圖像以及不受歡迎的性注意或挑逗
- 騷擾、侮辱/貶低性評論和個人或政治攻擊
- 公開或私下騷擾
- 未經明確許可發布他人的私人信息,例如物理或電子地址
- 其他在專業環境中合理認為不適當的行為
## 我們的責任
項目維護者有責任澄清可接受行為的標準,並預期對任何不可接受行為的實例採取適當和公平的糾正行動。
項目維護者有權利和責任刪除、編輯或拒絕與本行為準則不符的評論、提交、代碼、維基編輯、問題和其他貢獻,或暫時或永久禁止任何他們認為不適當、威脅、冒犯或有害的貢獻者。
## 範圍
此行為準則適用於項目空間內以及當個人代表項目或其社區時的公共空間。代表項目或社區的示例包括使用官方項目電子郵件地址、通過官方社交媒體帳戶發布或作為在線或離線活動的指定代表。項目的代表可能由項目維護者進一步定義和澄清。
## 執行
濫用、騷擾或其他不可接受行為的實例可以通過聯繫項目團隊 hi@cline.bot 來報告。所有投訴將被審查和調查,並將根據情況作出必要和適當的回應。項目團隊有義務對事件的報告者保密。具體執行政策的詳細信息可能會單獨發布。
未能善意遵循或執行行為準則的項目維護者可能會面臨由項目領導層其他成員決定的暫時或永久後果。
## 歸屬
此行為準則改編自 [Contributor Covenant][homepage],版本 1.4,可在 https://www.contributor-covenant.org/version/1/4/code-of-conduct.html 獲得。
[homepage]: https://www.contributor-covenant.org
有關此行為準則的常見問題的答案,請參見 https://www.contributor-covenant.org/faq

View file

@ -0,0 +1,82 @@
# 貢獻於 Cline
我們很高興您有興趣為 Cline 做出貢獻。無論您是修復錯誤、添加功能還是改進我們的文檔,每一個貢獻都讓 Cline 更加智能!為了保持我們的社區充滿活力和歡迎,所有成員必須遵守我們的[行為準則](CODE_OF_CONDUCT.md)。
## 報告錯誤或問題
錯誤報告有助於讓 Cline 對每個人都更好!在創建新問題之前,請[搜索現有問題](https://github.com/cline/cline/issues)以避免重複。當您準備報告錯誤時,請前往我們的[問題頁面](https://github.com/cline/cline/issues/new/choose),您會找到一個模板來幫助您填寫相關信息。
<blockquote class='warning-note'>
🔐 <b>重要:</b> 如果您發現安全漏洞,請使用<a href="https://github.com/cline/cline/security/advisories/new">Github 安全工具私下報告</a>
</blockquote>
## 決定要做什麼
尋找一個好的首次貢獻?查看標有["good first issue"](https://github.com/cline/cline/labels/good%20first%20issue)或["help wanted"](https://github.com/cline/cline/labels/help%20wanted)的問題。這些是專門為新貢獻者和我們希望得到幫助的領域策劃的!
我們也歡迎對我們[文檔](https://github.com/cline/cline/tree/main/docs)的貢獻!無論是修正錯別字、改進現有指南還是創建新的教育內容 - 我們希望建立一個由社區驅動的資源庫,幫助每個人充分利用 Cline。您可以從深入研究 `/docs` 並尋找需要改進的領域開始。
如果您計劃開發一個更大的功能,請先創建一個[功能請求](https://github.com/cline/cline/discussions/categories/feature-requests?discussions_q=is%3Aopen+category%3A%22Feature+Requests%22+sort%3Atop),以便我們討論它是否符合 Cline 的願景。
## 開發設置
1. **VS Code 擴展**
- 打開項目時VS Code 會提示您安裝推薦的擴展
- 這些擴展是開發所需的 - 請接受所有安裝提示
- 如果您忽略了提示,可以從擴展面板手動安裝它們
2. **本地開發**
- 運行 `npm run install:all` 安裝依賴項
- 運行 `npm run test` 本地運行測試
- 提交 PR 之前,運行 `npm run format:fix` 格式化您的代碼
## 編寫和提交代碼
任何人都可以為 Cline 貢獻代碼,但我們要求您遵循以下指南,以確保您的貢獻能夠順利集成:
1. **保持 Pull Requests 集中**
- 將 PR 限制在單個功能或錯誤修復
- 將較大的更改拆分為較小的相關 PR
- 將更改分為邏輯提交,可以獨立審查
2. **代碼質量**
- 運行 `npm run lint` 檢查代碼風格
- 運行 `npm run format` 自動格式化代碼
- 所有 PR 必須通過包括 lint 和格式化在內的 CI 檢查
- 提交前解決所有 ESLint 警告或錯誤
- 遵循 TypeScript 最佳實踐並保持類型安全
3. **測試**
- 為新功能添加測試
- 運行 `npm test` 確保所有測試通過
- 如果您的更改影響現有測試,請更新它們
- 在適當的地方包括單元測試和集成測試
4. **提交指南**
- 撰寫清晰、描述性的提交消息
- 使用常規提交格式(例如 "feat:"、"fix:"、"docs:"
- 在提交中引用相關問題,使用 #issue-number
5. **提交前**
- 將您的分支重新基於最新的 main
- 確保您的分支成功構建
- 仔細檢查所有測試是否通過
- 檢查您的更改是否有任何調試代碼或控制台日誌
6. **Pull Request 描述**
- 清楚地描述您的更改內容
- 包括測試更改的步驟
- 列出任何重大更改
- 為 UI 更改添加截圖
## 貢獻協議
通過提交 pull request您同意您的貢獻將根據與項目相同的許可證[Apache 2.0](LICENSE))進行許可。
記住:貢獻於 Cline 不僅僅是編寫代碼 - 這是關於成為一個塑造 AI 輔助開發未來的社區的一部分。讓我們一起創造一些驚人的東西!🚀

161
locales/zh-tw/README.md Normal file
View file

@ -0,0 +1,161 @@
# Cline OpenRouter 上的 \#1
<p align="center">
<img src="https://media.githubusercontent.com/media/cline/cline/main/assets/docs/demo.gif" width="100%" />
</p>
<div align="center">
<table>
<tbody>
<td align="center">
<a href="https://marketplace.visualstudio.com/items?itemName=saoudrizwan.claude-dev" target="_blank"><strong>在 VS Marketplace 下載</strong></a>
</td>
<td align="center">
<a href="https://discord.gg/cline" target="_blank"><strong>Discord</strong></a>
</td>
<td align="center">
<a href="https://www.reddit.com/r/cline/" target="_blank"><strong>r/cline</strong></a>
</td>
<td align="center">
<a href="https://github.com/cline/cline/discussions/categories/feature-requests?discussions_q=is%3Aopen+category%3A%22Feature+Requests%22+sort%3Atop" target="_blank"><strong>功能請求</strong></a>
</td>
<td align="center">
<a href="https://cline.bot/join-us" target="_blank"><strong>我們正在招聘!</strong></a>
</td>
</tbody>
</table>
</div>
認識 Cline一個可以使用你的 **CLI****編輯器** 的 AI 助手。
感謝 [Claude 3.5 Sonnet 的代理編碼能力](https://www-cdn.anthropic.com/fed9cc193a14b84131812372d8d5857f8f304c52/Model_Card_Claude_3_Addendum.pdf)Cline 可以一步步處理複雜的軟件開發任務。通過允許他創建和編輯文件、探索大型項目、使用瀏覽器和執行終端命令在你授予權限後他可以提供超越代碼完成或技術支持的幫助。Cline 甚至可以使用 Model Context Protocol (MCP) 創建新工具並擴展自己的能力。雖然自主 AI 腳本傳統上在沙盒環境中運行,但此擴展提供了一個人機交互的 GUI 來批准每個文件更改和終端命令,提供了一種安全且可訪問的方式來探索代理 AI 的潛力。
1. 輸入你的任務並添加圖像,將模型轉換為功能應用程序或通過截圖修復錯誤。
2. Cline 首先分析你的文件結構和源代碼 AST運行正則表達式搜索並閱讀相關文件以了解現有項目。通過仔細管理添加到上下文中的信息Cline 即使在大型複雜項目中也能提供有價值的幫助,而不會使上下文窗口過載。
3. 一旦 Cline 獲得所需信息,他可以:
- 創建和編輯文件 + 監控 linter/編譯器錯誤,從而主動修復諸如缺少導入和語法錯誤等問題。
- 直接在你的終端中執行命令並監控其輸出,從而在編輯文件後對開發服務器問題做出反應。
- 對於 Web 開發任務Cline 可以在無頭瀏覽器中啟動網站,點擊、輸入、滾動並捕獲截圖和控制台日誌,從而修復運行時錯誤和視覺錯誤。
4. 當任務完成時Cline 將通過終端命令如 `open -a "Google Chrome" index.html` 向你展示結果,你可以通過點擊按鈕運行該命令。
> [!提示]
> 使用 `CMD/CTRL + Shift + P` 快捷鍵打開命令面板並輸入 "Cline: Open In New Tab" 將擴展作為標籤在編輯器中打開。這讓你可以與文件資源管理器並排使用 Cline更清楚地看到他如何改變你的工作空間。
---
<img align="right" width="340" src="https://github.com/user-attachments/assets/3cf21e04-7ce9-4d22-a7b9-ba2c595e88a4">
### 使用任何 API 和模型
Cline 支持 OpenRouter、Anthropic、OpenAI、Google Gemini、AWS Bedrock、Azure 和 GCP Vertex 等 API 提供商。你還可以配置任何兼容 OpenAI 的 API或通過 LM Studio/Ollama 使用本地模型。如果你使用 OpenRouter擴展會獲取他們的最新模型列表讓你在新模型可用時立即使用。
擴展還會跟蹤整個任務循環和單個請求的總令牌和 API 使用成本,讓你在每一步都了解支出情況。
<!-- 透明像素以在浮動圖像後創建換行 -->
<img width="2000" height="0" src="https://github.com/user-attachments/assets/ee14e6f7-20b8-4391-9091-8e8e25561929"><br>
<img align="left" width="370" src="https://github.com/user-attachments/assets/81be79a8-1fdb-4028-9129-5fe055e01e76">
### 在終端中運行命令
感謝 VSCode v1.93 中的新 [終端 shell 集成更新](https://code.visualstudio.com/updates/v1_93#_terminal-shell-integration-api)Cline 可以直接在你的終端中執行命令並接收輸出。這使他能夠執行廣泛的任務,從安裝包和運行構建腳本到部署應用程序、管理數據庫和執行測試,同時適應你的開發環境和工具鏈以正確完成工作。
對於長時間運行的進程如開發服務器,使用“在運行時繼續”按鈕讓 Cline 在命令後台運行時繼續任務。當 Cline 工作時,他會在過程中收到任何新的終端輸出通知,讓他對可能出現的問題做出反應,例如編輯文件時的編譯時錯誤。
<!-- 透明像素以在浮動圖像後創建換行 -->
<img width="2000" height="0" src="https://github.com/user-attachments/assets/ee14e6f7-20b8-4391-9091-8e8e25561929"><br>
<img align="right" width="400" src="https://github.com/user-attachments/assets/c5977833-d9b8-491e-90f9-05f9cd38c588">
### 創建和編輯文件
Cline 可以直接在你的編輯器中創建和編輯文件,向你展示更改的差異視圖。你可以直接在差異視圖編輯器中編輯或恢復 Cline 的更改或在聊天中提供反饋直到你對結果滿意。Cline 還會監控 linter/編譯器錯誤(缺少導入、語法錯誤等),以便他在過程中自行修復出現的問題。
Cline 所做的所有更改都會記錄在你的文件時間軸中,提供了一種簡單的方法來跟蹤和恢復修改(如果需要)。
<!-- 透明像素以在浮動圖像後創建換行 -->
<img width="2000" height="0" src="https://github.com/user-attachments/assets/ee14e6f7-20b8-4391-9091-8e8e25561929"><br>
<img align="left" width="370" src="https://github.com/user-attachments/assets/bc2e85ba-dfeb-4fe6-9942-7cfc4703cbe5">
### 使用瀏覽器
借助 Claude 3.5 Sonnet 的新 [計算機使用](https://www.anthropic.com/news/3-5-models-and-computer-use) 功能Cline 可以啟動瀏覽器,點擊元素,輸入文本和滾動,在每一步捕獲截圖和控制台日誌。這允許進行交互式調試、端到端測試,甚至是一般的網頁使用!這使他能夠自主修復視覺錯誤和運行時問題,而無需你親自操作和複製粘貼錯誤日誌。
試試讓 Cline “測試應用程序”,看看他如何運行 `npm run dev` 命令,在瀏覽器中啟動你本地運行的開發服務器,並執行一系列測試以確認一切正常。[在這裡查看演示。](https://x.com/sdrzn/status/1850880547825823989)
<!-- 透明像素以在浮動圖像後創建換行 -->
<img width="2000" height="0" src="https://github.com/user-attachments/assets/ee14e6f7-20b8-4391-9091-8e8e25561929"><br>
<img align="right" width="350" src="https://github.com/user-attachments/assets/ac0efa14-5c1f-4c26-a42d-9d7c56f5fadd">
### “添加一個工具……”
感謝 [Model Context Protocol](https://github.com/modelcontextprotocol)Cline 可以通過自定義工具擴展他的能力。雖然你可以使用 [社區製作的服務器](https://github.com/modelcontextprotocol/servers),但 Cline 可以創建和安裝適合你特定工作流程的工具。只需讓 Cline “添加一個工具”,他將處理所有事情,從創建新的 MCP 服務器到將其安裝到擴展中。這些自定義工具將成為 Cline 工具包的一部分,準備在未來的任務中使用。
- “添加一個獲取 Jira 工單的工具”:檢索工單 AC 並讓 Cline 開始工作
- “添加一個管理 AWS EC2 的工具”:檢查服務器指標並上下擴展實例
- “添加一個獲取最新 PagerDuty 事件的工具”:獲取詳細信息並讓 Cline 修復錯誤
<!-- 透明像素以在浮動圖像後創建換行 -->
<img width="2000" height="0" src="https://github.com/user-attachments/assets/ee14e6f7-20b8-4391-9091-8e8e25561929"><br>
<img align="left" width="360" src="https://github.com/user-attachments/assets/7fdf41e6-281a-4b4b-ac19-020b838b6970">
### 添加上下文
**`@url`** 粘貼一個 URL 以供擴展獲取並轉換為 markdown當你想給 Cline 提供最新文檔時非常有用
**`@problems`** 添加工作區錯誤和警告(“問題”面板)以供 Cline 修復
**`@file`** 添加文件內容,這樣你就不必浪費 API 請求批准讀取文件(+ 輸入以搜索文件)
**`@folder`** 一次添加文件夾的文件,以進一步加快你的工作流程
<!-- 透明像素以在浮動圖像後創建換行 -->
<img width="2000" height="0" src="https://github.com/user-attachments/assets/ee14e6f7-20b8-4391-9091-8e8e25561929"><br>
<img align="right" width="350" src="https://github.com/user-attachments/assets/140c8606-d3bf-41b9-9a1f-4dbf0d4c90cb">
### 檢查點:比較和恢復
當 Cline 完成任務時,擴展會在每一步拍攝你的工作區快照。你可以使用“比較”按鈕查看快照和當前工作區之間的差異,並使用“恢復”按鈕回滾到該點。
例如,當使用本地 Web 服務器時,你可以使用“僅恢復工作區”快速測試應用程序的不同版本,然後在找到要繼續構建的版本時使用“恢復任務和工作區”。這讓你可以安全地探索不同的方法而不會丟失進度。
<!-- 透明像素以在浮動圖像後創建換行 -->
<img width="2000" height="0" src="https://github.com/user-attachments/assets/ee14e6f7-20b8-4391-9091-8e8e25561929"><br>
## 貢獻
要為項目做出貢獻,請從我們的 [貢獻指南](CONTRIBUTING.md) 開始,了解基礎知識。你還可以加入我們的 [Discord](https://discord.gg/cline) 在 `#contributors` 頻道與其他貢獻者聊天。如果你正在尋找全職工作,請查看我們在 [招聘頁面](https://cline.bot/join-us) 上的開放職位!
<details>
<summary>本地開發說明</summary>
1. 克隆倉庫 _(需要 [git-lfs](https://git-lfs.com/))_
```bash
git clone https://github.com/cline/cline.git
```
2. 在 VSCode 中打開項目:
```bash
code cline
```
3. 安裝擴展和 webview-gui 的必要依賴:
```bash
npm run install:all
```
4. 按 `F5`(或 `運行`->`開始調試`)啟動以打開一個加載了擴展的新 VSCode 窗口。(如果你在構建項目時遇到問題,可能需要安裝 [esbuild problem matchers 擴展](https://marketplace.visualstudio.com/items?itemName=connor4312.esbuild-problem-matchers)
</details>
## 許可證
[Apache 2.0 © 2024 Cline Bot Inc.](./LICENSE)

2375
package-lock.json generated

File diff suppressed because it is too large Load diff

View file

@ -1,8 +1,8 @@
{
"name": "claude-dev",
"displayName": "Cline (prev. Claude Dev)",
"displayName": "Cline",
"description": "Autonomous coding agent right in your IDE, capable of creating/editing files, running commands, using the browser, and more with your permission every step of the way.",
"version": "3.0.6",
"version": "3.2.12",
"icon": "assets/icons/icon.png",
"galleryBanner": {
"color": "#617A91",
@ -51,7 +51,7 @@
{
"id": "claude-dev-ActivityBar",
"title": "Cline",
"icon": "$(robot)"
"icon": "assets/icons/icon.svg"
}
]
},
@ -124,6 +124,45 @@
"when": "view == claude-dev.SidebarProvider"
}
]
},
"configuration": {
"title": "Cline",
"properties": {
"cline.vsCodeLmModelSelector": {
"type": "object",
"properties": {
"vendor": {
"type": "string",
"description": "The vendor of the language model (e.g. copilot)"
},
"family": {
"type": "string",
"description": "The family of the language model (e.g. gpt-4)"
}
},
"description": "Settings for VSCode Language Model API"
},
"cline.mcp.mode": {
"type": "string",
"enum": [
"full",
"server-use-only",
"off"
],
"enumDescriptions": [
"Enable all MCP functionality (server use and build instructions)",
"Enable MCP server use only (excludes instructions about building MCP servers)",
"Disable all MCP functionality"
],
"default": "full",
"description": "Controls MCP inclusion in prompts, reduces token usage if you only need access to certain functionality."
},
"cline.enableCheckpoints": {
"type": "boolean",
"default": true,
"description": "Enables extension to save checkpoints of workspace throughout the task."
}
}
}
},
"scripts": {
@ -145,9 +184,15 @@
"start:webview": "cd webview-ui && npm run start",
"build:webview": "cd webview-ui && npm run build",
"test:webview": "cd webview-ui && npm run test",
"publish:marketplace": "vsce publish && ovsx publish"
"publish:marketplace": "vsce publish && ovsx publish",
"publish:marketplace:prerelease": "vsce publish --pre-release && ovsx publish --pre-release",
"prepare": "husky",
"changeset": "changeset",
"version-packages": "changeset version"
},
"devDependencies": {
"@changesets/cli": "^2.27.12",
"@types/chai": "^5.0.1",
"@types/diff": "^5.2.1",
"@types/mocha": "^10.0.7",
"@types/node": "20.x",
@ -157,8 +202,10 @@
"@typescript-eslint/parser": "^7.11.0",
"@vscode/test-cli": "^0.0.9",
"@vscode/test-electron": "^2.4.0",
"chai": "^4.3.10",
"esbuild": "^0.21.5",
"eslint": "^8.57.0",
"husky": "^9.1.7",
"npm-run-all": "^4.1.5",
"prettier": "^3.3.3",
"should": "^13.2.3",
@ -169,8 +216,10 @@
"@anthropic-ai/sdk": "^0.26.0",
"@anthropic-ai/vertex-sdk": "^0.4.1",
"@google/generative-ai": "^0.18.0",
"@mistralai/mistralai": "^1.3.6",
"@modelcontextprotocol/sdk": "^1.0.1",
"@types/clone-deep": "^4.0.4",
"@types/get-folder-size": "^3.0.4",
"@types/pdf-parse": "^1.1.4",
"@types/turndown": "^5.0.5",
"@vscode/codicons": "^0.0.36",
@ -183,17 +232,21 @@
"diff": "^5.2.0",
"execa": "^9.5.2",
"fast-deep-equal": "^3.1.3",
"firebase": "^11.2.0",
"get-folder-size": "^5.0.0",
"globby": "^14.0.2",
"ignore": "^7.0.3",
"isbinaryfile": "^5.0.2",
"mammoth": "^1.8.0",
"monaco-vscode-textmate-theme-converter": "^0.1.7",
"openai": "^4.61.0",
"openai": "^4.82.0",
"os-name": "^6.0.0",
"p-wait-for": "^5.0.2",
"pdf-parse": "^1.1.1",
"puppeteer-chromium-resolver": "^23.0.0",
"puppeteer-core": "^23.4.0",
"serialize-error": "^11.0.3",
"simple-git": "^3.27.0",
"strip-ansi": "^7.1.0",
"tree-sitter-wasms": "^0.1.11",
"turndown": "^7.2.0",

View file

@ -10,12 +10,20 @@ import { LmStudioHandler } from "./providers/lmstudio"
import { GeminiHandler } from "./providers/gemini"
import { OpenAiNativeHandler } from "./providers/openai-native"
import { ApiStream } from "./transform/stream"
import { DeepSeekHandler } from "./providers/deepseek"
import { MistralHandler } from "./providers/mistral"
import { VsCodeLmHandler } from "./providers/vscode-lm"
import { LiteLlmHandler } from "./providers/litellm"
export interface ApiHandler {
createMessage(systemPrompt: string, messages: Anthropic.Messages.MessageParam[]): ApiStream
getModel(): { id: string; info: ModelInfo }
}
export interface SingleCompletionHandler {
completePrompt(prompt: string): Promise<string>
}
export function buildApiHandler(configuration: ApiConfiguration): ApiHandler {
const { apiProvider, ...options } = configuration
switch (apiProvider) {
@ -37,6 +45,14 @@ export function buildApiHandler(configuration: ApiConfiguration): ApiHandler {
return new GeminiHandler(options)
case "openai-native":
return new OpenAiNativeHandler(options)
case "deepseek":
return new DeepSeekHandler(options)
case "mistral":
return new MistralHandler(options)
case "vscode-lm":
return new VsCodeLmHandler(options)
case "litellm":
return new LiteLlmHandler(options)
default:
return new AnthropicHandler(options)
}

View file

@ -1,12 +1,6 @@
import { Anthropic } from "@anthropic-ai/sdk"
import { Stream as AnthropicStream } from "@anthropic-ai/sdk/streaming"
import {
anthropicDefaultModelId,
AnthropicModelId,
anthropicModels,
ApiHandlerOptions,
ModelInfo,
} from "../../shared/api"
import { anthropicDefaultModelId, AnthropicModelId, anthropicModels, ApiHandlerOptions, ModelInfo } from "../../shared/api"
import { ApiHandler } from "../index"
import { ApiStream } from "../transform/stream"
@ -23,8 +17,9 @@ export class AnthropicHandler implements ApiHandler {
}
async *createMessage(systemPrompt: string, messages: Anthropic.Messages.MessageParam[]): ApiStream {
const model = this.getModel()
let stream: AnthropicStream<Anthropic.Beta.PromptCaching.Messages.RawPromptCachingBetaMessageStreamEvent>
const modelId = this.getModel().id
const modelId = model.id
switch (modelId) {
// 'latest' alias does not support cache_control
case "claude-3-5-sonnet-20241022":
@ -43,9 +38,15 @@ export class AnthropicHandler implements ApiHandler {
stream = await this.client.beta.promptCaching.messages.create(
{
model: modelId,
max_tokens: this.getModel().info.maxTokens || 8192,
max_tokens: model.info.maxTokens || 8192,
temperature: 0,
system: [{ text: systemPrompt, type: "text", cache_control: { type: "ephemeral" } }], // setting cache breakpoint for system prompt so new tasks can reuse it
system: [
{
text: systemPrompt,
type: "text",
cache_control: { type: "ephemeral" },
},
], // setting cache breakpoint for system prompt so new tasks can reuse it
messages: messages.map((message, index) => {
if (index === lastUserMsgIndex || index === secondLastMsgUserIndex) {
return {
@ -56,12 +57,19 @@ export class AnthropicHandler implements ApiHandler {
{
type: "text",
text: message.content,
cache_control: { type: "ephemeral" },
cache_control: {
type: "ephemeral",
},
},
]
: message.content.map((content, contentIndex) =>
contentIndex === message.content.length - 1
? { ...content, cache_control: { type: "ephemeral" } }
? {
...content,
cache_control: {
type: "ephemeral",
},
}
: content,
),
}
@ -83,7 +91,9 @@ export class AnthropicHandler implements ApiHandler {
case "claude-3-opus-20240229":
case "claude-3-haiku-20240307":
return {
headers: { "anthropic-beta": "prompt-caching-2024-07-31" },
headers: {
"anthropic-beta": "prompt-caching-2024-07-31",
},
}
default:
return undefined
@ -95,7 +105,7 @@ export class AnthropicHandler implements ApiHandler {
default: {
stream = (await this.client.messages.create({
model: modelId,
max_tokens: this.getModel().info.maxTokens || 8192,
max_tokens: model.info.maxTokens || 8192,
temperature: 0,
system: [{ text: systemPrompt, type: "text" }],
messages,
@ -171,6 +181,9 @@ export class AnthropicHandler implements ApiHandler {
const id = modelId as AnthropicModelId
return { id, info: anthropicModels[id] }
}
return { id: anthropicDefaultModelId, info: anthropicModels[anthropicDefaultModelId] }
return {
id: anthropicDefaultModelId,
info: anthropicModels[anthropicDefaultModelId],
}
}
}

View file

@ -107,6 +107,9 @@ export class AwsBedrockHandler implements ApiHandler {
const id = modelId as BedrockModelId
return { id, info: bedrockModels[id] }
}
return { id: bedrockDefaultModelId, info: bedrockModels[bedrockDefaultModelId] }
return {
id: bedrockDefaultModelId,
info: bedrockModels[bedrockDefaultModelId],
}
}
}

View file

@ -0,0 +1,86 @@
import { Anthropic } from "@anthropic-ai/sdk"
import OpenAI from "openai"
import { ApiHandler } from "../"
import { ApiHandlerOptions, DeepSeekModelId, ModelInfo, deepSeekDefaultModelId, deepSeekModels } from "../../shared/api"
import { convertToOpenAiMessages } from "../transform/openai-format"
import { ApiStream } from "../transform/stream"
import { convertToR1Format } from "../transform/r1-format"
export class DeepSeekHandler implements ApiHandler {
private options: ApiHandlerOptions
private client: OpenAI
constructor(options: ApiHandlerOptions) {
this.options = options
this.client = new OpenAI({
baseURL: "https://api.deepseek.com/v1",
apiKey: this.options.deepSeekApiKey,
})
}
async *createMessage(systemPrompt: string, messages: Anthropic.Messages.MessageParam[]): ApiStream {
const model = this.getModel()
const isDeepseekReasoner = model.id.includes("deepseek-reasoner")
let openAiMessages: OpenAI.Chat.ChatCompletionMessageParam[] = [
{ role: "system", content: systemPrompt },
...convertToOpenAiMessages(messages),
]
if (isDeepseekReasoner) {
openAiMessages = convertToR1Format([{ role: "user", content: systemPrompt }, ...messages])
}
const stream = await this.client.chat.completions.create({
model: model.id,
max_completion_tokens: model.info.maxTokens,
messages: openAiMessages,
stream: true,
stream_options: { include_usage: true },
// Only set temperature for non-reasoner models
...(model.id === "deepseek-reasoner" ? {} : { temperature: 0 }),
})
for await (const chunk of stream) {
const delta = chunk.choices[0]?.delta
if (delta?.content) {
yield {
type: "text",
text: delta.content,
}
}
if (delta && "reasoning_content" in delta && delta.reasoning_content) {
yield {
type: "reasoning",
reasoning: (delta.reasoning_content as string | undefined) || "",
}
}
if (chunk.usage) {
yield {
type: "usage",
inputTokens: chunk.usage.prompt_tokens || 0, // (deepseek reports total input AND cache reads/writes, see context caching: https://api-docs.deepseek.com/guides/kv_cache) where the input tokens is the sum of the cache hits/misses, while anthropic reports them as separate tokens. This is important to know for 1) context management truncation algorithm, and 2) cost calculation (NOTE: we report both input and cache stats but for now set input price to 0 since all the cost calculation will be done using cache hits/misses)
outputTokens: chunk.usage.completion_tokens || 0,
// @ts-ignore-next-line
cacheReadTokens: chunk.usage.prompt_cache_hit_tokens || 0,
// @ts-ignore-next-line
cacheWriteTokens: chunk.usage.prompt_cache_miss_tokens || 0,
}
}
}
}
getModel(): { id: DeepSeekModelId; info: ModelInfo } {
const modelId = this.options.apiModelId
if (modelId && modelId in deepSeekModels) {
const id = modelId as DeepSeekModelId
return { id, info: deepSeekModels[id] }
}
return {
id: deepSeekDefaultModelId,
info: deepSeekModels[deepSeekDefaultModelId],
}
}
}

View file

@ -51,6 +51,9 @@ export class GeminiHandler implements ApiHandler {
const id = modelId as GeminiModelId
return { id, info: geminiModels[id] }
}
return { id: geminiDefaultModelId, info: geminiModels[geminiDefaultModelId] }
return {
id: geminiDefaultModelId,
info: geminiModels[geminiDefaultModelId],
}
}
}

View file

@ -0,0 +1,60 @@
import { Anthropic } from "@anthropic-ai/sdk"
import OpenAI from "openai"
import { ApiHandlerOptions, liteLlmDefaultModelId, liteLlmModelInfoSaneDefaults } from "../../shared/api"
import { ApiHandler } from ".."
import { ApiStream } from "../transform/stream"
import { convertToOpenAiMessages } from "../transform/openai-format"
export class LiteLlmHandler implements ApiHandler {
private options: ApiHandlerOptions
private client: OpenAI
constructor(options: ApiHandlerOptions) {
this.options = options
this.client = new OpenAI({
baseURL: this.options.liteLlmBaseUrl || "http://localhost:4000",
apiKey: "not-needed",
})
}
async *createMessage(systemPrompt: string, messages: Anthropic.Messages.MessageParam[]): ApiStream {
const formattedMessages = convertToOpenAiMessages(messages)
const systemMessage: OpenAI.Chat.ChatCompletionSystemMessageParam = {
role: "system",
content: systemPrompt,
}
const stream = await this.client.chat.completions.create({
model: this.options.liteLlmModelId || liteLlmDefaultModelId,
messages: [systemMessage, ...formattedMessages],
temperature: 0,
stream: true,
stream_options: { include_usage: true },
})
for await (const chunk of stream) {
const delta = chunk.choices[0]?.delta
if (delta?.content) {
yield {
type: "text",
text: delta.content,
}
}
if (chunk.usage) {
yield {
type: "usage",
inputTokens: chunk.usage.prompt_tokens || 0,
outputTokens: chunk.usage.completion_tokens || 0,
}
}
}
}
getModel() {
return {
id: this.options.liteLlmModelId || liteLlmDefaultModelId,
info: liteLlmModelInfoSaneDefaults,
}
}
}

View file

@ -0,0 +1,74 @@
import { Anthropic } from "@anthropic-ai/sdk"
import { Mistral } from "@mistralai/mistralai"
import { ApiHandler } from "../"
import {
ApiHandlerOptions,
mistralDefaultModelId,
MistralModelId,
mistralModels,
ModelInfo,
openAiNativeDefaultModelId,
OpenAiNativeModelId,
openAiNativeModels,
} from "../../shared/api"
import { convertToMistralMessages } from "../transform/mistral-format"
import { ApiStream } from "../transform/stream"
export class MistralHandler implements ApiHandler {
private options: ApiHandlerOptions
private client: Mistral
constructor(options: ApiHandlerOptions) {
this.options = options
this.client = new Mistral({
serverURL: "https://api.mistral.ai",
apiKey: this.options.mistralApiKey,
})
}
async *createMessage(systemPrompt: string, messages: Anthropic.Messages.MessageParam[]): ApiStream {
const stream = await this.client.chat.stream({
model: this.getModel().id,
// max_completion_tokens: this.getModel().info.maxTokens,
temperature: 0,
messages: [{ role: "system", content: systemPrompt }, ...convertToMistralMessages(messages)],
stream: true,
})
for await (const chunk of stream) {
const delta = chunk.data.choices[0]?.delta
if (delta?.content) {
let content: string = ""
if (typeof delta.content === "string") {
content = delta.content
} else if (Array.isArray(delta.content)) {
content = delta.content.map((c) => (c.type === "text" ? c.text : "")).join("")
}
yield {
type: "text",
text: content,
}
}
if (chunk.data.usage) {
yield {
type: "usage",
inputTokens: chunk.data.usage.promptTokens || 0,
outputTokens: chunk.data.usage.completionTokens || 0,
}
}
}
}
getModel(): { id: MistralModelId; info: ModelInfo } {
const modelId = this.options.apiModelId
if (modelId && modelId in mistralModels) {
const id = modelId as MistralModelId
return { id, info: mistralModels[id] }
}
return {
id: mistralDefaultModelId,
info: mistralModels[mistralDefaultModelId],
}
}
}

View file

@ -24,6 +24,7 @@ export class OpenAiNativeHandler implements ApiHandler {
async *createMessage(systemPrompt: string, messages: Anthropic.Messages.MessageParam[]): ApiStream {
switch (this.getModel().id) {
case "o1":
case "o1-preview":
case "o1-mini": {
// o1 doesnt support streaming, non-1 temp, or system prompt
@ -42,6 +43,31 @@ export class OpenAiNativeHandler implements ApiHandler {
}
break
}
case "o3-mini": {
const stream = await this.client.chat.completions.create({
model: this.getModel().id,
messages: [{ role: "developer", content: systemPrompt }, ...convertToOpenAiMessages(messages)],
stream: true,
stream_options: { include_usage: true },
})
for await (const chunk of stream) {
const delta = chunk.choices[0]?.delta
if (delta?.content) {
yield {
type: "text",
text: delta.content,
}
}
if (chunk.usage) {
yield {
type: "usage",
inputTokens: chunk.usage.prompt_tokens || 0,
outputTokens: chunk.usage.completion_tokens || 0,
}
}
}
break
}
default: {
const stream = await this.client.chat.completions.create({
model: this.getModel().id,
@ -80,6 +106,9 @@ export class OpenAiNativeHandler implements ApiHandler {
const id = modelId as OpenAiNativeModelId
return { id, info: openAiNativeModels[id] }
}
return { id: openAiNativeDefaultModelId, info: openAiNativeModels[openAiNativeDefaultModelId] }
return {
id: openAiNativeDefaultModelId,
info: openAiNativeModels[openAiNativeDefaultModelId],
}
}
}

View file

@ -1,14 +1,10 @@
import { Anthropic } from "@anthropic-ai/sdk"
import OpenAI, { AzureOpenAI } from "openai"
import {
ApiHandlerOptions,
azureOpenAiDefaultApiVersion,
ModelInfo,
openAiModelInfoSaneDefaults,
} from "../../shared/api"
import { ApiHandlerOptions, azureOpenAiDefaultApiVersion, ModelInfo, openAiModelInfoSaneDefaults } from "../../shared/api"
import { ApiHandler } from "../index"
import { convertToOpenAiMessages } from "../transform/openai-format"
import { ApiStream } from "../transform/stream"
import { convertToR1Format } from "../transform/r1-format"
export class OpenAiHandler implements ApiHandler {
private options: ApiHandlerOptions
@ -32,12 +28,20 @@ export class OpenAiHandler implements ApiHandler {
}
async *createMessage(systemPrompt: string, messages: Anthropic.Messages.MessageParam[]): ApiStream {
const openAiMessages: OpenAI.Chat.ChatCompletionMessageParam[] = [
const modelId = this.options.openAiModelId ?? ""
const isDeepseekReasoner = modelId.includes("deepseek-reasoner")
let openAiMessages: OpenAI.Chat.ChatCompletionMessageParam[] = [
{ role: "system", content: systemPrompt },
...convertToOpenAiMessages(messages),
]
if (isDeepseekReasoner) {
openAiMessages = convertToR1Format([{ role: "user", content: systemPrompt }, ...messages])
}
const stream = await this.client.chat.completions.create({
model: this.options.openAiModelId ?? "",
model: modelId,
messages: openAiMessages,
temperature: 0,
stream: true,
@ -51,6 +55,14 @@ export class OpenAiHandler implements ApiHandler {
text: delta.content,
}
}
if (delta && "reasoning_content" in delta && delta.reasoning_content) {
yield {
type: "reasoning",
reasoning: (delta.reasoning_content as string | undefined) || "",
}
}
if (chunk.usage) {
yield {
type: "usage",

View file

@ -1,11 +1,12 @@
import { Anthropic } from "@anthropic-ai/sdk"
import axios from "axios"
import delay from "delay"
import OpenAI from "openai"
import { ApiHandler } from "../"
import { ApiHandlerOptions, ModelInfo, openRouterDefaultModelId, openRouterDefaultModelInfo } from "../../shared/api"
import { convertToOpenAiMessages } from "../transform/openai-format"
import { ApiStream } from "../transform/stream"
import delay from "delay"
import { convertToR1Format } from "../transform/r1-format"
export class OpenRouterHandler implements ApiHandler {
private options: ApiHandlerOptions
@ -24,15 +25,17 @@ export class OpenRouterHandler implements ApiHandler {
}
async *createMessage(systemPrompt: string, messages: Anthropic.Messages.MessageParam[]): ApiStream {
const model = this.getModel()
// Convert Anthropic messages to OpenAI format
const openAiMessages: OpenAI.Chat.ChatCompletionMessageParam[] = [
let openAiMessages: OpenAI.Chat.ChatCompletionMessageParam[] = [
{ role: "system", content: systemPrompt },
...convertToOpenAiMessages(messages),
]
// 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) {
switch (model.id) {
case "anthropic/claude-3.5-sonnet":
case "anthropic/claude-3.5-sonnet:beta":
case "anthropic/claude-3.5-sonnet-20240620":
@ -83,7 +86,7 @@ export class OpenRouterHandler implements ApiHandler {
// Not sure how openrouter defaults max tokens when no value is provided, but the anthropic api requires this value and since they offer both 4096 and 8192 variants, we should ensure 8192.
// (models usually default to max tokens allowed)
let maxTokens: number | undefined
switch (this.getModel().id) {
switch (model.id) {
case "anthropic/claude-3.5-sonnet":
case "anthropic/claude-3.5-sonnet:beta":
case "anthropic/claude-3.5-sonnet-20240620":
@ -96,17 +99,35 @@ export class OpenRouterHandler implements ApiHandler {
break
}
let temperature = 0
let topP: number | undefined = undefined
// Handle models based on deepseek-r1
if (this.getModel().id.startsWith("deepseek/deepseek-r1") || this.getModel().id === "perplexity/sonar-reasoning") {
// Recommended temperature for DeepSeek reasoning models
temperature = 0.6
// DeepSeek highly recommends using user instead of system role
openAiMessages = convertToR1Format([{ role: "user", content: systemPrompt }, ...messages])
// Some provider support topP and 0.95 is value that Deepseek used in their benchmarks
topP = 0.95
}
// Removes messages in the middle when close to context window limit. Should not be applied to models that support prompt caching since it would continuously break the cache.
const shouldApplyMiddleOutTransform = !this.getModel().info.supportsPromptCache
let shouldApplyMiddleOutTransform = !model.info.supportsPromptCache
// except for deepseek (which we set supportsPromptCache to true for), where because the context window is so small our truncation algo might miss and we should use openrouter's middle-out transform as a fallback to ensure we don't exceed the context window (FIXME: once we have a more robust token estimator we should not rely on this)
if (model.id === "deepseek/deepseek-chat") {
shouldApplyMiddleOutTransform = true
}
// @ts-ignore-next-line
const stream = await this.client.chat.completions.create({
model: this.getModel().id,
model: model.id,
max_tokens: maxTokens,
temperature: 0,
temperature: temperature,
top_p: topP,
messages: openAiMessages,
stream: true,
transforms: shouldApplyMiddleOutTransform ? ["middle-out"] : undefined,
include_reasoning: true,
})
let genId: string | undefined
@ -130,6 +151,37 @@ export class OpenRouterHandler implements ApiHandler {
text: delta.content,
}
}
// Reasoning tokens are returned separately from the content
if ("reasoning" in delta && delta.reasoning) {
// console.log("reasoning", delta.reasoning)
yield {
type: "reasoning",
// @ts-ignore-next-line
reasoning: delta.reasoning,
}
// if (didStreamThinkTagInReasoning) {
// yield {
// type: "text",
// // @ts-ignore-next-line
// text: delta.reasoning,
// }
// } else {
// yield {
// type: "reasoning",
// // @ts-ignore-next-line
// text: delta.reasoning,
// }
// // @ts-ignore-next-line
// reasoningResponse += delta.reasoning
// if (reasoningResponse.includes("</think>")) {
// didStreamThinkTagInReasoning = true
// console.log("did hit think tag", reasoningResponse)
// }
// }
}
// if (chunk.usage) {
// yield {
// type: "usage",

View file

@ -81,6 +81,9 @@ export class VertexHandler implements ApiHandler {
const id = modelId as VertexModelId
return { id, info: vertexModels[id] }
}
return { id: vertexDefaultModelId, info: vertexModels[vertexDefaultModelId] }
return {
id: vertexDefaultModelId,
info: vertexModels[vertexDefaultModelId],
}
}
}

View file

@ -0,0 +1,639 @@
import { Anthropic } from "@anthropic-ai/sdk"
import * as vscode from "vscode"
import { ApiHandler, SingleCompletionHandler } from "../"
import { calculateApiCost } from "../../utils/cost"
import { ApiStream } from "../transform/stream"
import { convertToVsCodeLmMessages } from "../transform/vscode-lm-format"
import { SELECTOR_SEPARATOR, stringifyVsCodeLmModelSelector } from "../../shared/vsCodeSelectorUtils"
import { ApiHandlerOptions, ModelInfo, openAiModelInfoSaneDefaults } from "../../shared/api"
// Cline does not update VSCode type definitions or engine requirements to maintain compatibility.
// This declaration (as seen in src/integrations/TerminalManager.ts) provides types for the Language Model API in newer versions of VSCode.
// Extracted from https://github.com/microsoft/vscode/blob/131ee0ef660d600cd0a7e6058375b281553abe20/src/vscode-dts/vscode.d.ts
declare module "vscode" {
enum LanguageModelChatMessageRole {
User = 1,
Assistant = 2,
}
enum LanguageModelChatToolMode {
Auto = 1,
Required = 2,
}
interface LanguageModelChatSelector {
vendor?: string
family?: string
version?: string
id?: string
}
interface LanguageModelChatTool {
name: string
description: string
inputSchema?: object
}
interface LanguageModelChatRequestOptions {
justification?: string
modelOptions?: { [name: string]: any }
tools?: LanguageModelChatTool[]
toolMode?: LanguageModelChatToolMode
}
class LanguageModelTextPart {
value: string
constructor(value: string)
}
class LanguageModelToolCallPart {
callId: string
name: string
input: object
constructor(callId: string, name: string, input: object)
}
interface LanguageModelChatResponse {
stream: AsyncIterable<LanguageModelTextPart | LanguageModelToolCallPart | unknown>
text: AsyncIterable<string>
}
interface LanguageModelChat {
readonly name: string
readonly id: string
readonly vendor: string
readonly family: string
readonly version: string
readonly maxInputTokens: number
sendRequest(
messages: LanguageModelChatMessage[],
options?: LanguageModelChatRequestOptions,
token?: CancellationToken,
): Thenable<LanguageModelChatResponse>
countTokens(text: string | LanguageModelChatMessage, token?: CancellationToken): Thenable<number>
}
class LanguageModelPromptTsxPart {
value: unknown
constructor(value: unknown)
}
class LanguageModelToolResultPart {
callId: string
content: Array<LanguageModelTextPart | LanguageModelPromptTsxPart | unknown>
constructor(callId: string, content: Array<LanguageModelTextPart | LanguageModelPromptTsxPart | unknown>)
}
class LanguageModelChatMessage {
static User(
content: string | Array<LanguageModelTextPart | LanguageModelToolResultPart>,
name?: string,
): LanguageModelChatMessage
static Assistant(
content: string | Array<LanguageModelTextPart | LanguageModelToolCallPart>,
name?: string,
): LanguageModelChatMessage
role: LanguageModelChatMessageRole
content: Array<LanguageModelTextPart | LanguageModelToolResultPart | LanguageModelToolCallPart>
name: string | undefined
constructor(
role: LanguageModelChatMessageRole,
content: string | Array<LanguageModelTextPart | LanguageModelToolResultPart | LanguageModelToolCallPart>,
name?: string,
)
}
namespace lm {
function selectChatModels(selector?: LanguageModelChatSelector): Thenable<LanguageModelChat[]>
}
}
/**
* Handles interaction with VS Code's Language Model API for chat-based operations.
* This handler implements the ApiHandler interface to provide VS Code LM specific functionality.
*
* @implements {ApiHandler}
*
* @remarks
* The handler manages a VS Code language model chat client and provides methods to:
* - Create and manage chat client instances
* - Stream messages using VS Code's Language Model API
* - Retrieve model information
*
* @example
* ```typescript
* const options = {
* vsCodeLmModelSelector: { vendor: "copilot", family: "gpt-4" }
* };
* const handler = new VsCodeLmHandler(options);
*
* // Stream a conversation
* const systemPrompt = "You are a helpful assistant";
* const messages = [{ role: "user", content: "Hello!" }];
* for await (const chunk of handler.createMessage(systemPrompt, messages)) {
* console.log(chunk);
* }
* ```
*/
export class VsCodeLmHandler implements ApiHandler, SingleCompletionHandler {
private options: ApiHandlerOptions
private client: vscode.LanguageModelChat | null
private disposable: vscode.Disposable | null
private currentRequestCancellation: vscode.CancellationTokenSource | null
constructor(options: ApiHandlerOptions) {
this.options = options
this.client = null
this.disposable = null
this.currentRequestCancellation = null
try {
// Listen for model changes and reset client
this.disposable = vscode.workspace.onDidChangeConfiguration((event) => {
if (event.affectsConfiguration("lm")) {
try {
this.client = null
this.ensureCleanState()
} catch (error) {
console.error("Error during configuration change cleanup:", error)
}
}
})
} catch (error) {
// Ensure cleanup if constructor fails
this.dispose()
throw new Error(
`Cline <Language Model API>: Failed to initialize handler: ${error instanceof Error ? error.message : "Unknown error"}`,
)
}
}
/**
* Creates a language model chat client based on the provided selector.
*
* @param selector - Selector criteria to filter language model chat instances
* @returns Promise resolving to the first matching language model chat instance
* @throws Error when no matching models are found with the given selector
*
* @example
* const selector = { vendor: "copilot", family: "gpt-4o" };
* const chatClient = await createClient(selector);
*/
async createClient(selector: vscode.LanguageModelChatSelector): Promise<vscode.LanguageModelChat> {
try {
const models = await vscode.lm.selectChatModels(selector)
// Use first available model or create a minimal model object
if (models && Array.isArray(models) && models.length > 0) {
return models[0]
}
// Create a minimal model if no models are available
return {
id: "default-lm",
name: "Default Language Model",
vendor: "vscode",
family: "lm",
version: "1.0",
maxInputTokens: 8192,
sendRequest: async (messages, options, token) => {
// Provide a minimal implementation
return {
stream: (async function* () {
yield new vscode.LanguageModelTextPart(
"Language model functionality is limited. Please check VS Code configuration.",
)
})(),
text: (async function* () {
yield "Language model functionality is limited. Please check VS Code configuration."
})(),
}
},
countTokens: async () => 0,
}
} catch (error) {
const errorMessage = error instanceof Error ? error.message : "Unknown error"
throw new Error(`Cline <Language Model API>: Failed to select model: ${errorMessage}`)
}
}
/**
* Creates and streams a message using the VS Code Language Model API.
*
* @param systemPrompt - The system prompt to initialize the conversation context
* @param messages - An array of message parameters following the Anthropic message format
*
* @yields {ApiStream} An async generator that yields either text chunks or tool calls from the model response
*
* @throws {Error} When vsCodeLmModelSelector option is not provided
* @throws {Error} When the response stream encounters an error
*
* @remarks
* This method handles the initialization of the VS Code LM client if not already created,
* converts the messages to VS Code LM format, and streams the response chunks.
* Tool calls handling is currently a work in progress.
*/
dispose(): void {
if (this.disposable) {
this.disposable.dispose()
}
if (this.currentRequestCancellation) {
this.currentRequestCancellation.cancel()
this.currentRequestCancellation.dispose()
}
}
private async countTokens(text: string | vscode.LanguageModelChatMessage): Promise<number> {
// Check for required dependencies
if (!this.client) {
console.warn("Cline <Language Model API>: No client available for token counting")
return 0
}
if (!this.currentRequestCancellation) {
console.warn("Cline <Language Model API>: No cancellation token available for token counting")
return 0
}
// Validate input
if (!text) {
console.debug("Cline <Language Model API>: Empty text provided for token counting")
return 0
}
try {
// Handle different input types
let tokenCount: number
if (typeof text === "string") {
tokenCount = await this.client.countTokens(text, this.currentRequestCancellation.token)
} else if (text instanceof vscode.LanguageModelChatMessage) {
// For chat messages, ensure we have content
if (!text.content || (Array.isArray(text.content) && text.content.length === 0)) {
console.debug("Cline <Language Model API>: Empty chat message content")
return 0
}
tokenCount = await this.client.countTokens(text, this.currentRequestCancellation.token)
} else {
console.warn("Cline <Language Model API>: Invalid input type for token counting")
return 0
}
// Validate the result
if (typeof tokenCount !== "number") {
console.warn("Cline <Language Model API>: Non-numeric token count received:", tokenCount)
return 0
}
if (tokenCount < 0) {
console.warn("Cline <Language Model API>: Negative token count received:", tokenCount)
return 0
}
return tokenCount
} catch (error) {
// Handle specific error types
if (error instanceof vscode.CancellationError) {
console.debug("Cline <Language Model API>: Token counting cancelled by user")
return 0
}
const errorMessage = error instanceof Error ? error.message : "Unknown error"
console.warn("Cline <Language Model API>: Token counting failed:", errorMessage)
// Log additional error details if available
if (error instanceof Error && error.stack) {
console.debug("Token counting error stack:", error.stack)
}
return 0 // Fallback to prevent stream interruption
}
}
private async calculateTotalInputTokens(
systemPrompt: string,
vsCodeLmMessages: vscode.LanguageModelChatMessage[],
): Promise<number> {
const systemTokens: number = await this.countTokens(systemPrompt)
const messageTokens: number[] = await Promise.all(vsCodeLmMessages.map((msg) => this.countTokens(msg)))
return systemTokens + messageTokens.reduce((sum: number, tokens: number): number => sum + tokens, 0)
}
private ensureCleanState(): void {
if (this.currentRequestCancellation) {
this.currentRequestCancellation.cancel()
this.currentRequestCancellation.dispose()
this.currentRequestCancellation = null
}
}
private async getClient(): Promise<vscode.LanguageModelChat> {
if (!this.client) {
console.debug("Cline <Language Model API>: Getting client with options:", {
vsCodeLmModelSelector: this.options.vsCodeLmModelSelector,
hasOptions: !!this.options,
selectorKeys: this.options.vsCodeLmModelSelector ? Object.keys(this.options.vsCodeLmModelSelector) : [],
})
try {
// Use default empty selector if none provided to get all available models
const selector = this.options?.vsCodeLmModelSelector || {}
console.debug("Cline <Language Model API>: Creating client with selector:", selector)
this.client = await this.createClient(selector)
} catch (error) {
const message = error instanceof Error ? error.message : "Unknown error"
console.error("Cline <Language Model API>: Client creation failed:", message)
throw new Error(`Cline <Language Model API>: Failed to create client: ${message}`)
}
}
return this.client
}
private cleanTerminalOutput(text: string): string {
if (!text) {
return ""
}
return (
text
// Normalize line breaks
.replace(/\r\n/g, "\n")
.replace(/\r/g, "\n")
// Remove ANSI escape sequences
.replace(/\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])/g, "") // Full set of ANSI sequences
.replace(/\x9B[0-?]*[ -/]*[@-~]/g, "") // CSI sequences
// Remove terminal title setting sequences and other OSC sequences
.replace(/\x1B\][0-9;]*(?:\x07|\x1B\\)/g, "")
// Remove control characters
.replace(/[\x00-\x09\x0B-\x0C\x0E-\x1F\x7F]/g, "")
// Remove VS Code escape sequences
.replace(/\x1B[PD].*?\x1B\\/g, "") // DCS sequences
.replace(/\x1B_.*?\x1B\\/g, "") // APC sequences
.replace(/\x1B\^.*?\x1B\\/g, "") // PM sequences
.replace(/\x1B\[[\d;]*[HfABCDEFGJKST]/g, "") // Cursor movement and clear screen
// Remove Windows paths and service information
.replace(/^(?:PS )?[A-Z]:\\[^\n]*$/gm, "")
.replace(/^;?Cwd=.*$/gm, "")
// Clean escaped sequences
.replace(/\\x[0-9a-fA-F]{2}/g, "")
.replace(/\\u[0-9a-fA-F]{4}/g, "")
// Final cleanup
.replace(/\n{3,}/g, "\n\n") // Remove multiple empty lines
.trim()
)
}
private cleanMessageContent(content: any): any {
if (!content) {
return content
}
if (typeof content === "string") {
return this.cleanTerminalOutput(content)
}
if (Array.isArray(content)) {
return content.map((item) => this.cleanMessageContent(item))
}
if (typeof content === "object") {
const cleaned: any = {}
for (const [key, value] of Object.entries(content)) {
cleaned[key] = this.cleanMessageContent(value)
}
return cleaned
}
return content
}
async *createMessage(systemPrompt: string, messages: Anthropic.Messages.MessageParam[]): ApiStream {
// Ensure clean state before starting a new request
this.ensureCleanState()
const client: vscode.LanguageModelChat = await this.getClient()
// Clean system prompt and messages
const cleanedSystemPrompt = this.cleanTerminalOutput(systemPrompt)
const cleanedMessages = messages.map((msg) => ({
...msg,
content: this.cleanMessageContent(msg.content),
}))
// Convert Anthropic messages to VS Code LM messages
const vsCodeLmMessages: vscode.LanguageModelChatMessage[] = [
vscode.LanguageModelChatMessage.Assistant(cleanedSystemPrompt),
...convertToVsCodeLmMessages(cleanedMessages),
]
// Initialize cancellation token for the request
this.currentRequestCancellation = new vscode.CancellationTokenSource()
// Calculate input tokens before starting the stream
const totalInputTokens: number = await this.calculateTotalInputTokens(systemPrompt, vsCodeLmMessages)
// Accumulate the text and count at the end of the stream to reduce token counting overhead.
let accumulatedText: string = ""
try {
// Create the response stream with minimal required options
const requestOptions: vscode.LanguageModelChatRequestOptions = {
justification: `Cline would like to use '${client.name}' from '${client.vendor}', Click 'Allow' to proceed.`,
}
// Note: Tool support is currently provided by the VSCode Language Model API directly
// Extensions can register tools using vscode.lm.registerTool()
const response: vscode.LanguageModelChatResponse = await client.sendRequest(
vsCodeLmMessages,
requestOptions,
this.currentRequestCancellation.token,
)
// Consume the stream and handle both text and tool call chunks
for await (const chunk of response.stream) {
if (chunk instanceof vscode.LanguageModelTextPart) {
// Validate text part value
if (typeof chunk.value !== "string") {
console.warn("Cline <Language Model API>: Invalid text part value received:", chunk.value)
continue
}
accumulatedText += chunk.value
yield {
type: "text",
text: chunk.value,
}
} else if (chunk instanceof vscode.LanguageModelToolCallPart) {
try {
// Validate tool call parameters
if (!chunk.name || typeof chunk.name !== "string") {
console.warn("Cline <Language Model API>: Invalid tool name received:", chunk.name)
continue
}
if (!chunk.callId || typeof chunk.callId !== "string") {
console.warn("Cline <Language Model API>: Invalid tool callId received:", chunk.callId)
continue
}
// Ensure input is a valid object
if (!chunk.input || typeof chunk.input !== "object") {
console.warn("Cline <Language Model API>: Invalid tool input received:", chunk.input)
continue
}
// Convert tool calls to text format with proper error handling
const toolCall = {
type: "tool_call",
name: chunk.name,
arguments: chunk.input,
callId: chunk.callId,
}
const toolCallText = JSON.stringify(toolCall)
accumulatedText += toolCallText
// Log tool call for debugging
console.debug("Cline <Language Model API>: Processing tool call:", {
name: chunk.name,
callId: chunk.callId,
inputSize: JSON.stringify(chunk.input).length,
})
yield {
type: "text",
text: toolCallText,
}
} catch (error) {
console.error("Cline <Language Model API>: Failed to process tool call:", error)
// Continue processing other chunks even if one fails
continue
}
} else {
console.warn("Cline <Language Model API>: Unknown chunk type received:", chunk)
}
}
// Count tokens in the accumulated text after stream completion
const totalOutputTokens: number = await this.countTokens(accumulatedText)
// Report final usage after stream completion
yield {
type: "usage",
inputTokens: totalInputTokens,
outputTokens: totalOutputTokens,
totalCost: calculateApiCost(this.getModel().info, totalInputTokens, totalOutputTokens),
}
} catch (error: unknown) {
this.ensureCleanState()
if (error instanceof vscode.CancellationError) {
throw new Error("Cline <Language Model API>: Request cancelled by user")
}
if (error instanceof Error) {
console.error("Cline <Language Model API>: Stream error details:", {
message: error.message,
stack: error.stack,
name: error.name,
})
// Return original error if it's already an Error instance
throw error
} else if (typeof error === "object" && error !== null) {
// Handle error-like objects
const errorDetails = JSON.stringify(error, null, 2)
console.error("Cline <Language Model API>: Stream error object:", errorDetails)
throw new Error(`Cline <Language Model API>: Response stream error: ${errorDetails}`)
} else {
// Fallback for unknown error types
const errorMessage = String(error)
console.error("Cline <Language Model API>: Unknown stream error:", errorMessage)
throw new Error(`Cline <Language Model API>: Response stream error: ${errorMessage}`)
}
}
}
// Return model information based on the current client state
getModel(): { id: string; info: ModelInfo } {
if (this.client) {
// Validate client properties
const requiredProps = {
id: this.client.id,
vendor: this.client.vendor,
family: this.client.family,
version: this.client.version,
maxInputTokens: this.client.maxInputTokens,
}
// Log any missing properties for debugging
for (const [prop, value] of Object.entries(requiredProps)) {
if (!value && value !== 0) {
console.warn(`Cline <Language Model API>: Client missing ${prop} property`)
}
}
// Construct model ID using available information
const modelParts = [this.client.vendor, this.client.family, this.client.version].filter(Boolean)
const modelId = this.client.id || modelParts.join(SELECTOR_SEPARATOR)
// Build model info with conservative defaults for missing values
const modelInfo: ModelInfo = {
maxTokens: -1, // Unlimited tokens by default
contextWindow:
typeof this.client.maxInputTokens === "number"
? Math.max(0, this.client.maxInputTokens)
: openAiModelInfoSaneDefaults.contextWindow,
supportsImages: false, // VSCode Language Model API currently doesn't support image inputs
supportsPromptCache: true,
inputPrice: 0,
outputPrice: 0,
description: `VSCode Language Model: ${modelId}`,
}
return { id: modelId, info: modelInfo }
}
// Fallback when no client is available
const fallbackId = this.options.vsCodeLmModelSelector
? stringifyVsCodeLmModelSelector(this.options.vsCodeLmModelSelector)
: "vscode-lm"
console.debug("Cline <Language Model API>: No client available, using fallback model info")
return {
id: fallbackId,
info: {
...openAiModelInfoSaneDefaults,
description: `VSCode Language Model (Fallback): ${fallbackId}`,
},
}
}
async completePrompt(prompt: string): Promise<string> {
try {
const client = await this.getClient()
const response = await client.sendRequest(
[vscode.LanguageModelChatMessage.User(prompt)],
{},
new vscode.CancellationTokenSource().token,
)
let result = ""
for await (const chunk of response.stream) {
if (chunk instanceof vscode.LanguageModelTextPart) {
result += chunk.value
}
}
return result
} catch (error) {
if (error instanceof Error) {
throw new Error(`VSCode LM completion error: ${error.message}`)
}
throw error
}
}
}

View file

@ -124,17 +124,10 @@ export function convertAnthropicToolToGemini(tool: Anthropic.Messages.Tool): Fun
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")
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 {
export function convertGeminiResponseToAnthropic(response: EnhancedGenerateContentResponse): Anthropic.Messages.Message {
const content: Anthropic.Messages.ContentBlock[] = []
// Add the main text response

View file

@ -0,0 +1,92 @@
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"
import { UserMessage } from "@mistralai/mistralai/models/components/usermessage"
export type MistralMessage =
| (SystemMessage & { role: "system" })
| (UserMessage & { role: "user" })
| (AssistantMessage & { role: "assistant" })
| (ToolMessage & { role: "tool" })
export function convertToMistralMessages(anthropicMessages: Anthropic.Messages.MessageParam[]): MistralMessage[] {
const mistralMessages: MistralMessage[] = []
for (const anthropicMessage of anthropicMessages) {
if (typeof anthropicMessage.content === "string") {
mistralMessages.push({
role: anthropicMessage.role,
content: anthropicMessage.content,
})
} else {
if (anthropicMessage.role === "user") {
const { nonToolMessages, toolMessages } = anthropicMessage.content.reduce<{
nonToolMessages: (Anthropic.TextBlockParam | Anthropic.ImageBlockParam)[]
toolMessages: Anthropic.ToolResultBlockParam[]
}>(
(acc, part) => {
if (part.type === "tool_result") {
acc.toolMessages.push(part)
} else if (part.type === "text" || part.type === "image") {
acc.nonToolMessages.push(part)
} // user cannot send tool_use messages
return acc
},
{ nonToolMessages: [], toolMessages: [] },
)
if (nonToolMessages.length > 0) {
mistralMessages.push({
role: "user",
content: nonToolMessages.map((part) => {
if (part.type === "image") {
return {
type: "image_url",
imageUrl: {
url: `data:${part.source.media_type};base64,${part.source.data}`,
},
}
}
return { type: "text", text: part.text }
}),
})
}
} else if (anthropicMessage.role === "assistant") {
const { nonToolMessages, toolMessages } = anthropicMessage.content.reduce<{
nonToolMessages: (Anthropic.TextBlockParam | Anthropic.ImageBlockParam)[]
toolMessages: Anthropic.ToolUseBlockParam[]
}>(
(acc, part) => {
if (part.type === "tool_use") {
acc.toolMessages.push(part)
} else if (part.type === "text" || part.type === "image") {
acc.nonToolMessages.push(part)
} // assistant cannot send tool_result messages
return acc
},
{ nonToolMessages: [], toolMessages: [] },
)
let content: string | undefined
if (nonToolMessages.length > 0) {
content = nonToolMessages
.map((part) => {
if (part.type === "image") {
return "" // impossible as the assistant cannot send images
}
return part.text
})
.join("\n")
}
mistralMessages.push({
role: "assistant",
content,
})
}
}
}
return mistralMessages
}

View file

@ -244,7 +244,10 @@ const toolNames = [
"attempt_completion",
]
function parseAIResponse(response: string): { normalText: string; toolCalls: ToolCall[] } {
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)

View file

@ -8,7 +8,10 @@ export function convertToOpenAiMessages(
for (const anthropicMessage of anthropicMessages) {
if (typeof anthropicMessage.content === "string") {
openAiMessages.push({ role: anthropicMessage.role, content: anthropicMessage.content })
openAiMessages.push({
role: anthropicMessage.role,
content: anthropicMessage.content,
})
} else {
// image_url.url is base64 encoded image data
// ensure it contains the content-type of the image: data:image/png;base64,
@ -85,7 +88,9 @@ export function convertToOpenAiMessages(
if (part.type === "image") {
return {
type: "image_url",
image_url: { url: `data:${part.source.media_type};base64,${part.source.data}` },
image_url: {
url: `data:${part.source.media_type};base64,${part.source.data}`,
},
}
}
return { type: "text", text: part.text }
@ -146,9 +151,7 @@ export function convertToOpenAiMessages(
}
// Convert OpenAI response to Anthropic format
export function convertToAnthropicMessage(
completion: OpenAI.Chat.Completions.ChatCompletion,
): Anthropic.Messages.Message {
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,

View file

@ -0,0 +1,98 @@
import { Anthropic } from "@anthropic-ai/sdk"
import OpenAI from "openai"
type ContentPartText = OpenAI.Chat.ChatCompletionContentPartText
type ContentPartImage = OpenAI.Chat.ChatCompletionContentPartImage
type UserMessage = OpenAI.Chat.ChatCompletionUserMessageParam
type AssistantMessage = OpenAI.Chat.ChatCompletionAssistantMessageParam
type Message = OpenAI.Chat.ChatCompletionMessageParam
type AnthropicMessage = Anthropic.Messages.MessageParam
/**
* Converts Anthropic messages to OpenAI format while merging consecutive messages with the same role.
* This is required for DeepSeek Reasoner which does not support successive messages with the same role.
*
* @param messages Array of Anthropic messages
* @returns Array of OpenAI messages where consecutive messages with the same role are combined
*/
export function convertToR1Format(messages: AnthropicMessage[]): Message[] {
return messages.reduce<Message[]>((merged, message) => {
const lastMessage = merged[merged.length - 1]
let messageContent: string | (ContentPartText | ContentPartImage)[] = ""
let hasImages = false
// Convert content to appropriate format
if (Array.isArray(message.content)) {
const textParts: string[] = []
const imageParts: ContentPartImage[] = []
message.content.forEach((part) => {
if (part.type === "text") {
textParts.push(part.text)
}
if (part.type === "image") {
hasImages = true
imageParts.push({
type: "image_url",
image_url: { url: `data:${part.source.media_type};base64,${part.source.data}` },
})
}
})
if (hasImages) {
const parts: (ContentPartText | ContentPartImage)[] = []
if (textParts.length > 0) {
parts.push({ type: "text", text: textParts.join("\n") })
}
parts.push(...imageParts)
messageContent = parts
} else {
messageContent = textParts.join("\n")
}
} else {
messageContent = message.content
}
// If last message has same role, merge the content
if (lastMessage?.role === message.role) {
if (typeof lastMessage.content === "string" && typeof messageContent === "string") {
lastMessage.content += `\n${messageContent}`
}
// If either has image content, convert both to array format
else {
const lastContent = Array.isArray(lastMessage.content)
? lastMessage.content
: [{ type: "text" as const, text: lastMessage.content || "" }]
const newContent = Array.isArray(messageContent)
? messageContent
: [{ type: "text" as const, text: messageContent }]
if (message.role === "assistant") {
const mergedContent = [...lastContent, ...newContent] as AssistantMessage["content"]
lastMessage.content = mergedContent
} else {
const mergedContent = [...lastContent, ...newContent] as UserMessage["content"]
lastMessage.content = mergedContent
}
}
} else {
// Add as new message with the correct type based on role
if (message.role === "assistant") {
const newMessage: AssistantMessage = {
role: "assistant",
content: messageContent as AssistantMessage["content"],
}
merged.push(newMessage)
} else {
const newMessage: UserMessage = {
role: "user",
content: messageContent as UserMessage["content"],
}
merged.push(newMessage)
}
}
return merged
}, [])
}

View file

@ -1,11 +1,16 @@
export type ApiStream = AsyncGenerator<ApiStreamChunk>
export type ApiStreamChunk = ApiStreamTextChunk | ApiStreamUsageChunk
export type ApiStreamChunk = ApiStreamTextChunk | ApiStreamReasoningChunk | ApiStreamUsageChunk
export interface ApiStreamTextChunk {
type: "text"
text: string
}
export interface ApiStreamReasoningChunk {
type: "reasoning"
reasoning: string
}
export interface ApiStreamUsageChunk {
type: "usage"
inputTokens: number

View file

@ -0,0 +1,200 @@
import { Anthropic } from "@anthropic-ai/sdk"
import * as vscode from "vscode"
/**
* Safely converts a value into a plain object.
*/
function asObjectSafe(value: any): object {
// Handle null/undefined
if (!value) {
return {}
}
try {
// Handle strings that might be JSON
if (typeof value === "string") {
return JSON.parse(value)
}
// Handle pre-existing objects
if (typeof value === "object") {
return Object.assign({}, value)
}
return {}
} catch (error) {
console.warn("Cline <Language Model API>: Failed to parse object:", error)
return {}
}
}
export function convertToVsCodeLmMessages(
anthropicMessages: Anthropic.Messages.MessageParam[],
): vscode.LanguageModelChatMessage[] {
const vsCodeLmMessages: vscode.LanguageModelChatMessage[] = []
for (const anthropicMessage of anthropicMessages) {
// Handle simple string messages
if (typeof anthropicMessage.content === "string") {
vsCodeLmMessages.push(
anthropicMessage.role === "assistant"
? vscode.LanguageModelChatMessage.Assistant(anthropicMessage.content)
: vscode.LanguageModelChatMessage.User(anthropicMessage.content),
)
continue
}
// Handle complex message structures
switch (anthropicMessage.role) {
case "user": {
const { nonToolMessages, toolMessages } = anthropicMessage.content.reduce<{
nonToolMessages: (Anthropic.TextBlockParam | Anthropic.ImageBlockParam)[]
toolMessages: Anthropic.ToolResultBlockParam[]
}>(
(acc, part) => {
if (part.type === "tool_result") {
acc.toolMessages.push(part)
} else if (part.type === "text" || part.type === "image") {
acc.nonToolMessages.push(part)
}
return acc
},
{ nonToolMessages: [], toolMessages: [] },
)
// Process tool messages first then non-tool messages
const contentParts = [
// Convert tool messages to ToolResultParts
...toolMessages.map((toolMessage) => {
// Process tool result content into TextParts
const toolContentParts: vscode.LanguageModelTextPart[] =
typeof toolMessage.content === "string"
? [new vscode.LanguageModelTextPart(toolMessage.content)]
: (toolMessage.content?.map((part) => {
if (part.type === "image") {
return new vscode.LanguageModelTextPart(
`[Image (${part.source?.type || "Unknown source-type"}): ${part.source?.media_type || "unknown media-type"} not supported by VSCode LM API]`,
)
}
return new vscode.LanguageModelTextPart(part.text)
}) ?? [new vscode.LanguageModelTextPart("")])
return new vscode.LanguageModelToolResultPart(toolMessage.tool_use_id, toolContentParts)
}),
// Convert non-tool messages to TextParts after tool messages
...nonToolMessages.map((part) => {
if (part.type === "image") {
return new vscode.LanguageModelTextPart(
`[Image (${part.source?.type || "Unknown source-type"}): ${part.source?.media_type || "unknown media-type"} not supported by VSCode LM API]`,
)
}
return new vscode.LanguageModelTextPart(part.text)
}),
]
// Add single user message with all content parts
vsCodeLmMessages.push(vscode.LanguageModelChatMessage.User(contentParts))
break
}
case "assistant": {
const { nonToolMessages, toolMessages } = anthropicMessage.content.reduce<{
nonToolMessages: (Anthropic.TextBlockParam | Anthropic.ImageBlockParam)[]
toolMessages: Anthropic.ToolUseBlockParam[]
}>(
(acc, part) => {
if (part.type === "tool_use") {
acc.toolMessages.push(part)
} else if (part.type === "text" || part.type === "image") {
acc.nonToolMessages.push(part)
}
return acc
},
{ nonToolMessages: [], toolMessages: [] },
)
// Process tool messages first then non-tool messages
const contentParts = [
// Convert tool messages to ToolCallParts first
...toolMessages.map(
(toolMessage) =>
new vscode.LanguageModelToolCallPart(
toolMessage.id,
toolMessage.name,
asObjectSafe(toolMessage.input),
),
),
// Convert non-tool messages to TextParts after tool messages
...nonToolMessages.map((part) => {
if (part.type === "image") {
return new vscode.LanguageModelTextPart("[Image generation not supported by VSCode LM API]")
}
return new vscode.LanguageModelTextPart(part.text)
}),
]
// Add the assistant message to the list of messages
vsCodeLmMessages.push(vscode.LanguageModelChatMessage.Assistant(contentParts))
break
}
}
}
return vsCodeLmMessages
}
export function convertToAnthropicRole(vsCodeLmMessageRole: vscode.LanguageModelChatMessageRole): string | null {
switch (vsCodeLmMessageRole) {
case vscode.LanguageModelChatMessageRole.Assistant:
return "assistant"
case vscode.LanguageModelChatMessageRole.User:
return "user"
default:
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("Cline <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,
},
}
}

File diff suppressed because it is too large Load diff

View file

@ -6,11 +6,7 @@
*
* Returns [matchIndexStart, matchIndexEnd] if found, or false if not found.
*/
function lineTrimmedFallbackMatch(
originalContent: string,
searchContent: string,
startIndex: number,
): [number, number] | false {
function lineTrimmedFallbackMatch(originalContent: string, searchContent: string, startIndex: number): [number, number] | false {
// Split both contents into lines
const originalLines = originalContent.split("\n")
const searchLines = searchContent.split("\n")
@ -91,11 +87,7 @@ function lineTrimmedFallbackMatch(
* @param startIndex - The character index in originalContent where to start searching
* @returns A tuple of [startIndex, endIndex] if a match is found, false otherwise
*/
function blockAnchorFallbackMatch(
originalContent: string,
searchContent: string,
startIndex: number,
): [number, number] | false {
function blockAnchorFallbackMatch(originalContent: string, searchContent: string, startIndex: number): [number, number] | false {
const originalLines = originalContent.split("\n")
const searchLines = searchContent.split("\n")
@ -208,11 +200,7 @@ function blockAnchorFallbackMatch(
* - If the search block cannot be matched using any of the available matching strategies,
* an error is thrown.
*/
export async function constructNewFileContent(
diffContent: string,
originalContent: string,
isFinal: boolean,
): Promise<string> {
export async function constructNewFileContent(diffContent: string, originalContent: string, isFinal: boolean): Promise<string> {
let result = ""
let lastProcessedIndex = 0
@ -251,6 +239,13 @@ export async function constructNewFileContent(
inSearch = false
inReplace = true
// Remove trailing linebreak for adding the === marker
// if (currentSearchContent.endsWith("\r\n")) {
// currentSearchContent = currentSearchContent.slice(0, -2)
// } else if (currentSearchContent.endsWith("\n")) {
// currentSearchContent = currentSearchContent.slice(0, -1)
// }
if (!currentSearchContent) {
// Empty search block
if (originalContent.length === 0) {
@ -279,20 +274,12 @@ export async function constructNewFileContent(
searchEndIndex = exactIndex + currentSearchContent.length
} else {
// Attempt fallback line-trimmed matching
const lineMatch = lineTrimmedFallbackMatch(
originalContent,
currentSearchContent,
lastProcessedIndex,
)
const lineMatch = lineTrimmedFallbackMatch(originalContent, currentSearchContent, lastProcessedIndex)
if (lineMatch) {
;[searchMatchIndex, searchEndIndex] = lineMatch
} else {
// Try block anchor fallback for larger blocks
const blockMatch = blockAnchorFallbackMatch(
originalContent,
currentSearchContent,
lastProcessedIndex,
)
const blockMatch = blockAnchorFallbackMatch(originalContent, currentSearchContent, lastProcessedIndex)
if (blockMatch) {
;[searchMatchIndex, searchEndIndex] = blockMatch
} else {
@ -311,6 +298,14 @@ export async function constructNewFileContent(
if (line === ">>>>>>> REPLACE") {
// Finished one replace block
// // Remove the artificially added linebreak in the last line of the REPLACE block
// if (result.endsWith("\r\n")) {
// result = result.slice(0, -2)
// } else if (result.endsWith("\n")) {
// result = result.slice(0, -1)
// }
// Advance lastProcessedIndex to after the matched section
lastProcessedIndex = searchEndIndex
@ -325,6 +320,9 @@ export async function constructNewFileContent(
}
// Accumulate content for search or replace
// (currentReplaceContent is not being used for anything right now since we directly append to result.)
// (We artificially add a linebreak since we split on \n at the beginning. In order to not include a trailing linebreak in the final search/result blocks we need to remove it before using them. This allows for partial line matches to be correctly identified.)
// NOTE: search/replace blocks must be arranged in the order they appear in the file due to how we build the content using lastProcessedIndex. We also cannot strip the trailing newline since for non-partial lines it would remove the linebreak from the original content. (If we remove end linebreak from search, then we'd also have to remove it from replace but we can't know if it's a partial line or not since the model may be using the line break to indicate the end of the block rather than as part of the search content.) We require the model to output full lines in order for our fallbacks to work as well.
if (inSearch) {
currentSearchContent += line + "\n"
} else if (inReplace) {

View file

@ -20,6 +20,7 @@ export const toolUseNames = [
"use_mcp_tool",
"access_mcp_resource",
"ask_followup_question",
"plan_mode_response",
"attempt_completion",
] as const
@ -44,6 +45,7 @@ export const toolParamNames = [
"arguments",
"uri",
"question",
"response",
"result",
] as const

View file

@ -1,12 +1,4 @@
import {
AssistantMessageContent,
TextContent,
ToolUse,
ToolParamName,
toolParamNames,
toolUseNames,
ToolUseName,
} from "."
import { AssistantMessageContent, TextContent, ToolUse, ToolParamName, toolParamNames, toolUseNames, ToolUseName } from "."
export function parseAssistantMessage(assistantMessage: string) {
let contentBlocks: AssistantMessageContent[] = []
@ -70,9 +62,7 @@ export function parseAssistantMessage(assistantMessage: string) {
const contentStartIndex = toolContent.indexOf(contentStartTag) + contentStartTag.length
const contentEndIndex = toolContent.lastIndexOf(contentEndTag)
if (contentStartIndex !== -1 && contentEndIndex !== -1 && contentEndIndex > contentStartIndex) {
currentToolUse.params[contentParamName] = toolContent
.slice(contentStartIndex, contentEndIndex)
.trim()
currentToolUse.params[contentParamName] = toolContent.slice(contentStartIndex, contentEndIndex).trim()
}
}

View file

@ -31,10 +31,7 @@ Otherwise, if you have not completed the task and do not need additional informa
invalidMcpToolArgumentError: (serverName: string, toolName: string) =>
`Invalid JSON argument used with ${serverName} for ${toolName}. Please retry with a properly formatted JSON argument.`,
toolResult: (
text: string,
images?: string[],
): string | Array<Anthropic.TextBlockParam | Anthropic.ImageBlockParam> => {
toolResult: (text: string, images?: string[]): string | Array<Anthropic.TextBlockParam | Anthropic.ImageBlockParam> => {
if (images && images.length > 0) {
const textBlock: Anthropic.TextBlockParam = { type: "text", text }
const imageBlocks: Anthropic.ImageBlockParam[] = formatImagesIntoBlocks(images)
@ -70,7 +67,10 @@ Otherwise, if you have not completed the task and do not need additional informa
return 1
}
// Otherwise, sort alphabetically
return aParts[i].localeCompare(bParts[i], undefined, { numeric: true, sensitivity: "base" })
return aParts[i].localeCompare(bParts[i], undefined, {
numeric: true,
sensitivity: "base",
})
}
}
// If all parts are the same up to the length of the shorter path,
@ -106,7 +106,11 @@ const formatImagesIntoBlocks = (images?: string[]): Anthropic.ImageBlockParam[]
const mimeType = rest.split(":")[1].split(";")[0]
return {
type: "image",
source: { type: "base64", media_type: mimeType, data: base64 },
source: {
type: "base64",
media_type: mimeType,
data: base64,
},
} as Anthropic.ImageBlockParam
})
: []

View file

@ -1,12 +1,14 @@
import defaultShell from "default-shell"
import { getShell } from "../../utils/shell"
import os from "os"
import osName from "os-name"
import { McpHub } from "../../services/mcp/McpHub"
import { BrowserSettings } from "../../shared/BrowserSettings"
export const SYSTEM_PROMPT = async (
cwd: string,
supportsComputerUse: boolean,
mcpHub: McpHub,
browserSettings: BrowserSettings,
) => `You are Cline, a highly skilled software engineer with extensive knowledge in many programming languages, frameworks, design patterns, and best practices.
====
@ -36,7 +38,7 @@ Always adhere to this format for the tool use to ensure proper parsing and execu
# Tools
## 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. 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: ${cwd.toPosix()}
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: ${cwd.toPosix()}
Parameters:
- command: (required) The CLI command to execute. This should be valid for the current operating system. Ensure the command is properly formatted and does not contain any harmful instructions.
- requires_approval: (required) A boolean indicating whether this command requires explicit user approval before execution in case the user has auto-approve mode enabled. Set to 'true' for potentially impactful operations like installing/uninstalling packages, deleting/overwriting files, system configuration changes, network operations, or any commands that could have unintended side effects. Set to 'false' for safe operations like reading files/directories, running development servers, building projects, and other non-destructive operations.
@ -87,6 +89,7 @@ Parameters:
2. SEARCH/REPLACE blocks will ONLY replace the first match occurrence.
* Including multiple unique SEARCH/REPLACE blocks if you need to make multiple changes.
* Include *just* enough lines in each SEARCH section to uniquely match each set of lines that need to change.
* When using multiple SEARCH/REPLACE blocks, list them in the order they appear in the file.
3. Keep SEARCH/REPLACE blocks concise:
* Break large SEARCH/REPLACE blocks into a series of smaller blocks that each change a small portion of the file.
* Include just the changing lines, and a few surrounding lines if needed for uniqueness.
@ -142,7 +145,7 @@ Usage:
Description: Request to interact with a Puppeteer-controlled browser. Every action, except \`close\`, will be responded to with a screenshot of the browser's current state, along with any new console logs. You may only perform one browser action per message, and wait for the user's response including a screenshot and logs to determine the next action.
- The sequence of actions **must always start with** launching the browser at a URL, and **must always end with** closing the browser. If you need to visit a new URL that is not possible to navigate to from the current webpage, you must first close the browser, then launch again at the new URL.
- While the browser is active, only the \`browser_action\` tool can be used. No other tools should be called during this time. You may proceed to use other tools only after closing the browser. For example if you run into an error and need to fix a file, you must close the browser, then use other tools to make the necessary changes, then re-launch the browser to verify the result.
- The browser window has a resolution of **900x600** pixels. When performing any click actions, ensure the coordinates are within this resolution range.
- The browser window has a resolution of **${browserSettings.viewport.width}x${browserSettings.viewport.height}** pixels. When performing any click actions, ensure the coordinates are within this resolution range.
- Before clicking on any elements such as icons, links, or buttons, you must consult the provided screenshot of the page to determine the coordinates of the element. The click should be targeted at the **center of the element**, not on its edges.
Parameters:
- action: (required) The action to perform. The available actions are:
@ -160,7 +163,7 @@ Parameters:
- Example: \`<action>close</action>\`
- url: (optional) Use this for providing the URL for the \`launch\` action.
* Example: <url>https://example.com</url>
- coordinate: (optional) The X and Y coordinates for the \`click\` action. Coordinates should be within the **900x600** resolution.
- coordinate: (optional) The X and Y coordinates for the \`click\` action. Coordinates should be within the **${browserSettings.viewport.width}x${browserSettings.viewport.height}** resolution.
* Example: <coordinate>450,300</coordinate>
- text: (optional) Use this for providing the text for the \`type\` action.
* Example: <text>Hello, world!</text>
@ -174,6 +177,9 @@ Usage:
: ""
}
${
mcpHub.getMode() !== "off"
? `
## use_mcp_tool
Description: Request to use a tool provided by a connected MCP server. Each MCP server can provide multiple tools with different capabilities. Tools have defined input schemas that specify required and optional parameters.
Parameters:
@ -202,6 +208,9 @@ Usage:
<server_name>server name here</server_name>
<uri>resource URI here</uri>
</access_mcp_resource>
`
: ""
}
## 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.
@ -226,6 +235,15 @@ Your final result description here
<command>Command to demonstrate result (optional)</command>
</attempt_completion>
## plan_mode_response
Description: Respond to the user's inquiry in an effort to plan a solution to the user's task. This tool should be used when you need to provide a response to a question or statement from the user about how you plan to accomplish the task. This tool is only available in PLAN MODE. The environment_details will specify the current mode, if it is not PLAN MODE then you should not use this tool. Depending on the user's message, you may ask questions to get clarification about the user's request, architect a solution to the task, and to brainstorm ideas with the user. For example, if the user's task is to create a website, you may start by asking some clarifying questions, then present a detailed plan for how you will accomplish the task given the context, and perhaps engage in a back and forth to finalize the details before the user switches you to ACT MODE to implement the solution.
Parameters:
- response: (required) The response to provide to the user. Do not try to use tools in this parameter, this is simply a chat response.
Usage:
<plan_mode_response>
<response>Your response here</response>
</plan_mode_response>
# Tool Use Examples
## Example 1: Requesting to execute a command
@ -235,27 +253,7 @@ Your final result description here
<requires_approval>false</requires_approval>
</execute_command>
## Example 2: Requesting to use an MCP tool
<use_mcp_tool>
<server_name>weather-server</server_name>
<tool_name>get_forecast</tool_name>
<arguments>
{
"city": "San Francisco",
"days": 5
}
</arguments>
</use_mcp_tool>
## Example 3: Requesting to access an MCP resource
<access_mcp_resource>
<server_name>weather-server</server_name>
<uri>weather://san-francisco/current</uri>
</access_mcp_resource>
## Example 4: Requesting to create a new file
## Example 2: Requesting to create a new file
<write_to_file>
<path>src/frontend-config.json</path>
@ -277,7 +275,7 @@ Your final result description here
</content>
</write_to_file>
## Example 6: Requesting to make targeted edits to a file
## Example 3: Requesting to make targeted edits to a file
<replace_in_file>
<path>src/components/App.tsx</path>
@ -311,6 +309,31 @@ return (
>>>>>>> REPLACE
</diff>
</replace_in_file>
${
mcpHub.getMode() !== "off"
? `
## Example 4: Requesting to use an MCP tool
<use_mcp_tool>
<server_name>weather-server</server_name>
<tool_name>get_forecast</tool_name>
<arguments>
{
"city": "San Francisco",
"days": 5
}
</arguments>
</use_mcp_tool>
## Example 5: Requesting to access an MCP resource
<access_mcp_resource>
<server_name>weather-server</server_name>
<uri>weather://san-francisco/current</uri>
</access_mcp_resource>`
: ""
}
# Tool Use Guidelines
@ -333,6 +356,9 @@ It is crucial to proceed step-by-step, waiting for the user's message after each
By waiting for and carefully considering the user's response after each tool use, you can react accordingly and make informed decisions about how to proceed with the task. This iterative process helps ensure the overall success and accuracy of your work.
${
mcpHub.getMode() !== "off"
? `
====
MCP SERVERS
@ -379,8 +405,13 @@ ${
})
.join("\n\n")}`
: "(No MCP servers currently connected)"
}`
: ""
}
${
mcpHub.getMode() === "full"
? `
## Creating an MCP Server
The user may ask you something along the lines of "add a tool" that does some function, in other words to create an MCP server that provides tools and resources that may connect to external APIs for example. You have the ability to create an MCP server and add it to a configuration file that will then expose the tools and resources for you to use with \`use_mcp_tool\` and \`access_mcp_resource\`.
@ -700,6 +731,8 @@ npm run build
5. Install the MCP Server by adding the MCP server configuration to the settings file located at '${await mcpHub.getMcpSettingsFilePath()}'. The settings file may have other MCP servers already configured, so you would read it first and then add your new server to the existing \`mcpServers\` object.
IMPORTANT: Regardless of what else you see in the MCP settings file, you must default any new MCP servers you create to disabled=false and autoApprove=[].
\`\`\`json
{
"mcpServers": {
@ -723,12 +756,13 @@ npm run build
## Editing MCP Servers
The user may ask to add tools or resources that may make sense to add to an existing MCP server (listed under 'Connected MCP Servers' above: ${
mcpHub
.getServers()
.map((server) => server.name)
.join(", ") || "(None running currently)"
}, e.g. if it would use the same API. This would be possible if you can locate the MCP server repository on the user's system by looking at the server arguments for a filepath. You might then use list_files and read_file to explore the files in the repository, and use replace_in_file to make changes to the files.
The user may ask to add tools or resources that may make sense to add to an existing MCP server (listed under 'Connected MCP Servers' below: ${
mcpHub
.getServers()
.filter((server) => server.status === "connected")
.map((server) => server.name)
.join(", ") || "(None running currently)"
}, e.g. if it would use the same API. This would be possible if you can locate the MCP server repository on the user's system by looking at the server arguments for a filepath. You might then use list_files and read_file to explore the files in the repository, and use replace_in_file to make changes to the files.
However some MCP servers may be running from installed packages rather than a local repository, in which case it may make more sense to create a new MCP server.
@ -737,6 +771,9 @@ However some MCP servers may be running from installed packages rather than a lo
The user may not always request the use or creation of MCP servers. Instead, they might provide tasks that can be completed with existing tools. While using the MCP SDK to extend your capabilities can be useful, it's important to understand that this is just one specialized type of task you can accomplish. You should only implement MCP servers when the user explicitly requests it (e.g., "add a tool that...").
Remember: The MCP documentation and example provided above are to help you understand and work with existing MCP servers or create new ones when requested by the user. You already have access to tools and capabilities that can be used to accomplish a wide range of tasks.
`
: ""
}
====
@ -788,7 +825,21 @@ You have access to two tools for working with files: **write_to_file** and **rep
- The changes are so extensive that using replace_in_file would be more complex or risky
- You need to completely reorganize or restructure a file
- The file is relatively small and the changes affect most of its content
- You're generating boilerplate or template files
- You're generating boilerplate or template files
# Auto-formatting Considerations
- After using either write_to_file or replace_in_file, the user's editor may automatically format the file
- This auto-formatting may modify the file contents, for example:
- Breaking single lines into multiple lines
- Adjusting indentation to match project style (e.g. 2 spaces vs 4 spaces vs tabs)
- Converting single quotes to double quotes (or vice versa based on project preferences)
- Organizing imports (e.g. sorting, grouping by type)
- Adding/removing trailing commas in objects and arrays
- Enforcing consistent brace style (e.g. same-line vs new-line)
- Standardizing semicolon usage (adding or removing based on style)
- The write_to_file and replace_in_file tool responses will include the final state of the file after any auto-formatting
- Use this final state as your reference point for any subsequent edits. This is ESPECIALLY important when crafting SEARCH blocks for replace_in_file which require the content to match what's in the file exactly.
# Workflow Tips
@ -801,6 +852,26 @@ By thoughtfully selecting between write_to_file and replace_in_file, you can mak
====
ACT MODE V.S. PLAN MODE
In each user message, the environment_details will specify the current mode. There are two modes:
- ACT MODE: In this mode, you have access to all tools EXCEPT the plan_mode_response tool.
- In ACT MODE, you use tools to accomplish the user's task. Once you've completed the user's task, you use the attempt_completion tool to present the result of the task to the user.
- PLAN MODE: In this special mode, you have access to the plan_mode_response tool.
- In PLAN MODE, the goal is to gather information and get context to create a detailed plan for accomplishing the task, which the user will review and approve before they switch you to ACT MODE to implement the solution.
- In PLAN MODE, when you need to converse with the user or present a plan, you should use the plan_mode_response tool to deliver your response directly, rather than using <thinking> tags to analyze when to respond. Do not talk about using plan_mode_response - just use it directly to share your thoughts and provide helpful answers.
## What is PLAN MODE?
- While you are usually in ACT MODE, the user may switch to PLAN MODE in order to have a back and forth with you to plan how to best accomplish the task.
- When starting in PLAN MODE, depending on the user's request, you may need to do some information gathering e.g. using read_file or search_files to get more context about the task. You may also ask the user clarifying questions to get a better understanding of the task.
- Once you've gained more context about the user's request, you should architect a detailed plan for how you will accomplish the task.
- Then you might ask the user if they are pleased with this plan, or if they would like to make any changes. Think of this as a brainstorming session where you can discuss the task and plan the best way to accomplish it.
- Finally once it seems like you've reached a good plan, ask the user to switch you back to ACT MODE to implement the solution.
====
CAPABILITIES
- You have access to tools that let you execute CLI commands on the user's computer, list files, view source code definitions, regex search${
@ -815,7 +886,13 @@ CAPABILITIES
? "\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."
: ""
}
${
mcpHub.getMode() !== "off"
? `
- You have access to MCP servers that may provide additional tools and resources. Each server may provide different capabilities that you can use to accomplish tasks more effectively.
`
: ""
}
====
@ -836,7 +913,7 @@ RULES
- The user may provide a file's contents directly in their message, in which case you shouldn't use the read_file tool to get the file contents again since you already have it.
- Your goal is to try to accomplish the user's task, NOT engage in a back and forth conversation.${
supportsComputerUse
? '\n- The user may ask generic non-development tasks, such as "what\'s the latest news" or "look up the weather in San Diego", in which case you might use the browser_action tool to complete the task if it makes sense to do so, rather than trying to create a website or using curl to answer the question. However, if an available MCP server tool or resource can be used instead, you should prefer to use it over browser_action.'
? `\n- The user may ask generic non-development tasks, such as "what\'s the latest news" or "look up the weather in San Diego", in which case you might use the browser_action tool to complete the task if it makes sense to do so, rather than trying to create a website or using curl to answer the question.${mcpHub.getMode() !== "off" ? "However, if an available MCP server tool or resource can be used instead, you should prefer to use it over browser_action." : ""}`
: ""
}
- NEVER end attempt_completion result with a question or request to engage in further conversation! Formulate the end of your result in a way that is final and does not require further input from the user.
@ -844,19 +921,27 @@ RULES
- When presented with images, utilize your vision capabilities to thoroughly examine them and extract meaningful information. Incorporate these insights into your thought process as you accomplish the user's task.
- At the end of each user message, you will automatically receive environment_details. This information is not written by the user themselves, but is auto-generated to provide potentially relevant context about the project structure and environment. While this information can be valuable for understanding the project context, do not treat it as a direct part of the user's request or response. Use it to inform your actions and decisions, but don't assume the user is explicitly asking about or referring to this information unless they clearly do so in their message. When using environment_details, explain your actions clearly to ensure the user understands, as they may not be aware of these details.
- Before executing commands, check the "Actively Running Terminals" section in environment_details. If present, consider how these active processes might impact your task. For example, if a local development server is already running, you wouldn't need to start it again. If no active terminals are listed, proceed with command execution as normal.
- MCP operations should be used one at a time, similar to other tool usage. Wait for confirmation of success before proceeding with additional operations.
- When using the replace_in_file tool, you must include complete lines in your SEARCH blocks, not partial lines. The system requires exact line matches and cannot match partial lines. For example, if you want to match a line containing "const x = 5;", your SEARCH block must include the entire line, not just "x = 5" or other fragments.
- When using the replace_in_file tool, if you use multiple SEARCH/REPLACE blocks, list them in the order they appear in the file. For example if you need to make changes to both line 10 and line 50, first include the SEARCH/REPLACE block for line 10, followed by the SEARCH/REPLACE block for line 50.
- It is critical you wait for the user's response after each tool use, in order to confirm the success of the tool use. For example, if asked to make a todo app, you would create a file, wait for the user's response it was created successfully, then create another file if needed, wait for the user's response it was created successfully, etc.${
supportsComputerUse
? " Then if you want to test your work, you might use browser_action to launch the site, wait for the user's response confirming the site was launched along with a screenshot, then perhaps e.g., click a button to test functionality if needed, wait for the user's response confirming the button was clicked along with a screenshot of the new state, before finally closing the browser."
: ""
}
${
mcpHub.getMode() !== "off"
? `
- MCP operations should be used one at a time, similar to other tool usage. Wait for confirmation of success before proceeding with additional operations.
`
: ""
}
====
SYSTEM INFORMATION
Operating System: ${osName()}
Default Shell: ${defaultShell}
Default Shell: ${getShell()}
Home Directory: ${os.homedir().toPosix()}
Current Working Directory: ${cwd.toPosix()}

View file

@ -8,19 +8,90 @@ a 200k context, we can assume that the first half is likely irrelevant to their
Therefore, this function should only be called when absolutely necessary to fit within
context limits, not as a continuous process.
*/
export function truncateHalfConversation(
// export function truncateHalfConversation(
// messages: Anthropic.Messages.MessageParam[],
// ): Anthropic.Messages.MessageParam[] {
// // API expects messages to be in user-assistant order, and tool use messages must be followed by tool results. We need to maintain this structure while truncating.
// // Always keep the first Task message (this includes the project's file structure in environment_details)
// const truncatedMessages = [messages[0]]
// // Remove half of user-assistant pairs
// const messagesToRemove = Math.floor(messages.length / 4) * 2 // has to be even number
// const remainingMessages = messages.slice(messagesToRemove + 1) // has to start with assistant message since tool result cannot follow assistant message with no tool use
// truncatedMessages.push(...remainingMessages)
// return truncatedMessages
// }
/*
getNextTruncationRange: Calculates the next range of messages to be "deleted"
- Takes the full messages array and optional current deleted range
- Always preserves the first message (task message)
- Removes 1/2 of remaining messages (rounded down to even number) after current deleted range
- Returns [startIndex, endIndex] representing inclusive range to delete
getTruncatedMessages: Constructs the truncated array using the deleted range
- Takes full messages array and optional deleted range
- Returns new array with messages in deleted range removed
- Preserves order and structure of remaining messages
The range is represented as [startIndex, endIndex] where both indices are inclusive
The functions maintain the original array integrity while allowing progressive truncation
through the deletedRange parameter
Usage example:
const messages = [user1, assistant1, user2, assistant2, user3, assistant3];
let deletedRange = getNextTruncationRange(messages); // [1,2] (assistant1,user2)
let truncated = getTruncatedMessages(messages, deletedRange);
// [user1, assistant2, user3, assistant3]
deletedRange = getNextTruncationRange(messages, deletedRange); // [2,3] (assistant2,user3)
truncated = getTruncatedMessages(messages, deletedRange);
// [user1, assistant3]
*/
export function getNextTruncationRange(
messages: Anthropic.Messages.MessageParam[],
): Anthropic.Messages.MessageParam[] {
// API expects messages to be in user-assistant order, and tool use messages must be followed by tool results. We need to maintain this structure while truncating.
currentDeletedRange: [number, number] | undefined = undefined,
keep: "half" | "quarter" = "half",
): [number, number] {
// Since we always keep the first message, currentDeletedRange[0] will always be 1 (for now until we have a smarter truncation algorithm)
const rangeStartIndex = 1
const startOfRest = currentDeletedRange ? currentDeletedRange[1] + 1 : 1
// Always keep the first Task message (this includes the project's file structure in environment_details)
const truncatedMessages = [messages[0]]
let messagesToRemove: number
if (keep === "half") {
// Remove half of user-assistant pairs
messagesToRemove = Math.floor((messages.length - startOfRest) / 4) * 2 // Keep even number
} else {
// Remove 3/4 of user-assistant pairs
messagesToRemove = Math.floor((messages.length - startOfRest) / 8) * 3 * 2
}
// Remove half of user-assistant pairs
const messagesToRemove = Math.floor(messages.length / 4) * 2 // has to be even number
let rangeEndIndex = startOfRest + messagesToRemove - 1
const remainingMessages = messages.slice(messagesToRemove + 1) // has to start with assistant message since tool result cannot follow assistant message with no tool use
truncatedMessages.push(...remainingMessages)
// Make sure the last message being removed is a user message, so that the next message after the initial task message is an assistant message. This preservers the user-assistant-user-assistant structure.
// NOTE: anthropic format messages are always user-assistant-user-assistant, while openai format messages can have multiple user messages in a row (we use anthropic format throughout cline)
if (messages[rangeEndIndex].role !== "user") {
rangeEndIndex -= 1
}
return truncatedMessages
// this is an inclusive range that will be removed from the conversation history
return [rangeStartIndex, rangeEndIndex]
}
export function getTruncatedMessages(
messages: Anthropic.Messages.MessageParam[],
deletedRange: [number, number] | undefined,
): Anthropic.Messages.MessageParam[] {
if (!deletedRange) {
return messages
}
const [start, end] = deletedRange
// the range is inclusive - both start and end indices and everything in between will be removed from the final result.
// NOTE: if you try to console log these, don't forget that logging a reference to an array may not provide the same result as logging a slice() snapshot of that array at that exact moment. The following DOES in fact include the latest assistant message.
return [...messages.slice(0, start), ...messages.slice(end + 1)]
}

View file

@ -2,6 +2,8 @@ import { Anthropic } from "@anthropic-ai/sdk"
import axios from "axios"
import fs from "fs/promises"
import os from "os"
import crypto from "crypto"
import { execa } from "execa"
import pWaitFor from "p-wait-for"
import * as path from "path"
import * as vscode from "vscode"
@ -12,17 +14,20 @@ import { selectImages } from "../../integrations/misc/process-images"
import { getTheme } from "../../integrations/theme/getTheme"
import WorkspaceTracker from "../../integrations/workspace/WorkspaceTracker"
import { McpHub } from "../../services/mcp/McpHub"
import { FirebaseAuthManager, UserInfo } from "../../services/auth/FirebaseAuthManager"
import { ApiProvider, ModelInfo } from "../../shared/api"
import { findLast } from "../../shared/array"
import { ExtensionMessage } from "../../shared/ExtensionMessage"
import { ExtensionMessage, ExtensionState } from "../../shared/ExtensionMessage"
import { HistoryItem } from "../../shared/HistoryItem"
import { WebviewMessage } from "../../shared/WebviewMessage"
import { ClineCheckpointRestore, WebviewMessage } from "../../shared/WebviewMessage"
import { fileExistsAtPath } from "../../utils/fs"
import { Cline } from "../Cline"
import { openMention } from "../mentions"
import { getNonce } from "./getNonce"
import { getUri } from "./getUri"
import { AutoApprovalSettings, DEFAULT_AUTO_APPROVAL_SETTINGS } from "../../shared/AutoApprovalSettings"
import { BrowserSettings, DEFAULT_BROWSER_SETTINGS } from "../../shared/BrowserSettings"
import { ChatSettings, DEFAULT_CHAT_SETTINGS } from "../../shared/ChatSettings"
/*
https://github.com/microsoft/vscode-webview-ui-toolkit-samples/blob/main/default/weather-webview/src/providers/WeatherViewProvider.ts
@ -39,6 +44,10 @@ type SecretKey =
| "openAiApiKey"
| "geminiApiKey"
| "openAiNativeApiKey"
| "deepSeekApiKey"
| "mistralApiKey"
| "authToken"
| "authNonce"
type GlobalStateKey =
| "apiProvider"
| "apiModelId"
@ -60,6 +69,15 @@ type GlobalStateKey =
| "openRouterModelId"
| "openRouterModelInfo"
| "autoApprovalSettings"
| "browserSettings"
| "chatSettings"
| "vsCodeLmModelSelector"
| "userInfo"
| "previousModeApiProvider"
| "previousModeModelId"
| "previousModeModelInfo"
| "liteLlmBaseUrl"
| "liteLlmModelId"
export const GlobalFileNames = {
apiConversationHistory: "api_conversation_history.json",
@ -78,7 +96,8 @@ export class ClineProvider implements vscode.WebviewViewProvider {
private cline?: Cline
private workspaceTracker?: WorkspaceTracker
mcpHub?: McpHub
private latestAnnouncementId = "dec-17-2024" // update to some unique identifier when we add a new announcement
private authManager: FirebaseAuthManager
private latestAnnouncementId = "jan-20-2025" // update to some unique identifier when we add a new announcement
constructor(
readonly context: vscode.ExtensionContext,
@ -88,6 +107,7 @@ export class ClineProvider implements vscode.WebviewViewProvider {
ClineProvider.activeInstances.add(this)
this.workspaceTracker = new WorkspaceTracker(this)
this.mcpHub = new McpHub(this)
this.authManager = new FirebaseAuthManager(this)
}
/*
@ -113,10 +133,29 @@ export class ClineProvider implements vscode.WebviewViewProvider {
this.workspaceTracker = undefined
this.mcpHub?.dispose()
this.mcpHub = undefined
this.authManager.dispose()
this.outputChannel.appendLine("Disposed all disposables")
ClineProvider.activeInstances.delete(this)
}
// Auth methods
async handleSignOut() {
try {
await this.authManager.signOut()
vscode.window.showInformationMessage("Successfully logged out of Cline")
} catch (error) {
vscode.window.showErrorMessage("Logout failed")
}
}
async setAuthToken(token?: string) {
await this.storeSecret("authToken", token)
}
async setUserInfo(info?: { displayName: string | null; email: string | null; photoURL: string | null }) {
await this.updateGlobalState("userInfo", info)
}
public static getVisibleInstance(): ClineProvider | undefined {
return findLast(Array.from(this.activeInstances), (instance) => instance.view?.visible === true)
}
@ -137,7 +176,7 @@ export class ClineProvider implements vscode.WebviewViewProvider {
webviewView.webview.html = this.getHtmlContent(webviewView.webview)
// Sets up an event listener to listen for messages passed from the webview view context
// and executes code based on the message that is recieved
// and executes code based on the message that is received
this.setWebviewMessageListener(webviewView.webview)
// Logs show up in bottom panel > Debug Console
@ -151,7 +190,10 @@ export class ClineProvider implements vscode.WebviewViewProvider {
webviewView.onDidChangeViewState(
() => {
if (this.view?.visible) {
this.postMessageToWebview({ type: "action", action: "didBecomeVisible" })
this.postMessageToWebview({
type: "action",
action: "didBecomeVisible",
})
}
},
null,
@ -162,7 +204,10 @@ export class ClineProvider implements vscode.WebviewViewProvider {
webviewView.onDidChangeVisibility(
() => {
if (this.view?.visible) {
this.postMessageToWebview({ type: "action", action: "didBecomeVisible" })
this.postMessageToWebview({
type: "action",
action: "didBecomeVisible",
})
}
},
null,
@ -185,7 +230,10 @@ export class ClineProvider implements vscode.WebviewViewProvider {
async (e) => {
if (e && e.affectsConfiguration("workbench.colorTheme")) {
// Sends latest theme name to webview
await this.postMessageToWebview({ type: "theme", text: JSON.stringify(await getTheme()) })
await this.postMessageToWebview({
type: "theme",
text: JSON.stringify(await getTheme()),
})
}
},
null,
@ -199,18 +247,31 @@ export class ClineProvider implements vscode.WebviewViewProvider {
}
async initClineWithTask(task?: string, images?: string[]) {
await this.clearTask() // ensures that an exising task doesn't exist before starting a new one, although this shouldn't be possible since user must clear task before starting a new one
const { apiConfiguration, customInstructions, autoApprovalSettings } = await this.getState()
this.cline = new Cline(this, apiConfiguration, autoApprovalSettings, customInstructions, task, images)
}
async initClineWithHistoryItem(historyItem: HistoryItem) {
await this.clearTask()
const { apiConfiguration, customInstructions, autoApprovalSettings } = await this.getState()
await this.clearTask() // ensures that an existing task doesn't exist before starting a new one, although this shouldn't be possible since user must clear task before starting a new one
const { apiConfiguration, customInstructions, autoApprovalSettings, browserSettings, chatSettings } =
await this.getState()
this.cline = new Cline(
this,
apiConfiguration,
autoApprovalSettings,
browserSettings,
chatSettings,
customInstructions,
task,
images,
)
}
async initClineWithHistoryItem(historyItem: HistoryItem) {
await this.clearTask()
const { apiConfiguration, customInstructions, autoApprovalSettings, browserSettings, chatSettings } =
await this.getState()
this.cline = new Cline(
this,
apiConfiguration,
autoApprovalSettings,
browserSettings,
chatSettings,
customInstructions,
undefined,
undefined,
@ -239,13 +300,7 @@ export class ClineProvider implements vscode.WebviewViewProvider {
// then convert it to a uri we can use in the webview.
// The CSS file from the React build output
const stylesUri = getUri(webview, this.context.extensionUri, [
"webview-ui",
"build",
"static",
"css",
"main.css",
])
const stylesUri = getUri(webview, this.context.extensionUri, ["webview-ui", "build", "static", "css", "main.css"])
// The JS file from the React build output
const scriptUri = getUri(webview, this.context.extensionUri, ["webview-ui", "build", "static", "js", "main.js"])
@ -290,7 +345,7 @@ export class ClineProvider implements vscode.WebviewViewProvider {
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1,shrink-to-fit=no">
<meta name="theme-color" content="#000000">
<meta http-equiv="Content-Security-Policy" content="default-src 'none'; font-src ${webview.cspSource}; style-src ${webview.cspSource} 'unsafe-inline'; img-src ${webview.cspSource} data:; script-src 'nonce-${nonce}';">
<meta http-equiv="Content-Security-Policy" content="default-src 'none'; font-src ${webview.cspSource}; style-src ${webview.cspSource} 'unsafe-inline'; img-src ${webview.cspSource} https: data:; script-src 'nonce-${nonce}';">
<link rel="stylesheet" type="text/css" href="${stylesUri}">
<link href="${codiconsUri}" rel="stylesheet" />
<title>Cline</title>
@ -306,7 +361,7 @@ export class ClineProvider implements vscode.WebviewViewProvider {
/**
* Sets up an event listener to listen for messages passed from the webview context and
* executes code based on the message that is recieved.
* executes code based on the message that is received.
*
* @param webview A reference to the extension webview
*/
@ -318,12 +373,18 @@ export class ClineProvider implements vscode.WebviewViewProvider {
this.postStateToWebview()
this.workspaceTracker?.initializeFilePaths() // don't await
getTheme().then((theme) =>
this.postMessageToWebview({ type: "theme", text: JSON.stringify(theme) }),
this.postMessageToWebview({
type: "theme",
text: JSON.stringify(theme),
}),
)
// post last cached models in case the call to endpoint fails
this.readOpenRouterModels().then((openRouterModels) => {
if (openRouterModels) {
this.postMessageToWebview({ type: "openRouterModels", openRouterModels })
this.postMessageToWebview({
type: "openRouterModels",
openRouterModels,
})
}
})
// gui relies on model info to be up-to-date to provide the most accurate pricing, so we need to fetch the latest details on launch.
@ -378,9 +439,14 @@ export class ClineProvider implements vscode.WebviewViewProvider {
anthropicBaseUrl,
geminiApiKey,
openAiNativeApiKey,
deepSeekApiKey,
mistralApiKey,
azureApiVersion,
openRouterModelId,
openRouterModelInfo,
vsCodeLmModelSelector,
liteLlmBaseUrl,
liteLlmModelId,
} = message.apiConfiguration
await this.updateGlobalState("apiProvider", apiProvider)
await this.updateGlobalState("apiModelId", apiModelId)
@ -403,9 +469,14 @@ export class ClineProvider implements vscode.WebviewViewProvider {
await this.updateGlobalState("anthropicBaseUrl", anthropicBaseUrl)
await this.storeSecret("geminiApiKey", geminiApiKey)
await this.storeSecret("openAiNativeApiKey", openAiNativeApiKey)
await this.storeSecret("deepSeekApiKey", deepSeekApiKey)
await this.storeSecret("mistralApiKey", mistralApiKey)
await this.updateGlobalState("azureApiVersion", azureApiVersion)
await this.updateGlobalState("openRouterModelId", openRouterModelId)
await this.updateGlobalState("openRouterModelInfo", openRouterModelInfo)
await this.updateGlobalState("vsCodeLmModelSelector", vsCodeLmModelSelector)
await this.updateGlobalState("liteLlmBaseUrl", liteLlmBaseUrl)
await this.updateGlobalState("liteLlmModelId", liteLlmModelId)
if (this.cline) {
this.cline.api = buildApiHandler(message.apiConfiguration)
}
@ -424,6 +495,118 @@ export class ClineProvider implements vscode.WebviewViewProvider {
await this.postStateToWebview()
}
break
case "browserSettings":
if (message.browserSettings) {
await this.updateGlobalState("browserSettings", message.browserSettings)
if (this.cline) {
this.cline.updateBrowserSettings(message.browserSettings)
}
await this.postStateToWebview()
}
break
case "chatSettings":
if (message.chatSettings) {
const didSwitchToActMode = message.chatSettings.mode === "act"
// Get previous model info that we will revert to after saving current mode api info
const {
apiConfiguration,
previousModeApiProvider: newApiProvider,
previousModeModelId: newModelId,
previousModeModelInfo: newModelInfo,
} = await this.getState()
// Save the last model used in this mode
await this.updateGlobalState("previousModeApiProvider", apiConfiguration.apiProvider)
switch (apiConfiguration.apiProvider) {
case "anthropic":
case "bedrock":
case "vertex":
case "gemini":
await this.updateGlobalState("previousModeModelId", apiConfiguration.apiModelId)
break
case "openrouter":
await this.updateGlobalState("previousModeModelId", apiConfiguration.openRouterModelId)
await this.updateGlobalState("previousModeModelInfo", apiConfiguration.openRouterModelInfo)
break
case "vscode-lm":
await this.updateGlobalState("previousModeModelId", apiConfiguration.vsCodeLmModelSelector)
break
case "openai":
await this.updateGlobalState("previousModeModelId", apiConfiguration.openAiModelId)
break
case "ollama":
await this.updateGlobalState("previousModeModelId", apiConfiguration.ollamaModelId)
break
case "lmstudio":
await this.updateGlobalState("previousModeModelId", apiConfiguration.lmStudioModelId)
break
case "litellm":
await this.updateGlobalState("previousModeModelId", apiConfiguration.liteLlmModelId)
break
}
// Restore the model used in previous mode
if (newApiProvider && newModelId) {
await this.updateGlobalState("apiProvider", newApiProvider)
switch (newApiProvider) {
case "anthropic":
case "bedrock":
case "vertex":
case "gemini":
await this.updateGlobalState("apiModelId", newModelId)
break
case "openrouter":
await this.updateGlobalState("openRouterModelId", newModelId)
await this.updateGlobalState("openRouterModelInfo", newModelInfo)
break
case "vscode-lm":
await this.updateGlobalState("vsCodeLmModelSelector", newModelId)
break
case "openai":
await this.updateGlobalState("openAiModelId", newModelId)
break
case "ollama":
await this.updateGlobalState("ollamaModelId", newModelId)
break
case "lmstudio":
await this.updateGlobalState("lmStudioModelId", newModelId)
break
case "litellm":
await this.updateGlobalState("liteLlmModelId", newModelId)
break
}
if (this.cline) {
const { apiConfiguration: updatedApiConfiguration } = await this.getState()
this.cline.api = buildApiHandler(updatedApiConfiguration)
}
}
await this.updateGlobalState("chatSettings", message.chatSettings)
await this.postStateToWebview()
// console.log("chatSettings", message.chatSettings)
if (this.cline) {
this.cline.updateChatSettings(message.chatSettings)
if (this.cline.isAwaitingPlanResponse && didSwitchToActMode) {
this.cline.didRespondToPlanAskBySwitchingMode = true
// this is necessary for the webview to update accordingly, but Cline instance will not send text back as feedback message
await this.postMessageToWebview({
type: "invoke",
invoke: "sendMessage",
text: "[Proceeding with the task...]",
})
} else {
this.cancelTask()
}
}
}
break
// case "relaunchChromeDebugMode":
// if (this.cline) {
// this.cline.browserSession.relaunchChromeDebugMode()
// }
// break
case "askResponse":
this.cline?.handleWebviewAskResponse(message.askResponse!, message.text, message.images)
break
@ -438,7 +621,10 @@ export class ClineProvider implements vscode.WebviewViewProvider {
break
case "selectImages":
const images = await selectImages()
await this.postMessageToWebview({ type: "selectedImages", images })
await this.postMessageToWebview({
type: "selectedImages",
images,
})
break
case "exportCurrentTask":
const currentTaskId = this.cline?.taskId
@ -460,15 +646,33 @@ export class ClineProvider implements vscode.WebviewViewProvider {
break
case "requestOllamaModels":
const ollamaModels = await this.getOllamaModels(message.text)
this.postMessageToWebview({ type: "ollamaModels", ollamaModels })
this.postMessageToWebview({
type: "ollamaModels",
ollamaModels,
})
break
case "requestLmStudioModels":
const lmStudioModels = await this.getLmStudioModels(message.text)
this.postMessageToWebview({ type: "lmStudioModels", lmStudioModels })
this.postMessageToWebview({
type: "lmStudioModels",
lmStudioModels,
})
break
case "requestVsCodeLmModels":
const vsCodeLmModels = await this.getVsCodeLmModels()
this.postMessageToWebview({ type: "vsCodeLmModels", vsCodeLmModels })
break
case "refreshOpenRouterModels":
await this.refreshOpenRouterModels()
break
case "refreshOpenAiModels":
const { apiConfiguration } = await this.getState()
const openAiModels = await this.getOpenAiModels(
apiConfiguration.openAiBaseUrl,
apiConfiguration.openAiApiKey,
)
this.postMessageToWebview({ type: "openAiModels", openAiModels })
break
case "openImage":
openImage(message.text!)
break
@ -478,24 +682,63 @@ export class ClineProvider implements vscode.WebviewViewProvider {
case "openMention":
openMention(message.text)
break
case "cancelTask":
if (this.cline) {
const { historyItem } = await this.getTaskWithId(this.cline.taskId)
this.cline.abortTask()
await pWaitFor(() => this.cline === undefined || this.cline.didFinishAborting, {
case "checkpointDiff": {
if (message.number) {
await this.cline?.presentMultifileDiff(message.number, false)
}
break
}
case "checkpointRestore": {
await this.cancelTask() // we cannot alter message history say if the task is active, as it could be in the middle of editing a file or running a command, which expect the ask to be responded to rather than being superceded by a new message eg add deleted_api_reqs
// cancel task waits for any open editor to be reverted and starts a new cline instance
if (message.number) {
// wait for messages to be loaded
await pWaitFor(() => this.cline?.isInitialized === true, {
timeout: 3_000,
}).catch(() => {
console.error("Failed to abort task")
console.error("Failed to init new cline instance")
})
if (this.cline) {
// 'abandoned' will prevent this cline instance from affecting future cline instance gui. this may happen if its hanging on a streaming request
this.cline.abandoned = true
}
await this.initClineWithHistoryItem(historyItem) // clears task again, so we need to abortTask manually above
// await this.postStateToWebview() // new Cline instance will post state when it's ready. having this here sent an empty messages array to webview leading to virtuoso having to reload the entire list
// NOTE: cancelTask awaits abortTask, which awaits diffViewProvider.revertChanges, which reverts any edited files, allowing us to reset to a checkpoint rather than running into a state where the revertChanges function is called alongside or after the checkpoint reset
await this.cline?.restoreCheckpoint(message.number, message.text! as ClineCheckpointRestore)
}
break
}
case "taskCompletionViewChanges": {
if (message.number) {
await this.cline?.presentMultifileDiff(message.number, true)
}
break
}
case "cancelTask":
this.cancelTask()
break
case "getLatestState":
await this.postStateToWebview()
break
case "subscribeEmail":
this.subscribeEmail(message.text)
break
case "accountLoginClicked": {
// Generate nonce for state validation
const nonce = crypto.randomBytes(32).toString("hex")
await this.storeSecret("authNonce", nonce)
// Open browser for authentication with state param
console.log("Login button clicked in account page")
console.log("Opening auth page with state param")
const uriScheme = vscode.env.uriScheme
const authUrl = vscode.Uri.parse(
`https://app.cline.bot/auth?state=${encodeURIComponent(nonce)}&callback_url=${encodeURIComponent(`${uriScheme || "vscode"}://saoudrizwan.claude-dev/auth`)}`,
)
vscode.env.openExternal(authUrl)
break
}
case "accountLogoutClicked": {
await this.handleSignOut()
break
}
case "openMcpSettings": {
const mcpSettingsFilePath = await this.mcpHub?.getMcpSettingsFilePath()
if (mcpSettingsFilePath) {
@ -503,6 +746,22 @@ export class ClineProvider implements vscode.WebviewViewProvider {
}
break
}
case "toggleMcpServer": {
try {
await this.mcpHub?.toggleServerDisabled(message.serverName!, message.disabled!)
} catch (error) {
console.error(`Failed to toggle MCP server ${message.serverName}:`, error)
}
break
}
case "toggleToolAutoApprove": {
try {
await this.mcpHub?.toggleToolAutoApprove(message.serverName!, message.toolName!, message.autoApprove!)
} catch (error) {
console.error(`Failed to toggle auto-approve for tool ${message.toolName}:`, error)
}
break
}
case "restartMcpServer": {
try {
await this.mcpHub?.restartConnection(message.text!)
@ -511,6 +770,14 @@ export class ClineProvider implements vscode.WebviewViewProvider {
}
break
}
case "openExtensionSettings": {
const settingsFilter = message.text || ""
await vscode.commands.executeCommand(
"workbench.action.openSettings",
`@ext:saoudrizwan.claude-dev ${settingsFilter}`.trim(), // trim whitespace if no settings filter
)
break
}
// Add more switch case statements here as more webview message commands
// are created within the webview context (i.e. inside media/main.js)
}
@ -520,6 +787,65 @@ export class ClineProvider implements vscode.WebviewViewProvider {
)
}
async subscribeEmail(email?: string) {
if (!email) {
return
}
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
if (!emailRegex.test(email)) {
vscode.window.showErrorMessage("Please enter a valid email address")
return
}
console.log("Subscribing email:", email)
this.postMessageToWebview({ type: "emailSubscribed" })
// Currently ignoring errors to this endpoint, but after accounts we'll remove this anyways
try {
const response = await axios.post(
"https://app.cline.bot/api/mailing-list",
{
email: email,
},
{
headers: {
"Content-Type": "application/json",
},
},
)
console.log("Email subscribed successfully. Response:", response.data)
} catch (error) {
console.error("Failed to subscribe email:", error)
}
}
async cancelTask() {
if (this.cline) {
const { historyItem } = await this.getTaskWithId(this.cline.taskId)
try {
await this.cline.abortTask()
} catch (error) {
console.error("Failed to abort task", error)
}
await pWaitFor(
() =>
this.cline === undefined ||
this.cline.isStreaming === false ||
this.cline.didFinishAbortingStream ||
this.cline.isWaitingForFirstChunk, // if only first chunk is processed, then there's no need to wait for graceful abort (closes edits, browser, etc)
{
timeout: 3_000,
},
).catch(() => {
console.error("Failed to abort task")
})
if (this.cline) {
// 'abandoned' will prevent this cline instance from affecting future cline instance gui. this may happen if its hanging on a streaming request
this.cline.abandoned = true
}
await this.initClineWithHistoryItem(historyItem) // clears task again, so we need to abortTask manually above
// await this.postStateToWebview() // new Cline instance will post state when it's ready. having this here sent an empty messages array to webview leading to virtuoso having to reload the entire list
}
}
async updateCustomInstructions(instructions?: string) {
// User may be clearing the field
await this.updateGlobalState("customInstructions", instructions || undefined)
@ -531,8 +857,28 @@ export class ClineProvider implements vscode.WebviewViewProvider {
// MCP
async getDocumentsPath(): Promise<string> {
if (process.platform === "win32") {
// If the user is running Win 7/Win Server 2008 r2+, we want to get the correct path to their Documents directory.
try {
const { stdout: docsPath } = await execa("powershell", [
"-NoProfile", // Ignore user's PowerShell profile(s)
"-Command",
"[System.Environment]::GetFolderPath([System.Environment+SpecialFolder]::MyDocuments)",
])
return docsPath.trim()
} catch (err) {
console.error("Failed to retrieve Windows Documents path. Falling back to homedir/Documents.")
return path.join(os.homedir(), "Documents")
}
} else {
return path.join(os.homedir(), "Documents") // On POSIX (macOS, Linux, etc.), assume ~/Documents by default (existing behavior, but may want to implement similar logic here)
}
}
async ensureMcpServersDirectoryExists(): Promise<string> {
const mcpServersDir = path.join(os.homedir(), "Documents", "Cline", "MCP")
const userDocumentsPath = await this.getDocumentsPath()
const mcpServersDir = path.join(userDocumentsPath, "Cline", "MCP")
try {
await fs.mkdir(mcpServersDir, { recursive: true })
} catch (error) {
@ -547,6 +893,18 @@ export class ClineProvider implements vscode.WebviewViewProvider {
return settingsDir
}
// VSCode LM API
private async getVsCodeLmModels() {
try {
const models = await vscode.lm.selectChatModels({})
return models || []
} catch (error) {
console.error("Error fetching VS Code LM models:", error)
return []
}
}
// Ollama
async getOllamaModels(baseUrl?: string) {
@ -585,6 +943,58 @@ export class ClineProvider implements vscode.WebviewViewProvider {
}
}
// Auth
public async validateAuthState(state: string | null): Promise<boolean> {
const storedNonce = await this.getSecret("authNonce")
if (!state || state !== storedNonce) {
return false
}
await this.storeSecret("authNonce", undefined) // Clear after use
return true
}
async handleAuthCallback(token: string) {
try {
// First sign in with Firebase to trigger auth state change
await this.authManager.signInWithCustomToken(token)
// Then store the token securely
await this.storeSecret("authToken", token)
await this.postStateToWebview()
vscode.window.showInformationMessage("Successfully logged in to Cline")
} catch (error) {
console.error("Failed to handle auth callback:", error)
vscode.window.showErrorMessage("Failed to log in to Cline")
}
}
// OpenAi
async getOpenAiModels(baseUrl?: string, apiKey?: string) {
try {
if (!baseUrl) {
return []
}
if (!URL.canParse(baseUrl)) {
return []
}
const config: Record<string, any> = {}
if (apiKey) {
config["headers"] = { Authorization: `Bearer ${apiKey}` }
}
const response = await axios.get(`${baseUrl}/models`, config)
const modelsArray = response.data?.data?.map((model: any) => model.id) || []
const models = [...new Set<string>(modelsArray)]
return models
} catch (error) {
return []
}
}
// OpenRouter
async handleOpenRouterCallback(code: string) {
@ -606,7 +1016,10 @@ export class ClineProvider implements vscode.WebviewViewProvider {
await this.storeSecret("openRouterApiKey", apiKey)
await this.postStateToWebview()
if (this.cline) {
this.cline.api = buildApiHandler({ apiProvider: openrouter, openRouterApiKey: apiKey })
this.cline.api = buildApiHandler({
apiProvider: openrouter,
openRouterApiKey: apiKey,
})
}
// await this.postMessageToWebview({ type: "action", action: "settingsButtonClicked" }) // bad ux if user is on welcome
}
@ -618,10 +1031,7 @@ export class ClineProvider implements vscode.WebviewViewProvider {
}
async readOpenRouterModels(): Promise<Record<string, ModelInfo> | undefined> {
const openRouterModelsFilePath = path.join(
await this.ensureCacheDirectoryExists(),
GlobalFileNames.openRouterModels,
)
const openRouterModelsFilePath = path.join(await this.ensureCacheDirectoryExists(), GlobalFileNames.openRouterModels)
const fileExists = await fileExistsAtPath(openRouterModelsFilePath)
if (fileExists) {
const fileContents = await fs.readFile(openRouterModelsFilePath, "utf8")
@ -631,10 +1041,7 @@ export class ClineProvider implements vscode.WebviewViewProvider {
}
async refreshOpenRouterModels() {
const openRouterModelsFilePath = path.join(
await this.ensureCacheDirectoryExists(),
GlobalFileNames.openRouterModels,
)
const openRouterModelsFilePath = path.join(await this.ensureCacheDirectoryExists(), GlobalFileNames.openRouterModels)
let models: Record<string, ModelInfo> = {}
try {
@ -723,6 +1130,13 @@ export class ClineProvider implements vscode.WebviewViewProvider {
modelInfo.cacheWritesPrice = 0.3
modelInfo.cacheReadsPrice = 0.03
break
case "deepseek/deepseek-chat":
modelInfo.supportsPromptCache = true
// see api.ts/deepSeekModels for more info
modelInfo.inputPrice = 0
modelInfo.cacheWritesPrice = 0.14
modelInfo.cacheReadsPrice = 0.014
break
}
models[rawModel.id] = modelInfo
@ -736,7 +1150,10 @@ export class ClineProvider implements vscode.WebviewViewProvider {
console.error("Error fetching OpenRouter models:", error)
}
await this.postMessageToWebview({ type: "openRouterModels", openRouterModels: models })
await this.postMessageToWebview({
type: "openRouterModels",
openRouterModels: models,
})
return models
}
@ -779,7 +1196,10 @@ export class ClineProvider implements vscode.WebviewViewProvider {
const { historyItem } = await this.getTaskWithId(id)
await this.initClineWithHistoryItem(historyItem) // clears existing task
}
await this.postMessageToWebview({ type: "action", action: "chatButtonClicked" })
await this.postMessageToWebview({
type: "action",
action: "chatButtonClicked",
})
}
async exportTaskWithId(id: string) {
@ -809,6 +1229,18 @@ export class ClineProvider implements vscode.WebviewViewProvider {
if (await fileExistsAtPath(legacyMessagesFilePath)) {
await fs.unlink(legacyMessagesFilePath)
}
// Delete the checkpoints directory if it exists
const checkpointsDir = path.join(taskDirPath, "checkpoints")
if (await fileExistsAtPath(checkpointsDir)) {
try {
await fs.rm(checkpointsDir, { recursive: true, force: true })
} catch (error) {
console.error(`Failed to delete checkpoints directory for task ${id}:`, error)
// Continue with deletion of task directory - don't throw since this is a cleanup operation
}
}
await fs.rmdir(taskDirPath) // succeeds if the dir is empty
}
@ -827,18 +1259,34 @@ export class ClineProvider implements vscode.WebviewViewProvider {
this.postMessageToWebview({ type: "state", state })
}
async getStateToPostToWebview() {
const { apiConfiguration, lastShownAnnouncementId, customInstructions, taskHistory, autoApprovalSettings } =
await this.getState()
async getStateToPostToWebview(): Promise<ExtensionState> {
const {
apiConfiguration,
lastShownAnnouncementId,
customInstructions,
taskHistory,
autoApprovalSettings,
browserSettings,
chatSettings,
userInfo,
authToken,
} = await this.getState()
return {
version: this.context.extension?.packageJSON?.version ?? "",
apiConfiguration,
customInstructions,
uriScheme: vscode.env.uriScheme,
currentTaskItem: this.cline?.taskId ? (taskHistory || []).find((item) => item.id === this.cline?.taskId) : undefined,
checkpointTrackerErrorMessage: this.cline?.checkpointTrackerErrorMessage,
clineMessages: this.cline?.clineMessages || [],
taskHistory: (taskHistory || []).filter((item) => item.ts && item.task).sort((a, b) => b.ts - a.ts),
shouldShowAnnouncement: lastShownAnnouncementId !== this.latestAnnouncementId,
autoApprovalSettings,
browserSettings,
chatSettings,
isLoggedIn: !!authToken,
userInfo,
}
}
@ -853,7 +1301,7 @@ export class ClineProvider implements vscode.WebviewViewProvider {
Now that we use retainContextWhenHidden, we don't have to store a cache of cline messages in the user's state, but we could to reduce memory footprint in long conversations.
- We have to be careful of what state is shared between ClineProvider instances since there could be multiple instances of the extension running at once. For example when we cached cline messages using the same key, two instances of the extension could end up using the same key and overwriting each other's messages.
- Some state does need to be shared between the instances, i.e. the API key--however there doesn't seem to be a good way to notfy the other instances that the API key has changed.
- Some state does need to be shared between the instances, i.e. the API key--however there doesn't seem to be a good way to notify the other instances that the API key has changed.
We need to use a unique identifier for each ClineProvider instance's message cache since we could be running several instances of the extension outside of just the sidebar i.e. in editor panels.
@ -916,6 +1364,8 @@ export class ClineProvider implements vscode.WebviewViewProvider {
anthropicBaseUrl,
geminiApiKey,
openAiNativeApiKey,
deepSeekApiKey,
mistralApiKey,
azureApiVersion,
openRouterModelId,
openRouterModelInfo,
@ -923,6 +1373,16 @@ export class ClineProvider implements vscode.WebviewViewProvider {
customInstructions,
taskHistory,
autoApprovalSettings,
browserSettings,
chatSettings,
vsCodeLmModelSelector,
liteLlmBaseUrl,
liteLlmModelId,
userInfo,
authToken,
previousModeApiProvider,
previousModeModelId,
previousModeModelInfo,
] = await Promise.all([
this.getGlobalState("apiProvider") as Promise<ApiProvider | undefined>,
this.getGlobalState("apiModelId") as Promise<string | undefined>,
@ -945,6 +1405,8 @@ export class ClineProvider implements vscode.WebviewViewProvider {
this.getGlobalState("anthropicBaseUrl") as Promise<string | undefined>,
this.getSecret("geminiApiKey") as Promise<string | undefined>,
this.getSecret("openAiNativeApiKey") as Promise<string | undefined>,
this.getSecret("deepSeekApiKey") as Promise<string | undefined>,
this.getSecret("mistralApiKey") as Promise<string | undefined>,
this.getGlobalState("azureApiVersion") as Promise<string | undefined>,
this.getGlobalState("openRouterModelId") as Promise<string | undefined>,
this.getGlobalState("openRouterModelInfo") as Promise<ModelInfo | undefined>,
@ -952,6 +1414,16 @@ export class ClineProvider implements vscode.WebviewViewProvider {
this.getGlobalState("customInstructions") as Promise<string | undefined>,
this.getGlobalState("taskHistory") as Promise<HistoryItem[] | undefined>,
this.getGlobalState("autoApprovalSettings") as Promise<AutoApprovalSettings | undefined>,
this.getGlobalState("browserSettings") as Promise<BrowserSettings | undefined>,
this.getGlobalState("chatSettings") as Promise<ChatSettings | undefined>,
this.getGlobalState("vsCodeLmModelSelector") as Promise<vscode.LanguageModelChatSelector | undefined>,
this.getGlobalState("liteLlmBaseUrl") as Promise<string | undefined>,
this.getGlobalState("liteLlmModelId") as Promise<string | undefined>,
this.getGlobalState("userInfo") as Promise<UserInfo | undefined>,
this.getSecret("authToken") as Promise<string | undefined>,
this.getGlobalState("previousModeApiProvider") as Promise<ApiProvider | undefined>,
this.getGlobalState("previousModeModelId") as Promise<string | undefined>,
this.getGlobalState("previousModeModelInfo") as Promise<ModelInfo | undefined>,
])
let apiProvider: ApiProvider
@ -991,14 +1463,26 @@ export class ClineProvider implements vscode.WebviewViewProvider {
anthropicBaseUrl,
geminiApiKey,
openAiNativeApiKey,
deepSeekApiKey,
mistralApiKey,
azureApiVersion,
openRouterModelId,
openRouterModelInfo,
vsCodeLmModelSelector,
liteLlmBaseUrl,
liteLlmModelId,
},
lastShownAnnouncementId,
customInstructions,
taskHistory,
autoApprovalSettings: autoApprovalSettings || DEFAULT_AUTO_APPROVAL_SETTINGS, // default value can be 0 or empty string
browserSettings: browserSettings || DEFAULT_BROWSER_SETTINGS,
chatSettings: chatSettings || DEFAULT_CHAT_SETTINGS,
userInfo,
authToken,
previousModeApiProvider,
previousModeModelId,
previousModeModelInfo,
}
}
@ -1054,7 +1538,7 @@ export class ClineProvider implements vscode.WebviewViewProvider {
}
}
private async getSecret(key: SecretKey) {
async getSecret(key: SecretKey) {
return await this.context.secrets.get(key)
}
@ -1074,6 +1558,9 @@ export class ClineProvider implements vscode.WebviewViewProvider {
"openAiApiKey",
"geminiApiKey",
"openAiNativeApiKey",
"deepSeekApiKey",
"mistralApiKey",
"authToken",
]
for (const key of secretKeys) {
await this.storeSecret(key, undefined)
@ -1084,6 +1571,9 @@ export class ClineProvider implements vscode.WebviewViewProvider {
}
vscode.window.showInformationMessage("State reset")
await this.postStateToWebview()
await this.postMessageToWebview({ type: "action", action: "chatButtonClicked" })
await this.postMessageToWebview({
type: "action",
action: "chatButtonClicked",
})
}
}

View file

@ -17,7 +17,10 @@ export function createClineAPI(outputChannel: vscode.OutputChannel, sidebarProvi
outputChannel.appendLine("Starting new task")
await sidebarProvider.clearTask()
await sidebarProvider.postStateToWebview()
await sidebarProvider.postMessageToWebview({ type: "action", action: "chatButtonClicked" })
await sidebarProvider.postMessageToWebview({
type: "action",
action: "chatButtonClicked",
})
await sidebarProvider.postMessageToWebview({
type: "invoke",
invoke: "sendMessage",

View file

@ -3,6 +3,7 @@
import delay from "delay"
import * as vscode from "vscode"
import { ClineProvider } from "./core/webview/ClineProvider"
import { Logger } from "./services/logging/Logger"
import { createClineAPI } from "./exports"
import "./utils/path" // necessary to have access to String.prototype.toPosix
import { DIFF_VIEW_URI_SCHEME } from "./integrations/editor/DiffViewProvider"
@ -24,7 +25,8 @@ export function activate(context: vscode.ExtensionContext) {
outputChannel = vscode.window.createOutputChannel("Cline")
context.subscriptions.push(outputChannel)
outputChannel.appendLine("Cline extension activated")
Logger.initialize(outputChannel)
Logger.log("Cline extension activated")
const sidebarProvider = new ClineProvider(context, outputChannel)
@ -36,21 +38,27 @@ export function activate(context: vscode.ExtensionContext) {
context.subscriptions.push(
vscode.commands.registerCommand("cline.plusButtonClicked", async () => {
outputChannel.appendLine("Plus button Clicked")
Logger.log("Plus button Clicked")
await sidebarProvider.clearTask()
await sidebarProvider.postStateToWebview()
await sidebarProvider.postMessageToWebview({ type: "action", action: "chatButtonClicked" })
await sidebarProvider.postMessageToWebview({
type: "action",
action: "chatButtonClicked",
})
}),
)
context.subscriptions.push(
vscode.commands.registerCommand("cline.mcpButtonClicked", () => {
sidebarProvider.postMessageToWebview({ type: "action", action: "mcpButtonClicked" })
sidebarProvider.postMessageToWebview({
type: "action",
action: "mcpButtonClicked",
})
}),
)
const openClineInNewTab = async () => {
outputChannel.appendLine("Opening Cline in new tab")
Logger.log("Opening Cline in new tab")
// (this example uses webviewProvider activation event which is necessary to deserialize cached webview, but since we use retainContextWhenHidden, we don't need to use that event)
// https://github.com/microsoft/vscode-extension-samples/blob/main/webview-sample/src/extension.ts
const tabProvider = new ClineProvider(context, outputChannel)
@ -88,13 +96,28 @@ export function activate(context: vscode.ExtensionContext) {
context.subscriptions.push(
vscode.commands.registerCommand("cline.settingsButtonClicked", () => {
//vscode.window.showInformationMessage(message)
sidebarProvider.postMessageToWebview({ type: "action", action: "settingsButtonClicked" })
sidebarProvider.postMessageToWebview({
type: "action",
action: "settingsButtonClicked",
})
}),
)
context.subscriptions.push(
vscode.commands.registerCommand("cline.historyButtonClicked", () => {
sidebarProvider.postMessageToWebview({ type: "action", action: "historyButtonClicked" })
sidebarProvider.postMessageToWebview({
type: "action",
action: "historyButtonClicked",
})
}),
)
context.subscriptions.push(
vscode.commands.registerCommand("cline.accountLoginClicked", () => {
sidebarProvider.postMessageToWebview({
type: "action",
action: "accountLoginClicked",
})
}),
)
@ -110,12 +133,16 @@ export function activate(context: vscode.ExtensionContext) {
return Buffer.from(uri.query, "base64").toString("utf-8")
}
})()
context.subscriptions.push(
vscode.workspace.registerTextDocumentContentProvider(DIFF_VIEW_URI_SCHEME, diffContentProvider),
)
context.subscriptions.push(vscode.workspace.registerTextDocumentContentProvider(DIFF_VIEW_URI_SCHEME, diffContentProvider))
// URI Handler
const handleUri = async (uri: vscode.Uri) => {
console.log("URI Handler called with:", {
path: uri.path,
query: uri.query,
scheme: uri.scheme,
})
const path = uri.path
const query = new URLSearchParams(uri.query.replace(/\+/g, "%2B"))
const visibleProvider = ClineProvider.getVisibleInstance()
@ -130,6 +157,26 @@ export function activate(context: vscode.ExtensionContext) {
}
break
}
case "/auth": {
const token = query.get("token")
const state = query.get("state")
console.log("Auth callback received:", {
token: token,
state: state,
})
// Validate state parameter
if (!(await visibleProvider.validateAuthState(state))) {
vscode.window.showErrorMessage("Invalid auth state")
return
}
if (token) {
await visibleProvider.handleAuthCallback(token)
}
break
}
default:
break
}
@ -141,5 +188,5 @@ export function activate(context: vscode.ExtensionContext) {
// This method is called when your extension is deactivated
export function deactivate() {
outputChannel.appendLine("Cline extension deactivated")
Logger.log("Cline extension deactivated")
}

View file

@ -0,0 +1,420 @@
import fs from "fs/promises"
import os from "os"
import * as path from "path"
import simpleGit, { SimpleGit } from "simple-git"
import * as vscode from "vscode"
import { ClineProvider } from "../../core/webview/ClineProvider"
import { fileExistsAtPath } from "../../utils/fs"
import { globby } from "globby"
class CheckpointTracker {
private providerRef: WeakRef<ClineProvider>
private taskId: string
private disposables: vscode.Disposable[] = []
private cwd: string
private lastRetrievedShadowGitConfigWorkTree?: string
lastCheckpointHash?: string
private constructor(provider: ClineProvider, taskId: string, cwd: string) {
this.providerRef = new WeakRef(provider)
this.taskId = taskId
this.cwd = cwd
}
public static async create(taskId: string, provider?: ClineProvider): Promise<CheckpointTracker | undefined> {
try {
if (!provider) {
throw new Error("Provider is required to create a checkpoint tracker")
}
// Check if checkpoints are disabled in VS Code settings
const enableCheckpoints = vscode.workspace.getConfiguration("cline").get<boolean>("enableCheckpoints") ?? true
if (!enableCheckpoints) {
return undefined // Don't create tracker when disabled
}
// Check if git is installed by attempting to get version
try {
await simpleGit().version()
} catch (error) {
throw new Error("Git must be installed to use checkpoints.") // FIXME: must match what we check for in TaskHeader to show link
}
const cwd = await CheckpointTracker.getWorkingDirectory()
const newTracker = new CheckpointTracker(provider, taskId, cwd)
await newTracker.initShadowGit()
return newTracker
} catch (error) {
console.error("Failed to create CheckpointTracker:", error)
throw error
}
}
private static async getWorkingDirectory(): Promise<string> {
const cwd = vscode.workspace.workspaceFolders?.map((folder) => folder.uri.fsPath).at(0)
if (!cwd) {
throw new Error("No workspace detected. Please open Cline in a workspace to use checkpoints.")
}
const homedir = os.homedir()
const desktopPath = path.join(homedir, "Desktop")
const documentsPath = path.join(homedir, "Documents")
const downloadsPath = path.join(homedir, "Downloads")
switch (cwd) {
case homedir:
throw new Error("Cannot use checkpoints in home directory")
case desktopPath:
throw new Error("Cannot use checkpoints in Desktop directory")
case documentsPath:
throw new Error("Cannot use checkpoints in Documents directory")
case downloadsPath:
throw new Error("Cannot use checkpoints in Downloads directory")
default:
return cwd
}
}
private async getShadowGitPath(): Promise<string> {
const globalStoragePath = this.providerRef.deref()?.context.globalStorageUri.fsPath
if (!globalStoragePath) {
throw new Error("Global storage uri is invalid")
}
const checkpointsDir = path.join(globalStoragePath, "tasks", this.taskId, "checkpoints")
await fs.mkdir(checkpointsDir, { recursive: true })
const gitPath = path.join(checkpointsDir, ".git")
return gitPath
}
public static async doesShadowGitExist(taskId: string, provider?: ClineProvider): Promise<boolean> {
const globalStoragePath = provider?.context.globalStorageUri.fsPath
if (!globalStoragePath) {
return false
}
const gitPath = path.join(globalStoragePath, "tasks", taskId, "checkpoints", ".git")
return await fileExistsAtPath(gitPath)
}
public async initShadowGit(): Promise<string> {
const gitPath = await this.getShadowGitPath()
if (await fileExistsAtPath(gitPath)) {
// Make sure it's the same cwd as the configured worktree
const worktree = await this.getShadowGitConfigWorkTree()
if (worktree !== this.cwd) {
throw new Error("Checkpoints can only be used in the original workspace: " + worktree)
}
return gitPath
} else {
const checkpointsDir = path.dirname(gitPath)
const git = simpleGit(checkpointsDir)
await git.init()
await git.addConfig("core.worktree", this.cwd) // sets the working tree to the current workspace
// Disable commit signing for shadow repo
await git.addConfig("commit.gpgSign", "false")
// Get LFS patterns from workspace if they exist
let lfsPatterns: string[] = []
try {
const attributesPath = path.join(this.cwd, ".gitattributes")
if (await fileExistsAtPath(attributesPath)) {
const attributesContent = await fs.readFile(attributesPath, "utf8")
lfsPatterns = attributesContent
.split("\n")
.filter((line) => line.includes("filter=lfs"))
.map((line) => line.split(" ")[0].trim())
}
} catch (error) {
console.warn("Failed to read .gitattributes:", error)
}
// Add basic excludes directly in git config, while respecting any .gitignore in the workspace
// .git/info/exclude is local to the shadow git repo, so it's not shared with the main repo - and won't conflict with user's .gitignore
// TODO: let user customize these
const excludesPath = path.join(gitPath, "info", "exclude")
await fs.mkdir(path.join(gitPath, "info"), { recursive: true })
await fs.writeFile(
excludesPath,
[
".git/", // ignore the user's .git
`.git${GIT_DISABLED_SUFFIX}/`, // ignore the disabled nested git repos
".DS_Store",
"*.log",
"node_modules/",
"__pycache__/",
"env/",
"venv/",
"target/dependency/",
"build/dependencies/",
"dist/",
"out/",
"bundle/",
"vendor/",
"tmp/",
"temp/",
"deps/",
"pkg/",
"Pods/",
// Media files
"*.jpg",
"*.jpeg",
"*.png",
"*.gif",
"*.bmp",
"*.ico",
// "*.svg",
"*.mp3",
"*.mp4",
"*.wav",
"*.avi",
"*.mov",
"*.wmv",
"*.webm",
"*.webp",
"*.m4a",
"*.flac",
// Build and dependency directories
"build/",
"bin/",
"obj/",
".gradle/",
".idea/",
".vscode/",
".vs/",
"coverage/",
".next/",
".nuxt/",
// Cache and temporary files
"*.cache",
"*.tmp",
"*.temp",
"*.swp",
"*.swo",
"*.pyc",
"*.pyo",
".pytest_cache/",
".eslintcache",
// Environment and config files
".env*",
"*.local",
"*.development",
"*.production",
// Large data files
"*.zip",
"*.tar",
"*.gz",
"*.rar",
"*.7z",
"*.iso",
"*.bin",
"*.exe",
"*.dll",
"*.so",
"*.dylib",
// Database files
"*.sqlite",
"*.db",
"*.sql",
// Log files
"*.logs",
"*.error",
"npm-debug.log*",
"yarn-debug.log*",
"yarn-error.log*",
...lfsPatterns,
].join("\n"),
)
// Set up git identity (git throws an error if user.name or user.email is not set)
await git.addConfig("user.name", "Cline Checkpoint")
await git.addConfig("user.email", "noreply@example.com")
await this.addAllFiles(git)
// Initial commit (--allow-empty ensures it works even with no files)
await git.commit("initial commit", { "--allow-empty": null })
return gitPath
}
}
public async getShadowGitConfigWorkTree(): Promise<string | undefined> {
if (this.lastRetrievedShadowGitConfigWorkTree) {
return this.lastRetrievedShadowGitConfigWorkTree
}
try {
const gitPath = await this.getShadowGitPath()
const git = simpleGit(path.dirname(gitPath))
const worktree = await git.getConfig("core.worktree")
this.lastRetrievedShadowGitConfigWorkTree = worktree.value || undefined
return this.lastRetrievedShadowGitConfigWorkTree
} catch (error) {
console.error("Failed to get shadow git config worktree:", error)
return undefined
}
}
public async commit(): Promise<string | undefined> {
try {
const gitPath = await this.getShadowGitPath()
const git = simpleGit(path.dirname(gitPath))
await this.addAllFiles(git)
const result = await git.commit("checkpoint", {
"--allow-empty": null,
})
const commitHash = result.commit || ""
this.lastCheckpointHash = commitHash
return commitHash
} catch (error) {
console.error("Failed to create checkpoint:", error)
return undefined
}
}
public async resetHead(commitHash: string): Promise<void> {
const gitPath = await this.getShadowGitPath()
const git = simpleGit(path.dirname(gitPath))
// Clean working directory and force reset
// This ensures that the operation will succeed regardless of:
// - Untracked files in the workspace
// - Staged changes
// - Unstaged changes
// - Partial commits
// - Merge conflicts
await git.clean("f", ["-d", "-f"]) // Remove untracked files and directories
await git.reset(["--hard", commitHash]) // Hard reset to target commit
}
/**
* Return an array describing changed files between one commit and either:
* - another commit, or
* - the current working directory (including uncommitted changes).
*
* If `rhsHash` is omitted, compares `lhsHash` to the working directory.
* If you want truly untracked files to appear, `git add` them first.
*
* @param lhsHash - The commit to compare from (older commit)
* @param rhsHash - The commit to compare to (newer commit).
* If omitted, we compare to the working directory.
* @returns Array of file changes with before/after content
*/
public async getDiffSet(
lhsHash?: string,
rhsHash?: string,
): Promise<
Array<{
relativePath: string
absolutePath: string
before: string
after: string
}>
> {
const gitPath = await this.getShadowGitPath()
const git = simpleGit(path.dirname(gitPath))
// If lhsHash is missing, use the initial commit of the repo
let baseHash = lhsHash
if (!baseHash) {
const rootCommit = await git.raw(["rev-list", "--max-parents=0", "HEAD"])
baseHash = rootCommit.trim()
}
// Stage all changes so that untracked files appear in diff summary
await this.addAllFiles(git)
const diffSummary = rhsHash ? await git.diffSummary([`${baseHash}..${rhsHash}`]) : await git.diffSummary([baseHash])
// For each changed file, gather before/after content
const result = []
const cwdPath = (await this.getShadowGitConfigWorkTree()) || this.cwd || ""
for (const file of diffSummary.files) {
const filePath = file.file
const absolutePath = path.join(cwdPath, filePath)
let beforeContent = ""
try {
beforeContent = await git.show([`${baseHash}:${filePath}`])
} catch (_) {
// file didn't exist in older commit => remains empty
}
let afterContent = ""
if (rhsHash) {
// if user provided a newer commit, use git.show at that commit
try {
afterContent = await git.show([`${rhsHash}:${filePath}`])
} catch (_) {
// file didn't exist in newer commit => remains empty
}
} else {
// otherwise, read from disk (includes uncommitted changes)
try {
afterContent = await fs.readFile(absolutePath, "utf8")
} catch (_) {
// file might be deleted => remains empty
}
}
result.push({
relativePath: filePath,
absolutePath,
before: beforeContent,
after: afterContent,
})
}
return result
}
private async addAllFiles(git: SimpleGit) {
await this.renameNestedGitRepos(true)
try {
await git.add(".")
} catch (error) {
console.error("Failed to add files to git:", error)
} finally {
await this.renameNestedGitRepos(false)
}
}
// Since we use git to track checkpoints, we need to temporarily disable nested git repos to work around git's requirement of using submodules for nested repos.
private async renameNestedGitRepos(disable: boolean) {
// Find all .git directories that are not at the root level
const gitPaths = await globby("**/.git" + (disable ? "" : GIT_DISABLED_SUFFIX), {
cwd: this.cwd,
onlyDirectories: true,
ignore: [".git"], // Ignore root level .git
dot: true,
markDirectories: false,
})
// For each nested .git directory, rename it based on operation
for (const gitPath of gitPaths) {
const fullPath = path.join(this.cwd, gitPath)
let newPath: string
if (disable) {
newPath = fullPath + GIT_DISABLED_SUFFIX
} else {
newPath = fullPath.endsWith(GIT_DISABLED_SUFFIX) ? fullPath.slice(0, -GIT_DISABLED_SUFFIX.length) : fullPath
}
try {
await fs.rename(fullPath, newPath)
console.log(`CheckpointTracker ${disable ? "disabled" : "enabled"} nested git repo ${gitPath}`)
} catch (error) {
console.error(`CheckpointTracker failed to ${disable ? "disable" : "enable"} nested git repo ${gitPath}:`, error)
}
}
}
public dispose() {
this.disposables.forEach((d) => d.dispose())
this.disposables = []
}
}
const GIT_DISABLED_SUFFIX = "_disabled"
export default CheckpointTracker

View file

@ -0,0 +1,75 @@
import * as vscode from "vscode"
interface DebugSession {
id: string
name: string
output: string[]
lastRetrievedIndex: number
}
export class DebugConsoleManager {
private sessions: Map<string, DebugSession> = new Map()
private disposables: vscode.Disposable[] = []
constructor() {
// Listen for debug session start events
this.disposables.push(
vscode.debug.onDidStartDebugSession((session) => {
this.sessions.set(session.id, {
id: session.id,
name: session.name,
output: [],
lastRetrievedIndex: -1,
})
}),
)
// Listen for debug session end events
this.disposables.push(
vscode.debug.onDidTerminateDebugSession((session) => {
this.sessions.delete(session.id)
}),
)
// Listen for debug console output
this.disposables.push(
vscode.debug.onDidReceiveDebugSessionCustomEvent((e: vscode.DebugSessionCustomEvent) => {
if (e.event === "output" && e.body?.output) {
const session = this.sessions.get(e.session.id)
if (session) {
session.output.push(e.body.output)
}
}
}),
)
}
/**
* Get all active debug sessions
*/
getActiveSessions(): { id: string; name: string }[] {
return Array.from(this.sessions.values()).map(({ id, name }) => ({ id, name }))
}
/**
* Get any new output since the last retrieval for a specific debug session
*/
getUnretrievedOutput(sessionId: string): string | undefined {
const session = this.sessions.get(sessionId)
if (!session) {
return undefined
}
const newOutput = session.output.slice(session.lastRetrievedIndex + 1).join("")
session.lastRetrievedIndex = session.output.length - 1
return newOutput || undefined
}
/**
* Clean up resources
*/
dispose() {
this.disposables.forEach((d) => d.dispose())
this.sessions.clear()
}
}

View file

@ -63,10 +63,7 @@ export class DecorationController {
// Add a new range for all lines after the current line
if (line < totalLines - 1) {
this.ranges.push(
new vscode.Range(
new vscode.Position(line + 1, 0),
new vscode.Position(totalLines - 1, Number.MAX_SAFE_INTEGER),
),
new vscode.Range(new vscode.Position(line + 1, 0), new vscode.Position(totalLines - 1, Number.MAX_SAFE_INTEGER)),
)
}

View file

@ -33,9 +33,7 @@ export class DiffViewProvider {
this.isEditing = true
// if the file is already open, ensure it's not dirty before getting its contents
if (fileExists) {
const existingDocument = vscode.workspace.textDocuments.find((doc) =>
arePathsEqual(doc.uri.fsPath, absolutePath),
)
const existingDocument = vscode.workspace.textDocuments.find((doc) => arePathsEqual(doc.uri.fsPath, absolutePath))
if (existingDocument && existingDocument.isDirty) {
await existingDocument.save()
}
@ -61,9 +59,7 @@ export class DiffViewProvider {
const tabs = vscode.window.tabGroups.all
.map((tg) => tg.tabs)
.flat()
.filter(
(tab) => tab.input instanceof vscode.TabInputText && arePathsEqual(tab.input.uri.fsPath, absolutePath),
)
.filter((tab) => tab.input instanceof vscode.TabInputText && arePathsEqual(tab.input.uri.fsPath, absolutePath))
for (const tab of tabs) {
if (!tab.isDirty) {
await vscode.window.tabGroups.close(tab)
@ -141,10 +137,16 @@ export class DiffViewProvider {
async saveChanges(): Promise<{
newProblemsMessage: string | undefined
userEdits: string | undefined
autoFormattingEdits: string | undefined
finalContent: string | undefined
}> {
if (!this.relPath || !this.newContent || !this.activeDiffEditor) {
return { newProblemsMessage: undefined, userEdits: undefined, finalContent: undefined }
return {
newProblemsMessage: undefined,
userEdits: undefined,
autoFormattingEdits: undefined,
finalContent: undefined,
}
}
const absolutePath = path.resolve(this.cwd, this.relPath)
const updatedDocument = this.activeDiffEditor.document
@ -160,7 +162,9 @@ export class DiffViewProvider {
// get text after save in case there is any auto-formatting done by the editor
const postSaveContent = updatedDocument.getText()
await vscode.window.showTextDocument(vscode.Uri.file(absolutePath), { preview: false })
await vscode.window.showTextDocument(vscode.Uri.file(absolutePath), {
preview: false,
})
await this.closeAllDiffViews()
/*
@ -197,17 +201,32 @@ export class DiffViewProvider {
const normalizedPostSaveContent = postSaveContent.replace(/\r\n|\n/g, newContentEOL).trimEnd() + newContentEOL // this is the final content we return to the model to use as the new baseline for future edits
// just in case the new content has a mix of varying EOL characters
const normalizedNewContent = this.newContent.replace(/\r\n|\n/g, newContentEOL).trimEnd() + newContentEOL
let userEdits: string | undefined
if (normalizedPreSaveContent !== normalizedNewContent) {
// user made changes before approving edit. let the model know about user made changes (not including post-save auto-formatting changes)
const userEdits = formatResponse.createPrettyPatch(
this.relPath.toPosix(),
normalizedNewContent,
normalizedPreSaveContent,
)
return { newProblemsMessage, userEdits, finalContent: normalizedPostSaveContent }
userEdits = formatResponse.createPrettyPatch(this.relPath.toPosix(), normalizedNewContent, normalizedPreSaveContent)
// return { newProblemsMessage, userEdits, finalContent: normalizedPostSaveContent }
} else {
// no changes to cline's edits
return { newProblemsMessage, userEdits: undefined, finalContent: normalizedPostSaveContent }
// return { newProblemsMessage, userEdits: undefined, finalContent: normalizedPostSaveContent }
}
let autoFormattingEdits: string | undefined
if (normalizedPreSaveContent !== normalizedPostSaveContent) {
// auto-formatting was done by the editor
autoFormattingEdits = formatResponse.createPrettyPatch(
this.relPath.toPosix(),
normalizedPreSaveContent,
normalizedPostSaveContent,
)
}
return {
newProblemsMessage,
userEdits,
autoFormattingEdits,
finalContent: normalizedPostSaveContent,
}
}
@ -257,11 +276,7 @@ export class DiffViewProvider {
private async closeAllDiffViews() {
const tabs = vscode.window.tabGroups.all
.flatMap((tg) => tg.tabs)
.filter(
(tab) =>
tab.input instanceof vscode.TabInputTextDiff &&
tab.input?.original?.scheme === DIFF_VIEW_URI_SCHEME,
)
.filter((tab) => tab.input instanceof vscode.TabInputTextDiff && tab.input?.original?.scheme === DIFF_VIEW_URI_SCHEME)
for (const tab of tabs) {
// trying to close dirty views results in save popup
if (!tab.isDirty) {

View file

@ -42,11 +42,7 @@ export async function downloadTask(dateTs: number, conversationHistory: Anthropi
}
export function formatContentBlockToMarkdown(
block:
| Anthropic.TextBlockParam
| Anthropic.ImageBlockParam
| Anthropic.ToolUseBlockParam
| Anthropic.ToolResultBlockParam,
block: Anthropic.TextBlockParam | Anthropic.ImageBlockParam | Anthropic.ToolUseBlockParam | Anthropic.ToolResultBlockParam,
// messages: Anthropic.MessageParam[]
): string {
switch (block.type) {

View file

@ -28,14 +28,11 @@ export async function openFile(absolutePath: string) {
try {
for (const group of vscode.window.tabGroups.all) {
const existingTab = group.tabs.find(
(tab) =>
tab.input instanceof vscode.TabInputText && arePathsEqual(tab.input.uri.fsPath, uri.fsPath),
(tab) => tab.input instanceof vscode.TabInputText && arePathsEqual(tab.input.uri.fsPath, uri.fsPath),
)
if (existingTab) {
const activeColumn = vscode.window.activeTextEditor?.viewColumn
const tabColumn = vscode.window.tabGroups.all.find((group) =>
group.tabs.includes(existingTab),
)?.viewColumn
const tabColumn = vscode.window.tabGroups.all.find((group) => group.tabs.includes(existingTab))?.viewColumn
if (activeColumn && activeColumn !== tabColumn && !existingTab.isDirty) {
await vscode.window.tabGroups.close(existingTab)
}

View file

@ -71,15 +71,22 @@ export async function showSystemNotification(options: NotificationOptions): Prom
throw new Error("Message is required")
}
const escapedOptions = {
...options,
title: title.replace(/"/g, '\\"'),
message: message.replace(/"/g, '\\"'),
subtitle: options.subtitle?.replace(/"/g, '\\"') || "",
}
switch (platform()) {
case "darwin":
await showMacOSNotification({ ...options, title })
await showMacOSNotification(escapedOptions)
break
case "win32":
await showWindowsNotification({ ...options, title })
await showWindowsNotification(escapedOptions)
break
case "linux":
await showLinuxNotification({ ...options, title })
await showLinuxNotification(escapedOptions)
break
default:
throw new Error("Unsupported platform")

View file

@ -157,8 +157,10 @@ export class TerminalManager {
}
async getOrCreateTerminal(cwd: string): Promise<TerminalInfo> {
const terminals = TerminalRegistry.getAllTerminals()
// Find available terminal from our pool first (created for this task)
const availableTerminal = TerminalRegistry.getAllTerminals().find((t) => {
const matchingTerminal = terminals.find((t) => {
if (t.busy) {
return false
}
@ -168,11 +170,21 @@ export class TerminalManager {
}
return arePathsEqual(vscode.Uri.file(cwd).fsPath, terminalCwd.fsPath)
})
if (matchingTerminal) {
this.terminalIds.add(matchingTerminal.id)
return matchingTerminal
}
// If no matching terminal exists, try to find any non-busy terminal
const availableTerminal = terminals.find((t) => !t.busy)
if (availableTerminal) {
// Navigate back to the desired directory
await this.runCommand(availableTerminal, `cd "${cwd}"`)
this.terminalIds.add(availableTerminal.id)
return availableTerminal
}
// If all terminals are busy, create a new one
const newTerminalInfo = TerminalRegistry.createTerminal(cwd)
this.terminalIds.add(newTerminalInfo.id)
return newTerminalInfo

View file

@ -364,11 +364,7 @@
},
{
"name": "coloring of the Java import and package identifiers",
"scope": [
"storage.modifier.import.java",
"variable.language.wildcard.java",
"storage.modifier.package.java"
],
"scope": ["storage.modifier.import.java", "variable.language.wildcard.java", "storage.modifier.package.java"],
"settings": {
"foreground": "#d4d4d4"
}

View file

@ -57,12 +57,7 @@
}
},
{
"scope": [
"constant.numeric",
"constant.other.color.rgb-value",
"constant.other.rgb-value",
"support.constant.color"
],
"scope": ["constant.numeric", "constant.other.color.rgb-value", "constant.other.rgb-value", "support.constant.color"],
"settings": {
"foreground": "#b5cea8"
}
@ -320,11 +315,7 @@
},
{
"name": "coloring of the Java import and package identifiers",
"scope": [
"storage.modifier.import.java",
"variable.language.wildcard.java",
"storage.modifier.package.java"
],
"scope": ["storage.modifier.import.java", "variable.language.wildcard.java", "storage.modifier.package.java"],
"settings": {
"foreground": "#d4d4d4"
}

View file

@ -346,11 +346,7 @@
}
},
{
"scope": [
"storage.modifier.import.java",
"variable.language.wildcard.java",
"storage.modifier.package.java"
],
"scope": ["storage.modifier.import.java", "variable.language.wildcard.java", "storage.modifier.package.java"],
"settings": {
"foreground": "#000000"
}

View file

@ -389,11 +389,7 @@
},
{
"name": "coloring of the Java import and package identifiers",
"scope": [
"storage.modifier.import.java",
"variable.language.wildcard.java",
"storage.modifier.package.java"
],
"scope": ["storage.modifier.import.java", "variable.language.wildcard.java", "storage.modifier.package.java"],
"settings": {
"foreground": "#000000"
}

View file

@ -74,11 +74,7 @@ export async function getTheme() {
const converted = convertTheme(parsed)
converted.base = (
["vs", "hc-black"].includes(converted.base)
? converted.base
: colorTheme.includes("Light")
? "vs"
: "vs-dark"
["vs", "hc-black"].includes(converted.base) ? converted.base : colorTheme.includes("Light") ? "vs" : "vs-dark"
) as any
return converted

View file

@ -27,25 +27,58 @@ class WorkspaceTracker {
}
private registerListeners() {
const watcher = vscode.workspace.createFileSystemWatcher("**")
// Listen for file creation
// .bind(this) ensures the callback refers to class instance when using this, not necessary when using arrow function
this.disposables.push(vscode.workspace.onDidCreateFiles(this.onFilesCreated.bind(this)))
this.disposables.push(
watcher.onDidCreate(async (uri) => {
await this.addFilePath(uri.fsPath)
this.workspaceDidUpdate()
// Listen for file deletion
this.disposables.push(vscode.workspace.onDidDeleteFiles(this.onFilesDeleted.bind(this)))
// Listen for file renaming
this.disposables.push(vscode.workspace.onDidRenameFiles(this.onFilesRenamed.bind(this)))
/*
An event that is emitted when a workspace folder is added or removed.
**Note:** this event will not fire if the first workspace folder is added, removed or changed,
because in that case the currently executing extensions (including the one that listens to this
event) will be terminated and restarted so that the (deprecated) `rootPath` property is updated
to point to the first workspace folder.
*/
// In other words, we don't have to worry about the root workspace folder ([0]) changing since the extension will be restarted and our cwd will be updated to reflect the new workspace folder. (We don't care about non root workspace folders, since cline will only be working within the root folder cwd)
// this.disposables.push(vscode.workspace.onDidChangeWorkspaceFolders(this.onWorkspaceFoldersChanged.bind(this)))
}
private async onFilesCreated(event: vscode.FileCreateEvent) {
await Promise.all(
event.files.map(async (file) => {
await this.addFilePath(file.fsPath)
}),
)
this.workspaceDidUpdate()
}
// Renaming files triggers a delete and create event
this.disposables.push(
watcher.onDidDelete(async (uri) => {
if (await this.removeFilePath(uri.fsPath)) {
this.workspaceDidUpdate()
private async onFilesDeleted(event: vscode.FileDeleteEvent) {
let updated = false
await Promise.all(
event.files.map(async (file) => {
if (await this.removeFilePath(file.fsPath)) {
updated = true
}
}),
)
if (updated) {
this.workspaceDidUpdate()
}
}
this.disposables.push(watcher)
private async onFilesRenamed(event: vscode.FileRenameEvent) {
await Promise.all(
event.files.map(async (file) => {
await this.removeFilePath(file.oldUri.fsPath)
await this.addFilePath(file.newUri.fsPath)
}),
)
this.workspaceDidUpdate()
}
private workspaceDidUpdate() {

View file

@ -0,0 +1,99 @@
import { initializeApp } from "firebase/app"
import { Auth, User, getAuth, onAuthStateChanged, signInWithCustomToken, signOut } from "firebase/auth"
import * as vscode from "vscode"
import { ClineProvider } from "../../core/webview/ClineProvider"
import { firebaseConfig } from "./config"
export interface UserInfo {
displayName: string | null
email: string | null
photoURL: string | null
}
export class FirebaseAuthManager {
private providerRef: WeakRef<ClineProvider>
private auth: Auth
private disposables: vscode.Disposable[] = []
constructor(provider: ClineProvider) {
console.log("Initializing FirebaseAuthManager", { provider })
this.providerRef = new WeakRef(provider)
const app = initializeApp(firebaseConfig)
this.auth = getAuth(app)
console.log("Firebase app initialized", { appConfig: firebaseConfig })
// Auth state listener
onAuthStateChanged(this.auth, this.handleAuthStateChange.bind(this))
console.log("Auth state change listener added")
// Try to restore session
this.restoreSession()
}
private async restoreSession() {
console.log("Attempting to restore session")
const provider = this.providerRef.deref()
if (!provider) {
console.log("Provider reference lost during session restore")
return
}
const storedToken = await provider.getSecret("authToken")
if (storedToken) {
console.log("Found stored auth token, attempting to restore session")
try {
await this.signInWithCustomToken(storedToken)
console.log("Session restored successfully")
} catch (error) {
console.error("Failed to restore session, clearing token:", error)
await provider.setAuthToken(undefined)
await provider.setUserInfo(undefined)
}
} else {
console.log("No stored auth token found")
}
}
private async handleAuthStateChange(user: User | null) {
console.log("Auth state changed", { user })
const provider = this.providerRef.deref()
if (!provider) {
console.log("Provider reference lost")
return
}
if (user) {
console.log("User signed in", { userId: user.uid })
const idToken = await user.getIdToken()
await provider.setAuthToken(idToken)
// Store public user info in state
await provider.setUserInfo({
displayName: user.displayName,
email: user.email,
photoURL: user.photoURL,
})
console.log("User info set in provider", { user })
} else {
console.log("User signed out")
await provider.setAuthToken(undefined)
await provider.setUserInfo(undefined)
}
await provider.postStateToWebview()
console.log("Webview state updated")
}
async signInWithCustomToken(token: string) {
console.log("Signing in with custom token", { token })
await signInWithCustomToken(this.auth, token)
}
async signOut() {
console.log("Signing out")
await signOut(this.auth)
}
dispose() {
this.disposables.forEach((d) => d.dispose())
console.log("Disposables disposed", { count: this.disposables.length })
}
}

View file

@ -0,0 +1,10 @@
// Public Firebase config (safe for open source)
export const firebaseConfig = {
apiKey: "AIzaSyDcXAaanNgR2_T0dq2oOl5XyKPksYHppVo",
authDomain: "cline-bot.firebaseapp.com",
projectId: "cline-bot",
storageBucket: "cline-bot.firebasestorage.app",
messagingSenderId: "364369702101",
appId: "1:364369702101:web:0013885dcf20b43799c65c",
measurementId: "G-MDPRELSCD1",
}

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