Compare commits

..

1 Commits

Author SHA1 Message Date
abeatrix 6ffba23d3d refactor: convert GitCommitGenerator from module to class
- Convert module pattern to class-based implementation
- Move abort controller to private instance variable
- Add proper method documentation with JSDoc
- Improve encapsulation and code organization
2025-09-02 14:24:11 -07:00
549 changed files with 16902 additions and 32217 deletions
+5
View File
@@ -0,0 +1,5 @@
---
"claude-dev": patch
---
fix showing the ai core exisiting models when resource group field is empty (using the default resource group)
+5
View File
@@ -0,0 +1,5 @@
---
"claude-dev": patch
---
Fix issue on Account view where balance is fetched twice that cause janky UI
+5
View File
@@ -0,0 +1,5 @@
---
"claude-dev": patch
---
Fixes an issue where thinking text from litellm was not being passed through to Cline thinking UI
+5
View File
@@ -0,0 +1,5 @@
---
"claude-dev": patch
---
Fix Ollama connection issue to default endpoint at port 11434
+5
View File
@@ -0,0 +1,5 @@
---
"claude-dev": patch
---
Optimized Cline for GPT-5 model family with an aligned system prompt
+5
View File
@@ -0,0 +1,5 @@
---
"claude-dev": patch
---
REfactoring Tool Executor
+5
View File
@@ -0,0 +1,5 @@
---
"claude-dev": patch
---
Add search functionality to API provider dropdown
+5
View File
@@ -0,0 +1,5 @@
---
"claude-dev": patch
---
Remove disabled approve / reject buttons from UI.
+5
View File
@@ -0,0 +1,5 @@
---
"claude-dev": patch
---
Add "Use custom prompt" option to Ollama provider
+5
View File
@@ -0,0 +1,5 @@
---
"claude-dev": patch
---
Fix AutoApproveModal overflowing issue
+5
View File
@@ -0,0 +1,5 @@
---
"claude-dev": patch
---
Dify.ai api integration
+5
View File
@@ -0,0 +1,5 @@
---
"claude-dev": minor
---
support orchestration mode for sap provider
+5
View File
@@ -0,0 +1,5 @@
---
"claude-dev": patch
---
Improve Gemini Rate Limit handling
+5
View File
@@ -0,0 +1,5 @@
---
"claude-dev": patch
---
fix: Support Anthropic Caching when using LiteLLM
+5
View File
@@ -0,0 +1,5 @@
---
"claude-dev": patch
---
Prompt changes for deep-planning in windows/powershell
+2 -2
View File
@@ -1,3 +1,3 @@
/docs/
/.github/ @saoudrizwan @garoth @sjf
/README.md @saoudrizwan @nickbaumann98
/.github/ @saoudrizwan @dcbartlett
/README.md @saoudrizwan @nickbaumann98
+61 -66
View File
@@ -1,69 +1,64 @@
name: 🐛 Bug Report
description: File a bug report
labels: ['bug']
labels: ["bug"]
body:
- type: markdown
attributes:
value: |
**Important:** All bug reports must be reproducible using Claude Sonnet 4.5. Cline uses complex prompts so less capable models may not work as expected.
- type: dropdown
id: plugin-type
attributes:
label: Plugin Type
description: Which plugin are you reporting a bug for?
options:
- VSCode Extension
- JetBrains Plugin
default: 0
validations:
required: true
- type: input
id: cline-version
attributes:
label: Cline Version
description: What version of Cline are you using? (You can find this at the bottom of the Settings view)
placeholder: 'e.g., 1.2.3'
validations:
required: true
- type: textarea
id: what-happened
attributes:
label: What happened?
description: Also tell us, what did you expect to happen?
placeholder: Tell us what you see!
validations:
required: true
- type: textarea
id: steps
attributes:
label: Steps to reproduce
description: How do you trigger this bug? Please walk us through it step by step.
value: |
1.
2.
3.
validations:
required: false
- type: input
id: provider-model
attributes:
label: Provider/Model
description: What provider and model were you using when the issue occurred?
placeholder: 'e.g., cline:anthropic/claude-sonnet-4.5, gemini:gemini-2.5-pro-exp-03-25'
validations:
required: false
- type: textarea
id: system-info
attributes:
label: System Information
description: What operating system and hardware are you using?
placeholder: |
Operating System: Windows 11, macOS Sonoma, Ubuntu 22.04, etc.
Hardware: CPU, GPU, RAM specifications if relevant
e.g.,
OS: Windows 11
CPU: Intel Core i7-11700K
GPU: NVIDIA GeForce RTX 3070
RAM: 32GB DDR4
validations:
required: false
- type: markdown
attributes:
value: |
**Important:** All bug reports must be reproducible using Claude 4 Sonnet. Cline uses complex prompts so less capable models may not work as expected.
- type: textarea
id: what-happened
attributes:
label: What happened?
description: Also tell us, what did you expect to happen?
placeholder: Tell us what you see!
validations:
required: true
- type: textarea
id: steps
attributes:
label: Steps to reproduce
description: How do you trigger this bug? Please walk us through it step by step.
value: |
1.
2.
3.
validations:
required: false
- type: textarea
id: logs
attributes:
label: Relevant API REQUEST output
description: Please copy and paste any relevant output. This will be automatically formatted into code, so no need for backticks.
render: shell
- type: input
id: provider-model
attributes:
label: Provider/Model
description: What provider and model were you using when the issue occurred?
placeholder: "e.g., cline:anthropic/claude-3.7-sonnet, gemini:gemini-2.5-pro-exp-03-25"
validations:
required: true
- type: textarea
id: system-info
attributes:
label: System Information
description: What operating system and hardware are you using?
placeholder: |
Operating System: Windows 11, macOS Sonoma, Ubuntu 22.04, etc.
Hardware: CPU, GPU, RAM specifications if relevant
e.g.,
OS: Windows 11
CPU: Intel Core i7-11700K
GPU: NVIDIA GeForce RTX 3070
RAM: 32GB DDR4
validations:
required: true
- type: input
id: cline-version
attributes:
label: Cline Version
description: What version of Cline are you using? (You can find this at the bottom of the Settings view)
placeholder: "e.g., 1.2.3"
validations:
required: true
-75
View File
@@ -1,75 +0,0 @@
name: "Publish Nightly Release"
on:
schedule:
- cron: '0 12 * * *' # 4 AM PST (UTC-8) = 12 UTC
workflow_dispatch:
permissions:
contents: write
packages: write
checks: write
pull-requests: write
jobs:
test:
uses: ./.github/workflows/test.yml
publish:
needs: test
name: Publish Cline (Nightly) Extension
if: github.repository == 'cline/cline'
runs-on: ubuntu-latest
environment: PublishNightly
steps:
- uses: actions/checkout@v4
- name: Check for recent commits
run: |
if [ $(git rev-list --count HEAD --since="24 hours ago") -eq 0 ]; then
echo "No commits in last 24 hours, exiting"
exit 0
fi
echo "Found recent commits, proceeding with build"
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: "lts/*"
# 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 --include=optional
- name: Install webview-ui dependencies
if: steps.webview-cache.outputs.cache-hit != 'true'
run: cd webview-ui && npm ci --include=optional
- name: Install Publishing Tools
run: npm install -g @vscode/vsce ovsx
- name: Publish Extension as Pre-release
env:
VSCE_PAT: ${{ secrets.VSCE_PAT }}
OVSX_PAT: ${{ secrets.OVSX_PAT }}
TELEMETRY_SERVICE_API_KEY: ${{ secrets.TELEMETRY_SERVICE_API_KEY }}
ERROR_SERVICE_API_KEY: ${{ secrets.ERROR_SERVICE_API_KEY }}
CLINE_ENVIRONMENT: production
run: npm run publish:marketplace:nightly
-2
View File
@@ -95,8 +95,6 @@ jobs:
VSCE_PAT: ${{ secrets.VSCE_PAT }}
OVSX_PAT: ${{ secrets.OVSX_PAT }}
CLINE_ENVIRONMENT: production
TELEMETRY_SERVICE_API_KEY: ${{ secrets.TELEMETRY_SERVICE_API_KEY }}
ERROR_SERVICE_API_KEY: ${{ secrets.ERROR_SERVICE_API_KEY }}
run: |
# Required to generate the .vsix
vsce package --allow-package-secrets sendgrid --out "cline-${{ steps.get_version.outputs.version }}.vsix"
+104 -154
View File
@@ -1,9 +1,6 @@
name: Tests
on:
push:
branches:
- main
workflow_dispatch:
pull_request:
branches:
@@ -17,45 +14,7 @@ permissions:
pull-requests: write # Needed to add comments/annotations to PRs
jobs:
quality-checks:
runs-on: ubuntu-latest
name: Quality Checks
steps:
- name: Checkout code
uses: actions/checkout@v4
- name: Setup Node.js environment
uses: actions/setup-node@v4
with:
node-version: 22
- name: Cache root dependencies
uses: actions/cache@v4
id: root-cache
with:
path: node_modules
key: ${{ runner.os }}-npm-${{ hashFiles('package-lock.json') }}
- 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: Run Quality Checks (Parallel)
run: npm run ci:check-all
test:
needs: quality-checks
strategy:
fail-fast: false
matrix:
@@ -74,6 +33,18 @@ jobs:
with:
node-version: 22
# Setup Python for coverage script
- name: Setup Python
uses: actions/setup-python@v4
with:
python-version: "3.10"
- name: Install Python dependencies
run: |
python -m pip install --upgrade pip
pip install requests
# Cache root dependencies - only reuse if package-lock.json exactly matches
- name: Cache root dependencies
uses: actions/cache@v4
id: root-cache
@@ -81,6 +52,7 @@ jobs:
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
@@ -96,60 +68,54 @@ jobs:
if: steps.webview-cache.outputs.cache-hit != 'true'
run: cd webview-ui && npm ci
- name: Install xvfb on Linux
if: runner.os == 'Linux'
run: sudo apt-get update && sudo apt-get install -y xvfb
- name: Set up NPM on Windows
if: runner.os == 'Windows'
run: |
npm config set script-shell "C:\\Program Files\\Git\\bin\\bash.exe"
# Build the extension and tests (without redundant checks)
- name: Type Check
run: npm run check-types
- name: Lint Check
run: npm run lint
- name: Format Check
run: npm run format
# Build the extension before running tests
- name: Build Tests and Extension
run: npm run ci:build
run: npm run pretest
- name: Unit Tests with coverage - Linux
id: unit_tests_linux
- name: Unit Tests
run: npm run test:unit
# Run extension tests with coverage
- name: Extension Integration Tests with Coverage
id: extension_coverage
continue-on-error: true
if: runner.os == 'Linux'
run: |
npx nyc --nycrc-path .nycrc.unit.json --reporter=lcov npm run test:unit
- name: Unit Tests - Non-Linux
id: unit_tests_non_linux
continue-on-error: true
if: runner.os != 'Linux'
run: |
npm run test:unit
- name: Extension Integration Tests - Linux
id: integration_tests_linux
continue-on-error: true
if: runner.os == 'Linux'
run: xvfb-run -a npm run test:coverage
- name: Extension Integration Tests - Non-Linux
id: integration_tests_non_linux
continue-on-error: true
if: runner.os != 'Linux'
run: npm run test:integration
node ./scripts/test-ci.js 2>&1 | tee extension_coverage.txt
# Default the encoding to UTF-8 - It's not the default on Windows
PYTHONUTF8=1 PYTHONPATH=.github/scripts python -m coverage_check extract-coverage extension_coverage.txt --type=extension --github-output --verbose
# Run webview tests with coverage
- name: Webview Tests with Coverage
id: webview_tests
id: webview_coverage
continue-on-error: true
run: |
cd webview-ui
npm run test:coverage
- name: Check Test Results
if: always()
run: |
failed=""
[[ "${{ steps.unit_tests_linux.outcome }}" == "failure" && "${{ runner.os }}" == "Linux" ]] && failed="$failed unit_tests_linux"
[[ "${{ steps.unit_tests_non_linux.outcome }}" == "failure" && "${{ runner.os }}" != "Linux" ]] && failed="$failed unit_tests_non_linux"
[[ "${{ steps.integration_tests_linux.outcome }}" == "failure" && "${{ runner.os }}" == "Linux" ]] && failed="$failed integration_tests_linux"
[[ "${{ steps.integration_tests_non_linux.outcome }}" == "failure" && "${{ runner.os }}" != "Linux" ]] && failed="$failed integration_tests_non_linux"
[[ "${{ steps.webview_tests.outcome }}" == "failure" ]] && failed="$failed webview_tests"
[[ -n "$failed" ]] && { echo "❌ The following test suites failed:$failed"; exit 1; }
echo "✅ All tests passed"
# Ensure coverage dependency is installed
npm install --no-save @vitest/coverage-v8
npm run test:coverage 2>&1 | tee webview_coverage.txt
cd ..
# Default the encoding to UTF-8 - It's not the default on Windows
PYTHONUTF8=1 PYTHONPATH=.github/scripts python -m coverage_check extract-coverage webview-ui/webview_coverage.txt --type=webview --github-output --verbose
# Save coverage reports as artifacts (workflow-scoped)
- name: Save Coverage Reports
uses: actions/upload-artifact@v4
# Only upload artifacts on Linux - We only need coverage from one OS
@@ -157,21 +123,52 @@ jobs:
with:
name: pr-coverage-reports
path: |
coverage-unit/lcov.info
webview-ui/coverage/lcov.info
extension_coverage.txt
webview-ui/webview_coverage.txt
test-platform-integration:
needs: quality-checks
# Set the check as failed if any of the tests failed
- name: Check for test failures
run: |
# Check if any of the test steps failed
# https://docs.github.com/en/actions/writing-workflows/choosing-what-your-workflow-does/accessing-contextual-information-about-workflow-runs#steps-context
if [ "${{ steps.extension_coverage.outcome }}" != "success" ]; then
echo "Extension Integration Tests failed, see previous step for test output."
fi
if [ "${{ steps.webview_coverage.outcome }}" != "success" ]; then
echo "Webview Tests failed, see previous step for test output."
fi
if [ "${{ steps.extension_coverage.outcome }}" != "success" ] || [ "${{ steps.webview_coverage.outcome }}" != "success" ]; then
exit 1
fi
coverage:
needs: test
runs-on: ubuntu-latest
# Only run on PRs to main branch
if: github.event_name == 'pull_request' && github.base_ref == 'main'
steps:
- name: Checkout code
uses: actions/checkout@v4
with:
fetch-depth: 0 # Fetch all history for accurate comparison
# Setup Python for coverage script
- name: Setup Python
uses: actions/setup-python@v4
with:
python-version: "3.10"
- name: Install Python dependencies
run: |
python -m pip install --upgrade pip
pip install requests
- name: Setup Node.js environment
uses: actions/setup-node@v4
with:
node-version: 22
# Cache root dependencies - only reuse if package-lock.json exactly matches
- name: Cache root dependencies
uses: actions/cache@v4
id: root-cache
@@ -179,6 +176,7 @@ jobs:
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
@@ -186,14 +184,6 @@ jobs:
path: webview-ui/node_modules
key: ${{ runner.os }}-npm-webview-${{ hashFiles('webview-ui/package-lock.json') }}
# Cache testing-platform dependencies
- name: Cache testing-platform dependencies
uses: actions/cache@v4
id: testing-platform-cache
with:
path: testing-platform/node_modules
key: ${{ runner.os }}-npm-testing-platform-${{ hashFiles('testing-platform/package-lock.json') }}
- name: Install root dependencies
if: steps.root-cache.outputs.cache-hit != 'true'
run: npm ci
@@ -202,70 +192,30 @@ jobs:
if: steps.webview-cache.outputs.cache-hit != 'true'
run: cd webview-ui && npm ci
- name: Compile standalone
run: npm run compile-standalone
# Build the extension before running tests
- name: Build Extension
run: npm run compile
- name: Install testing platform dependencies
if: steps.testing-platform-cache.outputs.cache-hit != 'true'
run: cd testing-platform && npm ci
- name: Running testing platform integration spec tests
continue-on-error: true
timeout-minutes: 7
# Temporarily wrapping the test command to always return a neutral exit code.
# This prevents the job from showing as failed and avoids distracting developers
# until the integration tests are ready to be enforced.
run: |
npm run test:tp-orchestrator -- tests/specs/ --count=1 --coverage || true
- name: Save Coverage Reports
uses: actions/upload-artifact@v4
with:
name: test-platform-integration-core-coverage
path: coverage/**/lcov.info
qlty:
needs: [test, test-platform-integration]
runs-on: ubuntu-latest
# Run on PRs to main, pushes to main, and manual dispatches
steps:
- name: Checkout code
uses: actions/checkout@v4
- name: Download unit tests coverage reports
# Download coverage artifacts from test job
- name: Download Coverage Reports
uses: actions/download-artifact@v4
with:
name: pr-coverage-reports
path: .
path: . # Download to root directory to match expected paths
- name: Upload core unit tests coverage to Qlty
uses: qltysh/qlty-action/coverage@v2
with:
token: ${{ secrets.QLTY_COVERAGE_TOKEN }}
# we can merge multiple files if necessary
files: |
coverage-unit/lcov.info
tag: unit:core
# Process coverage workflow
- name: Process coverage workflow
id: coverage
run: |
# Extract PR number from GITHUB_REF
PR_NUMBER=$(echo "$GITHUB_REF" | sed -e 's/refs\/pull\///' -e 's/\/merge//')
- name: Upload webview-ui unit tests coverage to Qlty
uses: qltysh/qlty-action/coverage@v2
with:
token: ${{ secrets.QLTY_COVERAGE_TOKEN }}
# we can merge multiple files if necessary
files: |
webview-ui/coverage/lcov.info
tag: unit:webview-ui
add-prefix: webview-ui/
- name: Download test platform integration core coverage artifact
uses: actions/download-artifact@v4
with:
name: test-platform-integration-core-coverage
path: integration-core-coverage-reports
- name: Upload core integration tests coverage to Qlty
uses: qltysh/qlty-action/coverage@v2
with:
token: ${{ secrets.QLTY_COVERAGE_TOKEN }}
files: integration-core-coverage-reports/**/lcov.info
tag: integration:core
# Run the coverage workflow from root directory
PYTHONPATH=.github/scripts python -m coverage_check process-workflow \
--base-branch ${{ github.base_ref }} \
--pr-number $PR_NUMBER \
--repo $GITHUB_REPOSITORY \
--token ${{ secrets.GITHUB_TOKEN }} \
--verbose
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
@@ -1,53 +0,0 @@
name: Trigger Jetbrains Plugin <-> Cline Tests
on:
pull_request:
types: [opened, synchronize, reopened]
permissions:
contents: read
concurrency:
group: jetbrains-trigger-${{ github.event.number }}
cancel-in-progress: true
jobs:
trigger-integration-test:
name: Run Tests
runs-on: ubuntu-latest
steps:
- name: Generate GitHub App Token
id: app-token
uses: actions/create-github-app-token@v1
with:
app-id: 1998650
private-key: ${{ secrets.CLINE_JETBRAINS_WORKFLOW_KEY }}
owner: cline
repositories: intellij-plugin
- name: Trigger IntelliJ Plugin Integration Test
run: |
curl -X POST \
-H "Authorization: Bearer ${{ steps.app-token.outputs.token }}" \
-H "Accept: application/vnd.github.v3+json" \
-H "User-Agent: cline-pr-trigger" \
-H "Content-Type: application/json" \
https://api.github.com/repos/cline/intellij-plugin/dispatches \
-d @- <<EOF
{
"event_type": "cline-pr-check",
"client_payload": {
"pr_number": "${{ github.event.number }}",
"branch_name": "${{ github.head_ref }}",
"action": "${{ github.event.action }}",
"sha": "${{ github.event.pull_request.head.sha }}",
"pr_title": ${{ toJSON(github.event.pull_request.title) }},
"pr_url": "${{ github.event.pull_request.html_url }}"
}
}
EOF
- name: Log trigger details
run: |
echo "Triggered IntelliJ Plugin integration test for:"
echo " PR #${{ github.event.number }}: ${{ github.event.pull_request.title }}"
echo " Branch: ${{ github.head_ref }}"
echo " Action: ${{ github.event.action }}"
echo " SHA: ${{ github.event.pull_request.head.sha }}"
-2
View File
@@ -20,8 +20,6 @@ webview-ui/src/**/*.js.map
# Ignore coverage directories and files
coverage
coverage-unit
.nyc_output
# But don't ignore the coverage scripts in .github/scripts/
!.github/scripts/coverage/
+1 -1
View File
@@ -1 +1 @@
lint-staged
lint-staged --no-stash
-48
View File
@@ -1,48 +0,0 @@
{
"all": true,
"check-coverage": false,
"reporter": [
"text",
"lcov"
],
"include": [
"src/**/*.ts"
],
"exclude": [
"**/*.d.ts",
"**/*.{test,spec}.{js,jsx,ts,tsx,mjs,cjs}",
"**/__tests__/**",
"**/test/**",
"**/tests/**",
"**/.nyc_output/**",
"**/.vscode-test/**",
"**/tests-results/**",
"src/test/**",
"src/generated/**",
"**/node_modules/**",
"**/dist/**",
"**/out/**",
"**/build/**",
"**/coverage/**",
"**/coverage-unit/**",
"**/proto/**",
"**/*.{config,setup}.{js,ts,mjs,cjs}",
"**/vite-env.d.ts",
"**/*.{css,scss,sass,less,styl}",
"**/*.{svg,png,jpg,jpeg,gif,ico}",
"**/*.{json,yaml,yml}"
],
"extension": [
".ts",
".js"
],
"cache": true,
"sourceMap": true,
"instrument": true,
"report-dir": "./coverage-unit"
}
+8 -55
View File
@@ -12,7 +12,6 @@
"args": [
"--extensionDevelopmentPath=${workspaceFolder}",
"--disable-workspace-trust",
"--disable-extensions", // Avoid conflicts with installed extensions
"${workspaceFolder}"
],
"outFiles": [
@@ -32,7 +31,6 @@
"args": [
"--extensionDevelopmentPath=${workspaceFolder}",
"--disable-workspace-trust",
"--disable-extensions", // Avoid conflicts with installed extensions
"${workspaceFolder}"
],
"outFiles": [
@@ -52,7 +50,6 @@
"args": [
"--extensionDevelopmentPath=${workspaceFolder}",
"--disable-workspace-trust",
"--disable-extensions", // Avoid conflicts with installed extensions
"${workspaceFolder}"
],
"outFiles": [
@@ -74,7 +71,7 @@
"--user-data-dir=${workspaceFolder}/dist/tmp/user",
"--profile-temp",
"--sync=off",
"--disable-extensions", // Avoid conflicts with installed extensions
"--disable-extensions",
"--extensionDevelopmentPath=${workspaceFolder}",
"${workspaceFolder}"
],
@@ -94,7 +91,7 @@
{
"type": "node",
"request": "launch",
"name": "Debug Test Standalone Core Api Server (test:sca-server)",
"name": "Run cline-core service",
"skipFiles": [
"<node_internals>/**"
],
@@ -103,62 +100,18 @@
"${workspaceFolder}/**",
"!**/node_modules/**"
],
"cwd": "${workspaceFolder}",
"cwd": "${workspaceFolder}/dist-standalone",
"outFiles": [
"${workspaceFolder}/dist/**/*.js",
"${workspaceFolder}/dist-standalone/**/*.js"
],
"preLaunchTask": "compile-standalone",
"runtimeExecutable": "npx",
"runtimeArgs": [
"tsx"
],
"program": "scripts/test-standalone-core-api-server.ts",
"env": {
"PROTOBUS_PORT": "26040",
"HOSTBRIDGE_PORT": "26041",
"WORKSPACE_DIR": "${workspaceFolder}",
"E2E_TEST": "true",
"CLINE_ENVIRONMENT": "local"
// Turns on grpc debug log.
//"GRPC_TRACE": "all",
//"GRPC_VERBOSITY": "DEBUG",
"NODE_PATH": "${workspaceFolder}/dist-standalone/node_modules"
},
"console": "integratedTerminal",
"internalConsoleOptions": "neverOpen"
},
{
"type": "node",
"request": "launch",
"name": "Debug Current Test File",
"skipFiles": [
"<node_internals>/**"
],
"sourceMaps": true,
"resolveSourceMapLocations": [
"${workspaceFolder}/**",
"!**/node_modules/**"
],
"cwd": "${workspaceFolder}",
"runtimeExecutable": "npx",
"runtimeArgs": [
"mocha"
],
"args": [
"--require",
"ts-node/register",
"--require",
"source-map-support/register",
"--require",
"./src/test/requires.ts",
"--exit",
"${file}"
],
"env": {
"TS_NODE_PROJECT": "./tsconfig.unit-test.json",
"NODE_ENV": "test",
"IS_DEV": "true",
"CLINE_ENVIRONMENT": "local"
},
"console": "integratedTerminal",
"internalConsoleOptions": "openOnSessionStart"
"program": "cline-core.js"
}
]
}
+11 -6
View File
@@ -21,11 +21,16 @@
},
// Enable Lint and format using Biome
"biome.enabled": true,
"editor.defaultFormatter": "biomejs.biome",
"editor.codeActionsOnSave": {
"source.fixAll.biome": "explicit",
"source.removeUnused.biome": "always",
"source.removeUnusedImports": "always",
"source.organizeImports.biome": "always"
"[typescript]": {
"editor.defaultFormatter": "biomejs.biome"
},
"[typescriptreact]": {
"editor.defaultFormatter": "biomejs.biome"
},
"[jsonc]": {
"editor.defaultFormatter": "biomejs.biome"
},
"[json]": {
"editor.defaultFormatter": "biomejs.biome"
}
}
-6
View File
@@ -64,9 +64,3 @@ old_docs/**
e2e-build.mjs
e2e.vsix
test-results/
# Ignore Storybook files
**/*.stories.tsx
*storybook.log
storybook-static
**/StorybookDecorator.tsx
-129
View File
@@ -1,134 +1,5 @@
# Changelog
## [3.32.5]
- Improve thinking budget slider UI to take up less space
- Fix Vercel provider cost note and sign-up url
- Fix repeated API error 400 in SAP AI Core provider
- Add us-west-1 to Amazon Bedrock regions
- Fix OCA provider refresh logic
## [3.32.4]
- Add 1m context window support to Claude Sonnet 4.5
- Add Claude Sonnet 4.5 to GCP Vertex
- Add prompt caching support for OpenRouter accidental `anthropic/claude-4.5-sonnet` model ID
## [3.32.3]
- Add Claude Sonnet 4.5 to Bedrock provider
- Add Alert banner for new Claude Sonnet 4.5 model
## [3.32.2]
- Add Claude Sonnet 4.5 to Cline/OpenRouter/Anthropic providers
- Add /task deep link handler
## [3.32.1]
- Preserve reasoning traces for Cline/OpenRouter/Anthropic providers to maintain conversation integrity
- Add automatically retry on rate limit errors with SAP AI Core provider
- Fix Cline accounts using stale id token at refresh response
- Minor UI improvements to Settings and Task Header
## [3.32.0]
- Added the new code-supernova-1-million stealth model, available for free and delivering a 1 million token context window
- Changes to inform Cline about commands that are available on your system
## [3.31.1]
- Version bump
## [3.31.0]
- UI Improvements: New task header and focus chain design to take up less space for a cleaner experience
- Voice Mode: Experimental feature that must be enabled in settings for hands-free coding
- YOLO Mode: Enable in settings to let Cline approve all actions and automatically switch between plan/act mode
- Fix Oracle Code Assist provider issues
## [3.30.3]
- Add Oracle Code Assist provider
## [3.30.2]
- Fix UI tests
## [3.30.1]
- Fix model list not being updated in time for user to use shortcut button to update model to stealth model
- Fix flicker issue when switching modes
- Fix Sticky header in settings view overlaping with content on scroll
- Add experimental yolo mode feature that disables all user approvals and automatically executes a task and navigates through plan to act mode until the task is complete
## [3.30.0]
- Add code-supernova stealth model
## [3.29.2]
- Fix: Reverted change that caused formatting issues
- Fix: Moonshot - Pass max_tokens value to provider
## [3.29.1]
- Changeset bump + Announcement banner update
## [3.29.0]
- Updated Baseten provider to fetch models from server
- Fix: Updated insufficient balance URL for easy Cline balance top-ups
- Accessibility: Improvements to screen readers in MCP, Cline Rules, workflows, and history views.
## [3.28.4]
- Fix bug where some Windows machines had API request hanging
- Fix bug where 'Proceed while running' action button would be disabled after running an interactive command
- Fix prompt cache info not being displayed in History
## [3.28.3]
- Fixed issue with start new task button
- Feature to generate commit message for staged changes, with unstaged as fallback
## [3.28.2]
- Fix for focus chain settings
## [3.28.1]
- Requesty: use base URL to get models and API keys
- Removed focus chain feature flag
## [3.28.0]
- Synchronized Task History: Real-time task history synchronization across all Cline instances
- Optimized GPT-5 Integration: Fine-tuned system prompts for improved performance with GPT-5 model family
- Deep Planning Improvements: Optimized prompts for Windows/PowerShell environments and dependency exclusion
- Streamlined UI Experience: ESC key navigation, cleaner approve/reject buttons, and improved editor panel focus
- Smart Provider Search: Improved search functionality in API provider dropdown for faster model selection
- Added per-provider thinking tokens configurability
- Added Ollama custom prompt options
- Enhanced SAP AI Core Provider: Orchestration mode support and improved model visibility
- Added Dify.ai API Integration
- SambaNova Updates: Added DeepSeek-V3.1 model
- Better Gemini rate limit handling
- OpenAI Reasoning Effort: Minimal reasoning effort configuration for OpenAI models
- Fixed LiteLLM Caching: Anthropic caching compatibility when using LiteLLM
- Fixed Ollama default endpoint connections
- Fixed AutoApprove menu overflow
- Fixed extended thinking token issue with Anthropic models
- Fixed issue with slash commands removing text from prompt
## [3.27.2]
- Remove `grok-code-fast-1` promotion deadline
## [3.27.1]
- Add new Kimi K2 model to groq and moonshot providers
## [3.27.0]
- Fix `grok-code-fast-1` model information
+1 -30
View File
@@ -74,6 +74,7 @@ We also welcome contributions to our [documentation](https://github.com/cline/cl
4. Testing
- Run `npm run test` to run tests locally.
- Before submitting PR, run `npm run format:fix` to format your code
- Run `npm run test:ci` to run tests locally
### Extension
@@ -156,36 +157,6 @@ 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
**End-to-End (E2E) Testing**
Cline includes comprehensive E2E tests using Playwright that simulate real user interactions with the extension in VS Code:
- **Running E2E tests:**
```bash
npm run test:e2e # Build and run all E2E tests
npm run e2e # Run tests without rebuilding
npm run test:e2e -- --debug # Run with interactive debugger
```
- **Writing E2E tests:**
- Tests are located in `src/test/e2e/`
- Use the `e2e` fixture for single-root workspace tests
- Use `e2eMultiRoot` fixture for multi-root workspace tests
- Follow existing patterns in `auth.test.ts`, `chat.test.ts`, `diff.test.ts`, and `editor.test.ts`
- See `src/test/e2e/README.md` for detailed documentation
- **Debug mode features:**
- Interactive Playwright Inspector for step-by-step debugging
- Record new interactions and generate test code automatically
- Visual VS Code instance for manual testing
- Element inspection and selector validation
- **Test environment:**
- Automated VS Code setup with Cline extension loaded
- Mock API server for backend testing
- Temporary workspaces with test fixtures
- Video recording for failed tests
4. **Version Management with Changesets**
- Create a changeset for any user-facing changes using `npm run changeset`
+2 -9
View File
@@ -123,8 +123,7 @@
"!**/node_modules/**",
"!**/webview-ui/build/**",
"!**/generated/**",
"!**/proto/**",
"!**/tests/specs/**"
"!**/proto/**"
]
},
"plugins": [
@@ -136,12 +135,7 @@
"**",
"!**/hosts/vscode/**",
"!**/test/**",
"!**/*.test.ts",
"!src/dev/**",
"!src/extension.ts",
"!src/integrations/git/commit-message-generator.ts",
"!src/integrations/terminal/**",
"!src/core/controller/ui/openWalkthrough.ts"
"!src/extension.ts"
],
"plugins": [
"src/dev/grit/vscode-api.grit"
@@ -154,7 +148,6 @@
"!src/core/storage/FileContextTracker.ts",
"!src/core/context/context-tracking/FileContextTracker.ts",
"!src/common.ts",
"!src/services/logging/distinctId.ts",
"!src/core/storage/utils/state-helpers.ts",
"!src/extension.ts"
],
+25 -40
View File
@@ -25,15 +25,15 @@
},
"styling": {
"eyebrows": "breadcrumbs",
"codeblocks": "system",
"css": "styles.css"
"codeblocks": "system"
},
"appearance": {
"default": "system",
"strict": false
},
"fonts": {
"family": "Roboto"
"family": "Roboto",
"weight": 400
},
"navbar": {
"links": [
@@ -58,8 +58,9 @@
"group": "Getting Started",
"pages": [
"getting-started/what-is-cline",
"getting-started/installing-cline",
"getting-started/model-selection-guide",
"getting-started/installing-cline",
"getting-started/installing-cline-jetbrains",
"getting-started/task-management",
"getting-started/understanding-context-management",
{
@@ -81,6 +82,15 @@
{
"group": "Features",
"pages": [
"features/auto-approve",
"features/checkpoints",
"features/cline-rules",
"features/drag-and-drop",
"features/plan-and-act",
"features/slash-commands/workflows",
"features/focus-chain",
"features/auto-compact",
"features/editing-messages",
{
"group": "@ Mentions",
"pages": [
@@ -92,32 +102,6 @@
"features/at-mentions/url-mentions"
]
},
"features/auto-approve",
"features/auto-compact",
"features/checkpoints",
"features/cline-rules",
{
"group": "Commands & Shortcuts",
"pages": [
"features/commands-and-shortcuts/overview",
"features/commands-and-shortcuts/code-commands",
"features/commands-and-shortcuts/terminal-integration",
"features/commands-and-shortcuts/git-integration",
"features/commands-and-shortcuts/keyboard-shortcuts"
]
},
{
"group": "Customization",
"pages": [
"features/customization/opening-cline-in-sidebar",
"features/customization/disable-terminal-pagers"
]
},
"features/dictation",
"features/drag-and-drop",
"features/editing-messages",
"features/focus-chain",
"features/plan-and-act",
{
"group": "Slash Commands",
"pages": [
@@ -128,8 +112,16 @@
"features/slash-commands/deep-planning"
]
},
"features/slash-commands/workflows",
"features/yolo-mode"
{
"group": "Commands & Shortcuts",
"pages": [
"features/commands-and-shortcuts/overview",
"features/commands-and-shortcuts/code-commands",
"features/commands-and-shortcuts/terminal-integration",
"features/commands-and-shortcuts/git-integration",
"features/commands-and-shortcuts/keyboard-shortcuts"
]
}
]
},
{
@@ -191,8 +183,7 @@
"provider-config/openrouter",
"provider-config/sap-aicore",
"provider-config/vercel-ai-gateway",
"provider-config/requesty",
"provider-config/baseten"
"provider-config/requesty"
]
},
{
@@ -232,12 +223,6 @@
"url": "getting-started/what-is-cline"
}
],
"redirects": [
{
"source": "/getting-started/installing-cline-jetbrains",
"destination": "/getting-started/installing-cline"
}
],
"search": {
"prompt": "Search Cline documentation..."
},
@@ -56,7 +56,7 @@ Cline is your AI assistant that can:
## 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/prompts/system-prompt/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:
@@ -21,6 +21,7 @@ While Cline has only a few default keyboard shortcuts, you can assign your own s
| Command ID | Description |
| ---------------------------------------------------------------------------------------- | --------------------------------------------- |
| [`cline.openInNewTab`](/features/commands-and-shortcuts/overview) | Opens Cline in a new editor tab |
| [`cline.addToChat`](/features/commands-and-shortcuts/code-commands) | Adds selected code to Cline chat |
| [`cline.addTerminalOutputToChat`](/features/commands-and-shortcuts/terminal-integration) | Adds terminal output to Cline |
| `cline.focusChatInput` | Focuses the Cline chat input field |
@@ -1,79 +0,0 @@
---
title: "Disable Terminal Pagers During Cline Sessions"
description: "Make CLI output non-interactive when Cline runs commands by detecting the CLINE_ACTIVE environment variable and disabling pagers like less."
---
Many CLI tools (like Git) use a pager such as `less` for interactive, scrollable output. When Cline runs commands in your terminal, that interactivity gets in the way — the pager can pause on the first page and block progress. You can configure your shell so that when a terminal is spawned by Cline, pagers are disabled and output streams through normally.
## How it works
Cline sets an environment variable for terminals it opens to run commands:
- `CLINE_ACTIVE` — non-empty when the shell is running under Cline
You can detect this variable in your shell startup file and adjust environment variables or aliases only for Cline-run sessions. This keeps your normal interactive terminals unchanged.
## Quick setup (Zsh/Bash)
Add the following to your `~/.zshrc`, `~/.bashrc`, or `~/.bash_profile`:
```bash
# Disable pagers when the terminal is launched by Cline
if [[ -n "$CLINE_ACTIVE" ]]; then
export PAGER=cat
export GIT_PAGER=cat
export SYSTEMD_PAGER=cat
export LESS="-FRX"
fi
```
<Note>
- `PAGER=cat` ensures generic pager-aware tools print directly to stdout
- `GIT_PAGER=cat` prevents Git from invoking `less`
- `SYSTEMD_PAGER=cat` disables paging in systemd tools (if present)
- `LESS="-FRX"` makes `less` behave more like streaming output if a tool still calls it
</Note>
This configuration only applies when `CLINE_ACTIVE` is set, so your normal terminals keep their usual interactive behavior.
## Verify
- Open a task in Cline that runs terminal commands and check:
- `echo "$CLINE_ACTIVE"` prints a non-empty value
- `git log` or other long outputs should stream without pausing
- If changes don't take effect:
- Make sure you updated the correct startup file for your shell
- Restart VS Code/Cursor so integrated terminals reload your shell config
- Confirm your terminal profile sources your `~/.zshrc` or `~/.bashrc`
## Optional tweaks
- Prefer command-line options when you don't want to rely on env vars:
```bash
# One-off usage (no aliases)
git --no-pager log -n 50 --decorate --oneline
systemctl --no-pager status nginx
journalctl --no-pager -u nginx -n 200
less -FRX README.md
```
- You can also override paging via shell aliases scoped to Cline sessions using options rather than env vars:
```bash
if [[ -n "$CLINE_ACTIVE" ]]; then
# Make 'less' non-interactive by default
alias less='less -FRX'
# Disable paging for common tools via CLI flags
alias git='command git --no-pager'
alias systemctl='command systemctl --no-pager'
alias journalctl='command journalctl --no-pager'
fi
```
- If you prefer environment variables, many CLIs also respect a generic or tool-specific pager variable:
- Git: `GIT_PAGER=cat`
- Systemd: `SYSTEMD_PAGER=cat`
- Man pages: `MANPAGER=cat` (not typically needed for Cline-driven commands)
- Aliases affect the current interactive shell, while environment variables propagate to child processes. Choose the approach that best fits your workflow.
@@ -1,60 +0,0 @@
---
title: "Opening Cline in the Right Sidebar"
description: "Learn how to open Cline in the right sidebar in VS Code and Cursor"
---
By default, when you first install Cline, it appears in VS Code's left sidebar alongside your file explorer and other extensions. However, for a better coding experience, we recommend moving Cline to the right sidebar. This allows you to keep your project files visible in the left sidebar while chatting with Cline on the right, giving you full visibility of your codebase as Cline works on your project.
## VS Code
To open Cline in the right sidebar:
<Steps>
<Step title="Align Extension View">
Make sure your extension view is aligned vertically to the left
</Step>
<Step title="Open Right Side View">
Click the button that opens the right side panel in VS Code (typically used to open GitHub Copilot chat). Optionally use the `Option + CMD/Ctrl + B` shortcut.
</Step>
<Step title="Drag Cline Icon">
Drag the Cline icon over to the nav panel at the top of that right view
</Step>
</Steps>
<Frame>
<img
src="https://storage.googleapis.com/cline_public_images/vscode_right_view.gif"
alt="VS Code Right Sidebar Setup"
/>
</Frame>
## Cursor
To open Cline in the right sidebar:
<Steps>
<Step title="Align Extensions">
Cursor uses a horizontal activity bar by default to optimize space for the AI chat interface ([see here for details](https://cursor.com/docs/configuration/migrations/vscode#activity-bar-orientation)). To switch to vertical:
1. Open the Command Palette (`CMD/Ctrl + Shift + P`)
2. Search for "Preferences: Open Settings (UI)"
3. Search for `workbench.activityBar.orientation`
4. Set the value to `vertical`
5. Restart Cursor for the changes to take effect
</Step>
<Step title="Open Agent Panel">
Click the Cursor cube icon button that opens Cursor's agent (right side view panel)
</Step>
<Step title="Drag to Three Dots">
Drag the Cline icon directly onto the three dots button - it doesn't work if you just drag it to the top, it has to be the three dots
</Step>
</Steps>
<Frame>
<img
src="https://storage.googleapis.com/cline_public_images/cursor-side-bar.gif"
alt="Cursor Right Sidebar Setup"
/>
</Frame>
Once set up, Cline will load on the right side and you can use it as normal.
-149
View File
@@ -1,149 +0,0 @@
---
title: "Dictation"
description: "Communicate with Cline using your voice for faster, more natural AI collaboration"
---
Dictation transforms how you work with AI. Instead of typing out complex thoughts, you speak naturally and share your complete intent. This isn't just about speed - though voice is faster - it's about unlocking the kind of fluid collaboration that typing can't match.
## Why Voice Changes Everything
When you type, you edit yourself. You simplify complex ideas, skip context, and lose nuance. When you speak, you share everything on your mind - the full problem, the constraints, the edge cases you're worried about.
Use Dictation constantly in [Plan mode](/features/plan-and-act) for rapid back-and-forth discussions. Instead of typing careful, structured prompts, think about a problem. Cline asks clarifying questions, respond immediately, and iterate until having a solid plan.
The friction of typing was holding back real collaboration. Voice removes that friction.
## Getting Started
**Enable Dictation:**
1. Go to Settings → Features → Dictation
2. Toggle "Enable Dictation" on
3. Sign into your Cline account when prompted
4. Install FFmpeg if you haven't already (Cline will guide you)
Once enabled, you'll see a microphone button in the chat input area.
**Using Dictation:**
- Click the microphone button to start recording
- Speak naturally
- Click again to stop recording
- Wait for transcription to appear in the chat
<Tip>
Dictation works with any AI model you've configured. The transcription happens through Cline's service, but your conversation continues with whatever model you're using.
</Tip>
## System Requirements
Dictation uses FFmpeg to capture your voice across all platforms:
- **macOS**: FFmpeg (via Homebrew: `brew install ffmpeg`)
- **Linux**: FFmpeg (via apt: `sudo apt-get install ffmpeg`)
- **Windows**: FFmpeg (via winget: `winget install Gyan.FFmpeg`)
If you don't have FFmpeg installed, Cline will automatically detect this and prompt you to install it with a single click.
## Where Dictation Shines
### Plan Mode Conversations
Dictation is perfect for [Plan mode](/features/plan-and-act) discussions. Instead of carefully crafting prompts, you can:
- Dictate your entire problem context in one go
- Respond to Cline's questions immediately
- Iterate on ideas without typing friction
- Think out loud while Cline listens
Start a planning session by speaking for 2-3 minutes straight, explaining the full context of what you're trying to build, the constraints you're working with, and the specific challenges you're facing.
### Complex Problem Explanation
Some problems are hard to type out. When you're dealing with:
- Multi-step workflows with edge cases
- Integration challenges across multiple systems
- Performance issues with specific reproduction steps
- UI/UX problems that need detailed context
Speaking lets you explain the full situation naturally, including all the "oh, and also..." details that matter.
### Code Review and Debugging
When reviewing code or explaining bugs, voice lets you walk through your thought process:
- "This function looks fine, but I'm worried about what happens when..."
- "The issue might be in this section, or possibly this other area..."
- "I tried X and Y, but neither worked because..."
You can share your complete debugging journey instead of just the final question.
## Technical Requirements
**System Requirements:**
- FFmpeg installed on your system
- Active internet connection
- Cline account with transcription credits
**Audio Quality:**
- Records in WebM format with Opus codec
- Mono audio at 16kHz sample rate
- Optimized for voice recognition
**Privacy:**
- Audio recorded locally on your machine
- Only audio files sent for transcription
- No audio stored after transcription
- Temporary files automatically cleaned up
## Cost and Credits
Voice transcription costs $0.006 per minute through your Cline account. For most users, this works out to pennies per session.
A typical 5-minute planning conversation costs about 3 cents. Even heavy voice users rarely spend more than a few dollars per month.
<Note>
Pricing is experimental and may change as we refine the service.
</Note>
## Best Practices
**Speak Naturally**
Don't try to speak like you type. Use your normal conversational tone and don't worry about perfect grammar.
**Give Context First**
Start with the big picture, then drill down into specifics. "I'm building a React app that needs to handle real-time data, and I'm running into performance issues with the WebSocket connection..."
**Use Voice for Exploration**
Dictation is perfect for exploratory conversations where you're not sure exactly what you need. Start talking through the problem and let the conversation evolve.
**Combine with Text**
You don't have to use voice for everything. Use voice for complex explanations and context, then switch to text for quick follow-ups or code snippets.
## Troubleshooting
**Microphone Not Working**
- Check your IDE permissions for microphone access
- Ensure FFmpeg is properly installed
- Try refreshing VSCode/your editor
**Poor Transcription Quality**
- Speak clearly and at normal volume
- Reduce background noise if possible
- Check your microphone settings
**Connection Issues**
- Verify internet connection
- Check if firewall is blocking Cline's servers
- Try signing out and back into your Cline account
**Authentication Issues**
- Sign out and back into your Cline account if you see authentication errors
- Check that your account has sufficient transcription credits
- Verify your internet connection is stable
**Audio Recording Issues**
- Ensure FFmpeg is properly installed and accessible
- Check that your browser/IDE has microphone permissions
- Try restarting your editor if audio capture fails
## The Future of AI Collaboration
When you can speak your thoughts as fast as you think them, you stop self-editing. You share the full context, the edge cases, the "what if" scenarios that matter. This leads to better solutions and fewer back-and-forth clarifications.
-4
View File
@@ -24,10 +24,6 @@ Plan mode is where you and Cline figure out what you're trying to build and how
- Focuses on understanding requirements and creating a strategy
- Helps identify potential issues before you write a single line of code
<Tip>
Try [Dictation](/features/dictation) in Plan mode - instead of typing out complex requirements, you can speak naturally and share your complete thought process. It's perfect for rapid back-and-forth planning discussions.
</Tip>
#### Act Mode: Build It
Once you've got a plan, you switch to Act mode. Now Cline:
-83
View File
@@ -1,83 +0,0 @@
---
title: "YOLO Mode"
sidebarTitle: "YOLO Mode"
---
YOLO mode is exactly what it sounds like - Cline auto-approves everything. Check the box in feature settings and he'll execute file changes, terminal commands, even transitions from Plan to Act mode without asking.
Think of it as [Auto Approve](/features/auto-approve) on steroids - instead of granular permissions, YOLO mode gives Cline complete autonomy.
<Note>
**Warning: This is dangerous.** YOLO mode disables all safety checks. Cline will execute whatever he decides without asking permission.
</Note>
## What Gets Auto-Approved
When YOLO mode is enabled, Cline automatically approves:
- **All file operations** - reading, writing, and modifying files anywhere on your system
- **All terminal commands** - including potentially destructive operations
- **Browser actions** - web scraping, form submissions, navigation
- **MCP server tools** - external integrations and API calls
- **Mode transitions** - automatic switching from Plan to Act mode
Essentially, every safety guardrail is removed. Cline operates with complete autonomy.
## How to Enable YOLO Mode
Navigate to Cline Settings → Features and check the "YOLO Mode" box. That's it - no confirmation dialogs, no additional warnings. Once enabled, Cline will start auto-approving all actions immediately.
To disable it, simply uncheck the box. Any pending actions will still require your approval once YOLO mode is turned off.
## When You Might Use This
YOLO mode was built primarily for our upcoming scriptable CLI where fully autonomous execution makes sense. In the GUI, you might consider it for:
**Rapid prototyping** where you want zero friction and don't care about potential mistakes. Perfect for throwaway experiments or exploring new ideas quickly.
**Trusted, repetitive tasks** where you've already validated Cline's approach and want to eliminate approval overhead. Think routine refactoring or well-established patterns.
**Demonstration purposes** where you want to show Cline's capabilities without constant interruptions.
## What Could Go Wrong
Since YOLO mode removes all safety checks, Cline could:
- Delete important files without warning
- Execute commands that modify system settings
- Make network requests to external services
- Overwrite configuration files
- Install or uninstall software packages
- Commit and push changes to version control
The risk level depends entirely on what you ask Cline to do. Simple tasks remain relatively safe, but complex requests can have unpredictable consequences.
## Best Practices
If you decide to use YOLO mode:
**Start with isolated environments.** Use it in throwaway projects or sandboxed environments first. Never enable it on production codebases until you understand the risks.
**Be specific with requests.** Vague instructions combined with unlimited permissions can lead to unexpected results. The clearer your requirements, the more predictable Cline's actions.
**Monitor the output.** Even though Cline doesn't ask for permission, he still shows you what he's doing. Watch the terminal output and file changes as they happen.
**Keep version control handy.** Make sure you can easily revert changes if something goes wrong. Git becomes your safety net when YOLO mode is your workflow.
## Inspiration: What Becomes Possible
With YOLO mode enabled, you can:
**Build entire applications** from a single prompt. Describe what you want and let Cline handle everything - file creation, dependency installation, configuration setup, even deployment scripts.
**Automate complex workflows** that normally require dozens of approval clicks. Data processing pipelines, build system setup, or multi-step refactoring operations become seamless.
**Rapid iteration cycles** where you can quickly test ideas without approval friction. Perfect for exploring different approaches or experimenting with new technologies.
**Live demonstrations** where you can show Cline's full capabilities without stopping to approve every action. Great for presentations or teaching scenarios.
The key is understanding that YOLO mode transforms Cline from an interactive assistant into an autonomous agent. Use that power wisely.
---
Questions or feedback? Reach us in our [Discord](https://discord.gg/cline) or [r/cline](https://reddit.com/r/cline).
@@ -0,0 +1,135 @@
---
title: "Installing Cline for JetBrains"
description: "Get Cline running in your favorite JetBrains IDE with the same powerful AI assistance you know from VSCode."
---
<Frame>
<img
src="https://storage.googleapis.com/cline_public_images/docs/assets/jetbrains-logo.svg"
alt="JetBrains logo"
style={{ width: "200px", height: "auto", margin: "0 auto 20px auto", display: "block" }}
/>
</Frame>
Cline for JetBrains works almost identically to Cline in VSCode. All the core features work properly: diff editing, using tools, logging in with different providers, MCP servers, Cline rules and workflows, and more.
<Frame>
<img
src="https://storage.googleapis.com/cline_public_images/docs/assets/jetbrains-demo-hifi.gif"
alt="Cline running in JetBrains IDE showing AI assistance"
/>
</Frame>
<Note>Cline for JetBrains is currently in alpha. While all core features are functional, you may encounter occasional issues.</Note>
## Installation
Since Cline for JetBrains is currently in alpha, it's not yet available on the JetBrains Marketplace. You'll need to install it manually from a downloaded file:
### Manual Installation from Disk
1. **Download the Plugin:**
- Go to [https://plugins.jetbrains.com/plugin/28247-cline/versions/stable](https://plugins.jetbrains.com/plugin/28247-cline/versions/stable)
- Click **Download** to get the `.zip` file
<Frame>
<img
src="https://storage.googleapis.com/cline_public_images/docs/assets/cline-jetbrains-marketplace-download.png"
alt="JetBrains plugin marketplace showing Cline download page"
/>
</Frame>
2. **Install from Disk:**
- Open your JetBrains IDE
- Go to **IntelliJ IDEA** (or whichever IDE you are in) → **Settings**
<Frame>
<img
src="https://storage.googleapis.com/cline_public_images/docs/assets/cline-jetbrains-settings.png"
alt="JetBrains IDE settings dialog"
/>
</Frame>
- Select **Plugins** from the left sidebar
- Click the gear icon ⚙️ and select **Install Plugin from Disk...**
<Frame>
<img
src="https://storage.googleapis.com/cline_public_images/docs/assets/cline-jetbrains-install-disk.png"
alt="JetBrains IDE settings showing Install Plugin from Disk option"
/>
</Frame>
- Select the downloaded `.zip` file
<Frame>
<img
src="https://storage.googleapis.com/cline_public_images/docs/assets/cline-jetbrains-zip-file.png"
alt="File selection dialog showing Cline plugin zip file"
/>
</Frame>
- Restart your IDE when prompted
## Getting Started with Cline
After installation, you'll find Cline in your IDE:
1. **Open Cline:**
- Look for the Cline tool window (usually on the right side)
- Or go to **View** → **Tool Windows** → **Cline**
2. **Sign In (optional, BYOK is also available):**
- Click **Sign In** in the Cline panel
- You'll be taken to [app.cline.bot](https://app.cline.bot) to create your account
- No credit card needed to get started with free credits
3. **Start Coding:**
- Try this first prompt: "Hey Cline! Can you help me create a simple Hello World program in this project?"
## Key Differences from VSCode
While Cline for JetBrains includes all the same powerful features, there's one important difference to be aware of:
**Terminal Integration:** The terminal inside JetBrains isn't integrated with Cline the same way it is in VSCode. Cline can execute commands, but the output will only appear in the webview if you expand the **Command Output** section.
This means:
- Commands still run successfully
- You can see the output by clicking to expand Command Output in the chat
- Terminal commands work the same way, just with a different display
## What Works
Everything else works exactly like VSCode:
- **Diff Editing:** Cline can read, write, and edit files with the same precision
- **Tool Usage:** All of Cline's tools (file operations, web browsing, etc.) work identically
- **API Providers:** Connect to Anthropic, OpenAI, local models, and more
- **MCP Servers:** Full support for Model Context Protocol servers
- **Cline Rules:** Custom instructions and workflows work the same way
- **@ Mentions:** Reference files, folders, problems, and more
- **Drag & Drop:** Add files and images to conversations
## Tips for JetBrains Users
- **Project Context:** Cline automatically understands your project structure, just like in VSCode
- **Language Support:** Cline works with any language your JetBrains IDE supports
- **Debugging Help:** Share error messages and stack traces directly in the chat
- **Code Review:** Ask Cline to review your code changes before committing
## Troubleshooting
If you don't see the Cline tool window after installation:
- Restart your IDE completely
- Check **View** → **Tool Windows** → **Cline**
- Ensure the plugin is enabled in **Settings** → **Plugins**
Having other issues? Join our [Discord community](https://discord.gg/cline) for help from the team and other users.
## Next Steps
Now that you have Cline installed, you might want to:
- Learn about [model selection](/getting-started/model-selection-guide) to choose the best AI provider
- Explore [@ mentions](/features/at-mentions/overview) to reference files and context efficiently
- Set up [Cline rules](/features/cline-rules) for your specific workflow
- Try [MCP servers](/mcp/mcp-overview) to extend Cline's capabilities
+44 -233
View File
@@ -1,254 +1,65 @@
---
title: "Installing Cline"
description: "Get Cline set up in your editor and start building projects with AI assistance."
description: "Cline is a VS Code extension that brings AI-powered coding assistance directly
to your editor. Install using one of these methods:"
---
## Prerequisites
### Installation Options
Before installing Cline, make sure you have the following:
- **VS Code Marketplace (Recommended):** Fastest method for standard VS Code and Cursor users.
- **Open VSX Registry:** For VS Code-compatible editors like VSCodium.
### Create a Cline Account
### VS Code Marketplace: Step-by-Step Setup
Create a Cline account for the best experience. Creating a Cline account is completely free and you can [sign up here](https://app.cline.bot/signup). A Cline account provides:
- Access to multiple AI models including stealth models
- Seamless setup without needing to manage API keys
- At times, we partner with model providers to offer inferencing at no cost through your Cline account
Follow these steps to get Cline up and running:
### Compatible Editor
1. **Open VS Code:** Launch the VS Code application.
Cline works with the following IDEs:
- **VS Code** - Microsoft's popular code editor
- **Cursor** - AI-powered code editor based on VS Code
- **JetBrains IDEs** - IntelliJ IDEA, PyCharm, WebStorm, DataSpell, PhpStorm, and other JetBrains products
- **VSCodium** - Open-source version of VS Code
- **Windsurf** - VS Code-compatible editor
> **Note:** If VS Code shows "Running extensions might...", click "Allow".
Make sure you have one of these editors installed before proceeding with the Cline installation.
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 (`Ctrl + Shift + X` or `Cmd + Shift + X`).
4. **Search for 'Cline':** In the Extensions search bar, type `Cline`.
## Choose Your Editor
<Frame caption="VS Code marketplace with Cline extension ready to install">
<img
src="https://storage.googleapis.com/cline_public_images/docs/assets/image%20(20).png"
alt="VS Code marketplace showing Cline extension"
/>
</Frame>
Cline works across multiple IDEs. Select your preferred editor below for installation instructions:
1. **Install the Extension:** Click the "Install" button next to the Cline extension.
2. **Open Cline:**
- Click the Cline icon in the Activity Bar.
- Or, use the command palette (`Ctrl/Cmd + Shift + P`) and type "Cline: Open In New Tab" for a better view.
3. **Troubleshooting:** If you don't see the Cline icon, try restarting VS Code.
<Tabs>
<Tab title="VS Code/Cursor" icon="code">
### Installation Steps
> **Pro Tip:** You should see the Cline chat window appear in your VS Code editor!
1. **Open VS Code** and navigate to the Extensions view (`Ctrl/Cmd + Shift + X`)
2. **Search for "Cline"** in the Extensions marketplace
3. **Click Install** on the Cline extension
### Open VSX Registry
<Frame caption="VS Code marketplace with Cline extension ready to install">
<img
src="https://storage.googleapis.com/cline_public_images/docs/assets/image%20(20).png"
alt="VS Code marketplace showing Cline extension"
/>
</Frame>
For VS Code-compatible editors without Marketplace access (like VSCodium and Windsurf):
4. **Access Cline** after installation:
- Click the Cline icon in the Activity Bar, or
- Use Command Palette (`Ctrl/Cmd + Shift + P`) → "Cline: Open In New Tab"
1. Open your editor.
2. Access the Extensions view.
3. Search for "Cline".
4. Select "Cline" by saoudrizwan and click **Install**.
5. Reload if prompted.
> **Note:** If VS Code shows "Running extensions might..." dialog, click "Allow". If you don't see the Cline icon, restart VS Code.
### Creating Your Cline Account
<Accordion title="Troubleshooting">
**Plugin Installation Issues**
If you can't find Cline in the marketplace:
- Make sure you're searching in the **Marketplace** tab (not Installed)
- Try searching for "Cline AI" or just "Cline"
- Check that your VS Code version is compatible
If installation fails:
- Restart your VS Code and try again
- Check your internet connection
- Try installing from VSIX file as an alternative
**Plugin Not Appearing**
If you don't see the Cline tool window after installation:
- Restart VS Code completely (File → Exit and reopen)
- Check **View** → **Command Palette** → "Cline: Open In New Tab"
- Verify the plugin is enabled in **Extensions** view
- Look for the Cline icon in your Activity Bar (usually on the left side)
**Common Issues**
Plugin appears to be installed but doesn't work:
- Ensure you've restarted VS Code after installation
- Check if there are any error messages in the Developer Console
- Try disabling and re-enabling the extension
Performance or compatibility issues:
- Make sure you're using a supported VS Code version
- Check for VS Code updates that might improve compatibility
- Consider closing other resource-intensive extensions if needed
Need help? Join our [Discord community](https://discord.gg/cline).
</Accordion>
</Tab>
<Tab title="JetBrains IDEs" icon="brain">
<img
src="https://storage.googleapis.com/cline_public_images/docs/assets/jetbrains-logo.svg"
alt="JetBrains logo"
style={{ width: "200px", height: "auto", margin: "0 auto 20px auto", display: "block" }}
/>
Cline for JetBrains works almost identically to Cline in VSCode. All the core features work properly: diff editing, using tools, logging in with different providers, MCP servers, Cline rules and workflows, and more.
### Installation Steps
**Method 1: From IDE (Recommended)**
1. Open your JetBrains IDE
2. Go to **Settings** (`Ctrl+Alt+S` on Windows/Linux, `Cmd+,` on macOS)
3. Navigate to **Plugins** → **Marketplace**
4. Search for "Cline" and click **Install**
5. Restart your IDE
<Frame>
<img
src="https://storage.googleapis.com/cline_public_images/docs/assets/cline-jetbrains-marketplace-search.png"
alt="JetBrains marketplace showing Cline plugin search results"
/>
</Frame>
**Method 2: Browser Install**
Visit the [JetBrains Marketplace](https://plugins.jetbrains.com/plugin/28247-cline) and click **Install to IDE**.
<Accordion title="Method 3: Manual Installation">
1. Download the plugin from the [marketplace page](https://plugins.jetbrains.com/plugin/28247-cline)
2. Go to **Settings** → **Plugins**
3. Click the gear icon → **Install Plugin from Disk**
4. Select the downloaded `.zip` file
5. Restart your IDE
</Accordion>
### Using the Plugin
After installation, youll find Cline in your IDE. Look for the Cline tool window (usually on the right side) or go to View → Tool Windows → Cline.
### Key Features
Cline for JetBrains includes all core features:
- Diff editing and file modifications
- Multiple API providers (Anthropic, OpenAI, local models)
- MCP servers and custom tools
- Cline rules and workflows
- @ mentions for files, folders, and problems
- Drag & drop support
> **Note:** Terminal output appears in collapsible sections rather than streaming directly to chat.
### Key Differences from VSCode
The terminal integration works differently in JetBrains. Unlike VSCode where terminal output streams directly to the chat, JetBrains shows command output in a collapsible section. Commands still execute successfully - you just need to expand the Command Output section to see results.
<Accordion title="Troubleshooting">
**Plugin Installation Issues**
If you can't find Cline in the marketplace:
- Make sure you're searching in the **Marketplace** tab (not Installed)
- Try searching for "Cline AI" or just "Cline"
- Check that your IDE version is compatible (2023.1 or later recommended)
If installation fails:
- Restart your IDE and try again
- Check your internet connection
- Try installing from disk as an alternative
**Plugin Not Appearing**
If you don't see the Cline tool window after installation:
- Restart your IDE completely (File → Exit and reopen)
- Check **View** → **Tool Windows** → **Cline**
- Verify the plugin is enabled in **Settings** → **Plugins** → **Installed** tab
- Look for the Cline icon in your IDE's tool window bar (usually on the right side)
**Common Issues**
Plugin appears to be installed but doesn't work:
- Ensure you've restarted your IDE after installation
- Check if there are any error messages in the IDE's event log
- Try disabling and re-enabling the plugin in Settings
Performance or compatibility issues:
- Make sure you're using a supported JetBrains IDE version
- Check for IDE updates that might improve compatibility
- Consider allocating more memory to your IDE if needed
Need help? Join our [Discord community](https://discord.gg/cline).
</Accordion>
</Tab>
<Tab title="VSCodium/Windsurf" icon="terminal">
### Installation Steps
For VS Code-compatible editors using Open VSX Registry:
1. **Open your editor** (VSCodium, Windsurf, etc.)
2. **Navigate to Extensions view** (`Ctrl/Cmd + Shift + X`)
3. **Search for "Cline"** in the marketplace
4. **Select "Cline" by saoudrizwan** and click **Install**
5. **Reload** if prompted
> **Note:** These editors use the Open VSX Registry instead of the VS Code Marketplace.
<Accordion title="Troubleshooting">
**Plugin Installation Issues**
If you can't find Cline in the marketplace:
- Make sure you're searching in the **Marketplace** tab (not Installed)
- Try searching for "Cline AI" or just "Cline"
- Check that your editor version is compatible
If installation fails:
- Restart your editor and try again
- Check your internet connection
- Try installing from disk as an alternative
**Plugin Not Appearing**
If you don't see the Cline tool window after installation:
- Restart your editor completely (File → Exit and reopen)
- Check **View** → **Command Palette** → "Cline: Open In New Tab"
- Verify the plugin is enabled in **Extensions** view
- Look for the Cline icon in your Activity Bar (usually on the left side)
**Common Issues**
Plugin appears to be installed but doesn't work:
- Ensure you've restarted your editor after installation
- Check if there are any error messages in the Developer Console
- Try disabling and re-enabling the extension
Performance or compatibility issues:
- Make sure you're using a supported editor version
- Check for editor updates that might improve compatibility
- Consider closing other resource-intensive extensions if needed
Need help? Join our [Discord community](https://discord.gg/cline).
</Accordion>
</Tab>
</Tabs>
### Sign In to Your Cline Account
Now that you have Cline installed, sign in to access your account:
1. **Open Cline** in your editor (click the Cline icon in the Activity Bar or Tool Windows)
2. **Click "Sign In"** - you'll see this button in the Cline interface
3. **Complete authentication** - you'll be redirected to [app.cline.bot](https://app.cline.bot) to sign in
4. **Return to your editor** - once signed in, you'll be automatically redirected back
Now that you have Cline installed, let's get you set up with your account:
1. **Sign In to Cline:**
- Click the **Sign In** button in the Cline extension.
- You'll be taken to [app.cline.bot](https://app.cline.bot) to create your account.
2. **Start with Free Credits:**
- No credit card needed!
3. **Available AI Models:**
- Anthropic Claude 3.5-Sonnet (recommended for coding)
- DeepSeek Chat (cost-effective alternative)
- Google Gemini 2.0 Flash
- And more — all through your Cline account.
### Your First Interaction with Cline
@@ -269,4 +80,4 @@ Hey Cline! Could you help me create a new project folder called "hello-world" in
### Still Struggling?
Join our [Discord community](https://discord.gg/cline) and engage with our team and other Cline users directly.
Join our Discord community and engage with our team and other Cline users directly.
@@ -9,7 +9,7 @@ New models drop constantly, so this guide focuses on what's working well with Cl
| Model | Context Window | Input Price* | Output Price* | Best For |
|-------|---------------|--------------|---------------|----------|
| **Claude Sonnet 4.5** | 1M tokens | $3-6 | $15-22.50 | Reliable tool usage, complex codebases |
| **Claude Sonnet 4** | 1M tokens | $3-6 | $15-22.50 | Reliable tool usage, complex codebases |
| **Qwen3 Coder** | 256K tokens | $0.20 | $0.80 | Coding tasks, open source flexibility |
| **Gemini 2.5 Pro** | 1M+ tokens | TBD | TBD | Large codebases, document analysis |
| **GPT-5** | 400K tokens | $1.25 | $10 | Latest OpenAI tech, three modes |
@@ -57,9 +57,9 @@ New models drop constantly, so this guide focuses on what's working well with Cl
| If you want... | Use this |
|----------------|----------|
| Something that just works | Claude Sonnet 4.5 |
| Something that just works | Claude Sonnet 4 |
| To save money | DeepSeek V3 or Qwen3 variants |
| Huge context windows | Gemini 2.5 Pro or Claude Sonnet 4.5 |
| Huge context windows | Gemini 2.5 Pro or Claude Sonnet 4 |
| Open source | Qwen3 Coder, Z AI GLM 4.5, or Kimi K2 |
| Latest tech | GPT-5 |
| Speed | Qwen3 Coder on Cerebras (fastest available) |
@@ -74,6 +74,6 @@ Cline automatically handles context limits with [auto-compact](/features/auto-co
## The Bottom Line
Start with **Claude Sonnet 4.5** if you want reliability. Experiment with **open source options** once you're comfortable to find the best fit for your workflow and budget.
Start with **Claude Sonnet 4** if you want reliability. Experiment with **open source options** once you're comfortable to find the best fit for your workflow and budget.
The landscape moves fast - these recommendations reflect what's working now, but keep an eye on new releases.
@@ -53,7 +53,7 @@ Think of context like a whiteboard you and Cline share:
- **Context Window** is the size of the whiteboard itself:
- Measured in tokens (1 token ≈ 3/4 of an English word)
- Each model has a fixed size:
- Claude Sonnet 4.5: 1,000,000 tokens
- Claude Sonnet 4: 1,000,000 tokens
- Qwen3 Coder: 256,000 tokens
- Gemini 2.5 Pro: 1,000,000+ tokens
- GPT-5: 400,000 tokens
@@ -77,7 +77,7 @@ Cline provides a visual way to monitor your context window usage through a progr
- ↑ shows input tokens (what you've sent to the LLM)
- ↓ shows output tokens (what the LLM has generated)
- The progress bar visualizes how much of your context window you've used
- The total shows your model's maximum capacity (e.g., 1M for Claude Sonnet 4.5)
- The total shows your model's maximum capacity (e.g., 1M for Claude Sonnet 4)
### When to Watch the Bar
+3 -3
View File
@@ -1,9 +1,9 @@
---
title: "What is Cline?"
description: "An introduction to Cline, your AI-powered development assistant for modern IDEs."
description: "An introduction to Cline, your AI-powered development assistant in VS Code."
---
Cline is an open source AI coding agent that brings frontier AI models directly to your IDE. Unlike autocomplete tools, Cline is a true coding agent that can understand entire codebases, plan complex changes, and execute multi-step tasks.
Cline is an open source AI coding agent that brings frontier AI models directly to your VS Code editor. Unlike autocomplete tools, Cline is a true coding agent that can understand entire codebases, plan complex changes, and execute multi-step tasks.
## Open Source AI Coding, Uncompromised
@@ -69,4 +69,4 @@ Define project-specific instructions that Cline follows including coding standar
## Getting Started
Ready to experience AI coding without limits? [Install Cline](/getting-started/installing-cline) for your preferred IDE and start with our [Model Selection Guide](/getting-started/model-selection-guide) to choose the right AI model for your needs.
Ready to experience AI coding without limits? [Install Cline](/getting-started/installing-cline) and start with our [Model Selection Guide](/getting-started/model-selection-guide) to choose the right AI model for your needs.
-14
View File
@@ -1,14 +0,0 @@
// HubSpot Tracking Code for Cline Documentation
;(() => {
// Check if HubSpot script is already loaded to prevent duplicates
if (!document.getElementById("hs-script-loader")) {
var script = document.createElement("script")
script.type = "text/javascript"
script.id = "hs-script-loader"
script.async = true
script.src = "https://js-na2.hs-scripts.com/243656267.js"
// Append the script to the document head
document.head.appendChild(script)
}
})()
+2 -2
View File
@@ -7,7 +7,7 @@ title: "Configuring MCP Servers"
Utilizing MCP servers will increase your token usage. Cline offers the ability to restrict or disable MCP server functionality as desired.
1. Click the "MCP Servers" icon in the top navigation bar of the Cline extension.
2. Select the "Configure" tab, and then Click the "Advanced MCP Settings" link at the bottom of that pane.
2. Select the "Installed" tab, and then Click the "Advanced MCP Settings" link at the bottom of that pane.
3. Cline will open a new settings window. find `Cline>Mcp:Mode` and make your selection from the dropdown menu.
<Frame>
@@ -56,7 +56,7 @@ To set the maximum time to wait for a response after a tool call to the MCP serv
Settings for all installed MCP servers are located in the `cline_mcp_settings.json` file:
1. Click the MCP Servers icon at the top navigation bar of the Cline pane.
2. Select the "Configure" tab.
2. Select the "Installed" tab.
3. Click the "Configure MCP Servers" button at the bottom of the pane.
The file uses a JSON format with a `mcpServers` object containing named server configurations:
+2 -2
View File
@@ -54,7 +54,7 @@ Please note: Smithery is maintained independently and is not affiliated with our
### Managing Installed MCP Servers
Once added, your MCP servers appear in the "Configure" tab where you can:
Once added, your MCP servers appear in the "Installed" tab where you can:
#### View Server Status
@@ -98,7 +98,7 @@ If a server fails to connect:
For advanced users, Cline stores MCP server configurations in a JSON file that can be modified:
1. In the "Configure" tab, click "Configure MCP Servers" to access the settings file
1. In the "Installed" tab, click "Configure MCP Servers" to access the settings file
2. The configuration for each server follows this format:
```json
+4 -4
View File
@@ -1386,7 +1386,7 @@
"integrity": "sha512-/uR4hAwpcJW9+zbmZL48kKFnWLkOxhIqoGWvZzjg0CniVhR4emtQJAps80WqLAhz0iJgCQxg/axtA7leaznDzQ==",
"license": "Elastic-2.0",
"dependencies": {
"axios": "^1.12.0",
"axios": "^1.8.3",
"openapi-types": "^12.0.0"
},
"engines": {
@@ -2688,9 +2688,9 @@
}
},
"node_modules/axios": {
"version": "1.12.2",
"resolved": "https://registry.npmjs.org/axios/-/axios-1.12.2.tgz",
"integrity": "sha512-vMJzPewAlRyOgxV2dU0Cuz2O8zzzx9VYtbJOaBgXFeLc4IV/Eg50n4LowmehOOR61S8ZMpc2K5Sa7g6A4jfkUw==",
"version": "1.11.0",
"resolved": "https://registry.npmjs.org/axios/-/axios-1.11.0.tgz",
"integrity": "sha512-1Lx3WLFQWm3ooKDYZD1eXmoGO9fxYQjrycfHFC8P0sCfQVXyROp0p9PFWBehewBOdCwHc+f/b8I0fMto5eSfwA==",
"license": "MIT",
"dependencies": {
"follow-redirects": "^1.15.6",
+6 -3
View File
@@ -18,8 +18,11 @@ Cline supports the following Anthropic Claude models:
- `claude-opus-4-1-20250805`
- `claude-opus-4-20250514`
- `anthropic/claude-sonnet-4.5` (Recommended)
- `claude-opus-4-20250514:thinking` (Extended Thinking variant)
- `claude-sonnet-4-20250514` (Recommended)
- `claude-sonnet-4-20250514:thinking` (Extended Thinking variant)
- `claude-3-7-sonnet-20250219`
- `claude-3-7-sonnet-20250219:thinking` (Extended Thinking variant)
- `claude-3-5-sonnet-20241022`
- `claude-3-5-haiku-20241022`
- `claude-3-opus-20240229`
@@ -44,8 +47,8 @@ Cline users can leverage this by checking the `Enable Extended Thinking` box bel
**Key Aspects of Extended Thinking:**
- **Supported Models:** This feature is available for select models, including Claude Opus 4, Claude Sonnet 4.5, and Claude Sonnet 3.7.
- **Summarized Thinking (Claude 4):** For Claude 4 and 4.5 models, the API returns a summary of the full thinking process to balance insight with efficiency and prevent misuse. You are billed for the full thinking tokens, not just the summary.
- **Supported Models:** This feature is available for select models, including variants of Claude Opus 4, Claude Sonnet 4, and Claude Sonnet 3.7. The specific models listed in the "Supported Models" section above with the `:thinking` suffix are pre-configured in Cline to utilize this.
- **Summarized Thinking (Claude 4):** For Claude 4 models, the API returns a summary of the full thinking process to balance insight with efficiency and prevent misuse. You are billed for the full thinking tokens, not just the summary.
- **Streaming:** Extended thinking responses, including the `thinking` blocks, can be streamed.
- **Tool Use & Prompt Caching:** Extended thinking interacts with tool use (requiring thinking blocks to be passed back) and prompt caching (with specific behaviors around cache invalidation and context).
-115
View File
@@ -1,115 +0,0 @@
---
title: "Baseten"
description: "Learn how to configure and use Baseten's Model APIs with Cline. Access frontier open-source models with enterprise-grade performance, reliability, and competitive pricing."
---
Baseten provides on-demand frontier model APIs designed for production applications, not just experimentation. Built on the Baseten Inference Stack, these APIs deliver enterprise-grade performance and reliability with optimized inference for leading open-source models from OpenAI, DeepSeek, Meta, Moonshot AI, and Alibaba Cloud.
**Website:** [https://www.baseten.co/products/model-apis/](https://www.baseten.co/products/model-apis/)
### Getting an API Key
1. **Sign Up/Sign In:** Go to [Baseten](https://www.baseten.co/) and create an account or sign in.
2. **Navigate to API Keys:** Access your dashboard and go to the API Keys section.
3. **Create a Key:** Generate a new API key. Give it a descriptive name (e.g., "Cline").
4. **Copy the Key:** Copy the API key immediately and store it securely.
### Supported Models
Cline supports all current models under Baseten Model APIs, including:
For the most updated pricing, please visit: https://www.baseten.co/products/model-apis/
**Reasoning Models:**
- `deepseek-ai/DeepSeek-R1` - DeepSeek's first-generation reasoning model (163K context) - \$2.55/\$5.95 per 1M tokens
- `deepseek-ai/DeepSeek-R1-0528` - Latest revision of DeepSeek's reasoning model (163K context) - \$2.55/\$5.95 per 1M tokens
- `deepseek-ai/DeepSeek-V3.1` - Hybrid reasoning with advanced tool calling (163K context) - \$0.50/\$1.50 per 1M tokens
- `deepseek-ai/DeepSeek-V3-0324` - Fast general-purpose with enhanced reasoning (163K context) - \$0.77/\$0.77 per 1M tokens
**Flagship Models:**
- `openai/gpt-oss-120b` (OpenAI) - 120B MoE with strong reasoning capabilities (128K context) - \$0.10/\$0.50 per 1M tokens
- `moonshotai/Kimi-K2-Instruct` (Moonshot AI) - 1 trillion parameter model for agentic tasks (131K context) - \$0.60/\$2.50 per 1M tokens
- `moonshotai/Kimi-K2-Instruct-0905` (Moonshot AI) - September update with enhanced capabilities (262K context) - \$0.60/\$2.50 per 1M tokens
**Meta Llama 4 Series:**
- `meta-llama/Llama-4-Maverick-17B-128E-Instruct` - High-efficiency processing (1M context!) - \$0.19/\$0.72 per 1M tokens
- `meta-llama/Llama-4-Scout-17B-16E-Instruct` - Precise context understanding (1M context!) - \$0.13/\$0.50 per 1M tokens
**Coding Specialists:**
- `Qwen/Qwen3-Coder-480B-A35B-Instruct`- Advanced coding and reasoning (262K context) - \$0.38/\$1.53 per 1M tokens
- `Qwen/Qwen3-235B-A22B-Instruct-2507` - Math and reasoning expert (262K context) - \$0.22/\$0.80 per 1M tokens
### Configuration in Cline
1. **Open Cline Settings:** Click the settings icon (⚙️) in the Cline panel.
2. **Select Provider:** Choose "Baseten" from the "API Provider" dropdown.
3. **Enter API Key:** Paste your Baseten API key into the "Baseten API Key" field.
4. **Select Model:** Choose your desired model from the "Model" dropdown.
### Production-First Architecture
Baseten's Model APIs are built for production environments with several key advantages:
#### Enterprise-Grade Reliability
- **Four nines of uptime** (99.99%) through active-active redundancy
- **Cloud-agnostic, multi-cluster autoscaling** for consistent availability
- **SOC 2 Type II certified** and **HIPAA compliant** for security requirements
#### Optimized Performance
- **Pre-optimized models** shipped with the Baseten Inference Stack
- **Latest-generation GPUs** with multi-cloud infrastructure
- **Ultra-fast inference** optimized from the bottom up for production workloads
#### Cost Efficiency
- **5-10x less expensive** than closed alternatives
- **Optimized multi-cloud infrastructure** for efficient resource utilization
- **Transparent pricing** with no hidden costs or rate limit surprises
#### Developer Experience
- **OpenAI compatible API** - migrate by swapping a single URL
- **Drop-in replacement** for closed models with comprehensive observability
- **Seamless scaling** from Model APIs to dedicated deployments
### Special Features
#### Function Calling & Tool Use
All Baseten models support structured outputs, function calling, and tool use as part of the Baseten Inference Stack, making them ideal for agentic applications.
#### Reasoning Capabilities
DeepSeek models offer enhanced reasoning with step-by-step thought processes, while maintaining production-ready performance.
#### Long Context Support
- **Up to 1 million tokens** for Llama 4 models (Maverick and Scout)
- **262K tokens** for Qwen3 models
- **163K tokens** for DeepSeek models
- **Perfect for code repositories** and complex multi-turn conversations
#### Quantization Optimizations
Models are deployed with advanced quantization techniques (fp4, fp8, fp16) for optimal performance while maintaining quality.
### Migration from Other Providers
Baseten's OpenAI compatibility makes migration straightforward:
**From OpenAI:**
- Swap `api.openai.com` with `inference.baseten.co/v1`
- Keep existing request/response formats
- Benefit from significant cost savings
**From Other Providers:**
- Use standard OpenAI SDK format
- Maintain existing prompting strategies
- Access to newer open-source models
### Tips and Notes
- **Model Selection:** Choose models based on your specific use case - reasoning models for complex tasks, coding models for development work, and flagship models for general applications.
- **Cost Optimization:** Baseten offers some of the most competitive pricing in the market, especially for open-source models.
- **Context Windows:** Take advantage of large context windows (up to 1M tokens) for including substantial codebases and documentation.
- **Enterprise Ready:** Baseten is designed for production use with enterprise-grade security, compliance, and reliability.
- **Dynamic Model Updates:** Cline automatically fetches the latest model list from Baseten, ensuring access to new models as they're released.
- **Multi-Cloud Capacity Management (MCM):** Baseten's multi-cloud infrastructure ensures high availability and low latency globally.
- **Support:** Baseten provides dedicated support for production deployments and can work with you on dedicated resources as you scale.
### Pricing Information
Current pricing is highly competitive and transparent. For the most up-to-date pricing, visit the [Baseten Model APIs page](https://www.baseten.co/products/model-apis/). Prices typically range from \$0.10-\$6.00 per million tokens, making Baseten significantly more cost-effective than many closed-model alternatives while providing access to state-of-the-art open-source models.
-38
View File
@@ -49,44 +49,6 @@ All models feature:
4. **Enter API Key:** Paste your Z AI API key into the "Z AI API Key" field.
5. **Select Model:** Choose your desired model from the "Model" dropdown.
### GLM Coding Plans
Z AI offers subscription plans specifically designed for coding applications. These plans provide cost-effective access to GLM-4.5 models through a prompt-based structure rather than traditional API usage billing.
#### Plan Options
**GLM Coding Lite** - $3/month
- 120 prompts per 5-hour cycle
- Access to GLM-4.5 model
- Works exclusively through coding tools like Cline
**GLM Coding Pro** - $15/month
- 600 prompts per 5-hour cycle
- Access to GLM-4.5 model
- Works exclusively through coding tools like Cline
Both plans offer promotional pricing for the first month: Lite drops from \$6 to \$3, Pro drops from \$30 to \$15.
<Frame>
<img src="https://storage.googleapis.com/cline_public_images/docs/assets/zAI-coding-plan.png" alt="zAI subscription page showing GLM Coding Lite and Pro plans with pricing" />
</Frame>
#### Setting up GLM Coding Plans
To use the GLM Coding Plans with Cline:
1. **Subscribe:** Go to [https://z.ai/subscribe](https://z.ai/subscribe) and choose your plan.
2. **Create API Key:** After subscribing, log into your zAI dashboard and create an API key for your coding plan.
3. **Configure in Cline:** Open Cline settings, select "Z AI" as your provider, and paste your API key into the "Z AI API Key" field.
<Frame>
<img src="https://storage.googleapis.com/cline_public_images/docs/assets/zAI-provider.png" alt="Cline settings with zAI provider selected and API key field highlighted" />
</Frame>
The setup connects your subscription directly to Cline, giving you access to GLM-4.5's tool-calling capabilities optimized for coding workflows.
### Z AI's Hybrid Intelligence
Z AI's GLM-4.5 series introduces revolutionary capabilities that set it apart from conventional language models:
-47
View File
@@ -1,47 +0,0 @@
/* Custom styles for Cline documentation */
/* Make h1 titles lighter in font weight */
h1 {
font-weight: 500 !important;
}
/* Also apply to any h1 elements within content areas */
.content h1,
.markdown h1,
article h1,
main h1 {
font-weight: 500 !important;
}
/* JetBrains logo visibility fix for dark mode */
/* Add a subtle background and border to ensure visibility in both light and dark modes */
img[alt="JetBrains logo"] {
background-color: rgba(255, 255, 255, 0.9);
border: 1px solid rgba(0, 0, 0, 0.1);
border-radius: 8px;
padding: 12px;
transition: all 0.3s ease;
}
/* Dark mode specific styling */
[data-theme="dark"] img[alt="JetBrains logo"],
.dark img[alt="JetBrains logo"] {
background-color: rgba(255, 255, 255, 0.95);
border: 1px solid rgba(0, 0, 0, 0.2);
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}
/* Media query for system dark mode preference */
@media (prefers-color-scheme: dark) {
img[alt="JetBrains logo"] {
background-color: rgba(255, 255, 255, 0.95);
border: 1px solid rgba(0, 0, 0, 0.2);
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}
}
/* Hover effect for better interactivity */
img[alt="JetBrains logo"]:hover {
transform: scale(1.02);
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}
+6 -20
View File
@@ -6,7 +6,7 @@ import * as esbuild from "esbuild"
const __filename = fileURLToPath(import.meta.url)
const __dirname = path.dirname(__filename)
const production = process.argv.includes("--production") || process.env["IS_DEBUG_BUILD"] === "false"
const production = process.argv.includes("--production")
const watch = process.argv.includes("--watch")
const standalone = process.argv.includes("--standalone")
const e2eBuild = process.argv.includes("--e2e-build")
@@ -123,29 +123,15 @@ const copyWasmFiles = {
},
}
const buildEnvVars = { "import.meta.url": "_importMetaUrl" }
if (production) {
// IS_DEV is always disable in production builds.
buildEnvVars["process.env.IS_DEV"] = "false"
}
// Set the environment and telemetry env vars. The API key env vars need to be populated in the GitHub
// workflows from the secrets.
if (process.env.CLINE_ENVIRONMENT) {
buildEnvVars["process.env.CLINE_ENVIRONMENT"] = JSON.stringify(process.env.CLINE_ENVIRONMENT)
}
if (process.env.TELEMETRY_SERVICE_API_KEY) {
buildEnvVars["process.env.TELEMETRY_SERVICE_API_KEY"] = JSON.stringify(process.env.TELEMETRY_SERVICE_API_KEY)
}
if (process.env.ERROR_SERVICE_API_KEY) {
buildEnvVars["process.env.ERROR_SERVICE_API_KEY"] = JSON.stringify(process.env.ERROR_SERVICE_API_KEY)
}
// Base configuration shared between extension and standalone builds
const baseConfig = {
bundle: true,
minify: production,
sourcemap: !production,
logLevel: "silent",
define: buildEnvVars,
define: production
? { "import.meta.url": "_importMetaUrl", "process.env.IS_DEV": JSON.stringify(!production) }
: { "import.meta.url": "_importMetaUrl" },
tsconfig: path.resolve(__dirname, "tsconfig.json"),
plugins: [
copyWasmFiles,
@@ -174,9 +160,9 @@ const standaloneConfig = {
...baseConfig,
entryPoints: ["src/standalone/cline-core.ts"],
outfile: `${destDir}/cline-core.js`,
// These modules need to load files from the module directory at runtime,
// These gRPC protos need to load files from the module directory at runtime,
// so they cannot be bundled.
external: ["vscode", "@grpc/reflection", "grpc-health-check", "better-sqlite3"],
external: ["vscode", "@grpc/reflection", "grpc-health-check"],
}
// E2E build script configuration
+17
View File
@@ -148,6 +148,11 @@ export async function spawnVSCode(workspacePath: string, vsixPath?: string): Pro
command: "workbench.view.extension.saoudrizwan.claude-dev-ActivityBar",
when: "viewContainer.workbench.view.extension.saoudrizwan.claude-dev-ActivityBar.enabled",
},
{
key: "alt+shift+c",
command: "cline.openInNewTab",
when: "viewContainer.workbench.view.extension.saoudrizwan.claude-dev-ActivityBar.enabled",
},
]
fs.writeFileSync(keybindingsPath, JSON.stringify(keybindings, null, 2))
console.log(`Created keybindings.json to help with Cline activation`)
@@ -182,6 +187,11 @@ export async function spawnVSCode(workspacePath: string, vsixPath?: string): Pro
setTimeout(() => {
// Try to open Cline in the sidebar
require('vscode').commands.executeCommand('workbench.view.extension.saoudrizwan.claude-dev-ActivityBar');
// Also try to open Cline in a tab as a fallback
setTimeout(() => {
require('vscode').commands.executeCommand('cline.openInNewTab');
}, 5000);
}, 5000);
`
fs.writeFileSync(startupScriptPath, startupScript)
@@ -278,6 +288,13 @@ export async function spawnVSCode(workspacePath: string, vsixPath?: string): Pro
// Wait a moment for the sidebar to initialize
await new Promise(resolve => setTimeout(resolve, 2000));
// Also open Cline in a tab as a fallback
console.log('Opening Cline in a tab...');
await vscode.commands.executeCommand('cline.openInNewTab');
// Wait a moment for the tab to initialize
await new Promise(resolve => setTimeout(resolve, 2000));
// Create the test server if it doesn't exist
console.log('Creating test server...');
+2 -3
View File
@@ -1,6 +1,5 @@
import { Anthropic } from "@anthropic-ai/sdk"
import { ToolParamName } from "../../src/core/assistant-message"
import { ClineDefaultTool } from "../../src/shared/tools"
import { ToolUseName, ToolParamName } from "../../src/core/assistant-message"
export interface InputMessage {
role: "user" | "assistant"
@@ -89,7 +88,7 @@ export interface TestResult {
}
export interface ExtractedToolCall {
name: ClineDefaultTool
name: ToolUseName
input: Partial<Record<ToolParamName, string>>
}
+31 -82
View File
@@ -9,9 +9,9 @@
"version": "0.1.0",
"license": "MIT",
"dependencies": {
"axios": "^1.12.0",
"axios": "^1.8.2",
"better-sqlite3": "^11.10.0",
"chalk": "5.6.2",
"chalk": "^4.1.2",
"commander": "^9.4.1",
"dotenv": "^16.5.0",
"execa": "^5.1.1",
@@ -200,13 +200,12 @@
"integrity": "sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q=="
},
"node_modules/axios": {
"version": "1.12.2",
"resolved": "https://registry.npmjs.org/axios/-/axios-1.12.2.tgz",
"integrity": "sha512-vMJzPewAlRyOgxV2dU0Cuz2O8zzzx9VYtbJOaBgXFeLc4IV/Eg50n4LowmehOOR61S8ZMpc2K5Sa7g6A4jfkUw==",
"license": "MIT",
"version": "1.10.0",
"resolved": "https://registry.npmjs.org/axios/-/axios-1.10.0.tgz",
"integrity": "sha512-/1xYAC4MP/HEG+3duIhFr4ZQXR4sQXOIe+o6sdqzeykGLx6Upp/1p8MHqhINOvGeP7xyNHe7tsiJByc4SSVUxw==",
"dependencies": {
"follow-redirects": "^1.15.6",
"form-data": "^4.0.4",
"form-data": "^4.0.0",
"proxy-from-env": "^1.1.0"
}
},
@@ -293,12 +292,15 @@
}
},
"node_modules/chalk": {
"version": "5.6.2",
"resolved": "https://registry.npmjs.org/chalk/-/chalk-5.6.2.tgz",
"integrity": "sha512-7NzBL0rN6fMUW+f7A6Io4h40qQlG+xGmtMxfbnH/K7TAtt8JQWVQK+6g0UXKMeVJoyV5EkkNsErQ8pVD3bLHbA==",
"license": "MIT",
"version": "4.1.2",
"resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz",
"integrity": "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==",
"dependencies": {
"ansi-styles": "^4.1.0",
"supports-color": "^7.1.0"
},
"engines": {
"node": "^12.17.0 || ^14.13 || >=16.0.0"
"node": ">=10"
},
"funding": {
"url": "https://github.com/chalk/chalk?sponsor=1"
@@ -605,10 +607,9 @@
}
},
"node_modules/form-data": {
"version": "4.0.4",
"resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.4.tgz",
"integrity": "sha512-KrGhL9Q4zjj0kiUt5OO4Mr/A/jlI2jDYs5eHBpYHPcBEVSiipAvn2Ko2HnPe20rmcuuvMHNdZFp+4IlGTMF0Ow==",
"license": "MIT",
"version": "4.0.3",
"resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.3.tgz",
"integrity": "sha512-qsITQPfmvMOSAdeyZ+12I1c+CKSstAFAwu+97zrnWAbIr5u8wfsExUzCesVLC8NgHuRUqNN4Zy6UPWUTRGslcA==",
"dependencies": {
"asynckit": "^0.4.0",
"combined-stream": "^1.0.8",
@@ -707,7 +708,6 @@
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz",
"integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==",
"license": "MIT",
"engines": {
"node": ">=8"
}
@@ -843,22 +843,6 @@
"url": "https://github.com/sponsors/sindresorhus"
}
},
"node_modules/log-symbols/node_modules/chalk": {
"version": "4.1.2",
"resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz",
"integrity": "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==",
"license": "MIT",
"dependencies": {
"ansi-styles": "^4.1.0",
"supports-color": "^7.1.0"
},
"engines": {
"node": ">=10"
},
"funding": {
"url": "https://github.com/chalk/chalk?sponsor=1"
}
},
"node_modules/make-error": {
"version": "1.3.6",
"resolved": "https://registry.npmjs.org/make-error/-/make-error-1.3.6.tgz",
@@ -1019,22 +1003,6 @@
"url": "https://github.com/sponsors/sindresorhus"
}
},
"node_modules/ora/node_modules/chalk": {
"version": "4.1.2",
"resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz",
"integrity": "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==",
"license": "MIT",
"dependencies": {
"ansi-styles": "^4.1.0",
"supports-color": "^7.1.0"
},
"engines": {
"node": ">=10"
},
"funding": {
"url": "https://github.com/chalk/chalk?sponsor=1"
}
},
"node_modules/path-key": {
"version": "3.1.1",
"resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz",
@@ -1283,7 +1251,6 @@
"version": "7.2.0",
"resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz",
"integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==",
"license": "MIT",
"dependencies": {
"has-flag": "^4.0.0"
},
@@ -1668,12 +1635,12 @@
"integrity": "sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q=="
},
"axios": {
"version": "1.12.2",
"resolved": "https://registry.npmjs.org/axios/-/axios-1.12.2.tgz",
"integrity": "sha512-vMJzPewAlRyOgxV2dU0Cuz2O8zzzx9VYtbJOaBgXFeLc4IV/Eg50n4LowmehOOR61S8ZMpc2K5Sa7g6A4jfkUw==",
"version": "1.10.0",
"resolved": "https://registry.npmjs.org/axios/-/axios-1.10.0.tgz",
"integrity": "sha512-/1xYAC4MP/HEG+3duIhFr4ZQXR4sQXOIe+o6sdqzeykGLx6Upp/1p8MHqhINOvGeP7xyNHe7tsiJByc4SSVUxw==",
"requires": {
"follow-redirects": "^1.15.6",
"form-data": "^4.0.4",
"form-data": "^4.0.0",
"proxy-from-env": "^1.1.0"
}
},
@@ -1728,9 +1695,13 @@
}
},
"chalk": {
"version": "5.6.2",
"resolved": "https://registry.npmjs.org/chalk/-/chalk-5.6.2.tgz",
"integrity": "sha512-7NzBL0rN6fMUW+f7A6Io4h40qQlG+xGmtMxfbnH/K7TAtt8JQWVQK+6g0UXKMeVJoyV5EkkNsErQ8pVD3bLHbA=="
"version": "4.1.2",
"resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz",
"integrity": "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==",
"requires": {
"ansi-styles": "^4.1.0",
"supports-color": "^7.1.0"
}
},
"chownr": {
"version": "1.1.4",
@@ -1938,9 +1909,9 @@
"integrity": "sha512-gew4GsXizNgdoRyqmyfMHyAmXsZDk6mHkSxZFCzW9gwlbtOW44CDtYavM+y+72qD/Vq2l550kMF52DT8fOLJqQ=="
},
"form-data": {
"version": "4.0.4",
"resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.4.tgz",
"integrity": "sha512-KrGhL9Q4zjj0kiUt5OO4Mr/A/jlI2jDYs5eHBpYHPcBEVSiipAvn2Ko2HnPe20rmcuuvMHNdZFp+4IlGTMF0Ow==",
"version": "4.0.3",
"resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.3.tgz",
"integrity": "sha512-qsITQPfmvMOSAdeyZ+12I1c+CKSstAFAwu+97zrnWAbIr5u8wfsExUzCesVLC8NgHuRUqNN4Zy6UPWUTRGslcA==",
"requires": {
"asynckit": "^0.4.0",
"combined-stream": "^1.0.8",
@@ -2083,17 +2054,6 @@
"requires": {
"chalk": "^4.1.0",
"is-unicode-supported": "^0.1.0"
},
"dependencies": {
"chalk": {
"version": "4.1.2",
"resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz",
"integrity": "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==",
"requires": {
"ansi-styles": "^4.1.0",
"supports-color": "^7.1.0"
}
}
}
},
"make-error": {
@@ -2204,17 +2164,6 @@
"log-symbols": "^4.1.0",
"strip-ansi": "^6.0.0",
"wcwidth": "^1.0.1"
},
"dependencies": {
"chalk": {
"version": "4.1.2",
"resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz",
"integrity": "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==",
"requires": {
"ansi-styles": "^4.1.0",
"supports-color": "^7.1.0"
}
}
}
},
"path-key": {
+2 -2
View File
@@ -19,9 +19,9 @@
"author": "",
"license": "MIT",
"dependencies": {
"axios": "^1.12.0",
"axios": "^1.8.2",
"better-sqlite3": "^11.10.0",
"chalk": "5.6.2",
"chalk": "^4.1.2",
"dotenv": "^16.5.0",
"commander": "^9.4.1",
"execa": "^5.1.1",
+213 -1913
View File
File diff suppressed because it is too large Load Diff
+57 -64
View File
@@ -2,7 +2,7 @@
"name": "claude-dev",
"displayName": "Cline",
"description": "Autonomous coding agent right in your IDE, capable of creating/editing files, running commands, using the browser, and more with your permission every step of the way.",
"version": "3.32.5",
"version": "3.27.0",
"icon": "assets/icons/icon.png",
"engines": {
"vscode": "^1.84.0"
@@ -133,6 +133,11 @@
"title": "History",
"icon": "$(history)"
},
{
"command": "cline.popoutButtonClicked",
"title": "Open in Editor",
"icon": "$(link-external)"
},
{
"command": "cline.accountButtonClicked",
"title": "Account",
@@ -143,6 +148,11 @@
"title": "Settings",
"icon": "$(settings-gear)"
},
{
"command": "cline.openInNewTab",
"title": "Open In New Tab",
"category": "Cline"
},
{
"command": "cline.dev.createTestTasks",
"title": "Create Test Tasks",
@@ -190,11 +200,6 @@
"command": "cline.openWalkthrough",
"title": "Open Walkthrough",
"category": "Cline"
},
{
"command": "cline.reconstructTaskHistory",
"title": "Reconstruct Task History",
"category": "Cline"
}
],
"keybindings": [
@@ -236,6 +241,11 @@
"group": "navigation@3",
"when": "view == claude-dev.SidebarProvider"
},
{
"command": "cline.popoutButtonClicked",
"group": "navigation@4",
"when": "view == claude-dev.SidebarProvider"
},
{
"command": "cline.accountButtonClicked",
"group": "navigation@5",
@@ -247,6 +257,38 @@
"when": "view == claude-dev.SidebarProvider"
}
],
"editor/title": [
{
"command": "cline.plusButtonClicked",
"group": "navigation@1",
"when": "activeWebviewPanelId == claude-dev.TabPanelProvider"
},
{
"command": "cline.mcpButtonClicked",
"group": "navigation@2",
"when": "activeWebviewPanelId == claude-dev.TabPanelProvider"
},
{
"command": "cline.historyButtonClicked",
"group": "navigation@3",
"when": "activeWebviewPanelId == claude-dev.TabPanelProvider"
},
{
"command": "cline.popoutButtonClicked",
"group": "navigation@4",
"when": "activeWebviewPanelId == claude-dev.TabPanelProvider"
},
{
"command": "cline.accountButtonClicked",
"group": "navigation@5",
"when": "activeWebviewPanelId == claude-dev.TabPanelProvider"
},
{
"command": "cline.settingsButtonClicked",
"group": "navigation@6",
"when": "activeWebviewPanelId == claude-dev.TabPanelProvider"
}
],
"editor/context": [
{
"command": "cline.addToChat",
@@ -299,9 +341,7 @@
"package": "npm run check-types && npm run build:webview && npm run lint && node esbuild.mjs --production",
"protos": "node scripts/build-proto.mjs",
"postprotos": "biome format src/shared/proto src/core/controller src/hosts/ webview-ui/src/services src/generated --write --no-errors-on-unmatched",
"clean:build": "rimraf dist dist-standalone webview-ui/build src/generated out/",
"clean:deps": "rimraf node_modules webview-ui/node_modules",
"clean:all": "npm run clean:build && npm run clean:deps",
"clean": "rimraf dist dist-standalone webview-ui/build src/generated out/",
"compile-tests": "node ./scripts/build-tests.js",
"watch-tests": "tsc -p . -w --outDir out",
"check-types": "npm run protos && npx tsc --noEmit && cd webview-ui && npx tsc -b --noEmit",
@@ -309,27 +349,21 @@
"format": "biome format --changed --no-errors-on-unmatched --files-ignore-unknown=true --diagnostic-level=error",
"format:fix": "biome check --changed --no-errors-on-unmatched --files-ignore-unknown=true --write",
"fix:all": "biome check --no-errors-on-unmatched --files-ignore-unknown=true --write --diagnostic-level=error --unsafe",
"ci:check-all": "npm-run-all -p check-types lint format",
"ci:build": "npm run protos && npm run build:webview && node esbuild.mjs && npm run compile-tests",
"pretest": "npm run compile && npm run compile-tests && npm run compile-standalone && npm run lint",
"test": "npm-run-all test:unit test:integration",
"test:ci": "node scripts/test-ci.js",
"test:integration": "vscode-test",
"test:unit": "TS_NODE_PROJECT='./tsconfig.unit-test.json' mocha",
"test:coverage": "vscode-test --coverage",
"test:sca-server": "npx tsx watch scripts/test-standalone-core-api-server.ts",
"test:tp-orchestrator": "npx tsx scripts/testing-platform-orchestrator.ts",
"e2e": "playwright test -c playwright.config.ts",
"test:e2e:build": "vsce package --allow-package-secrets sendgrid --out dist/e2e.vsix",
"test:e2e": "playwright install && npm run test:e2e:build && node src/test/e2e/utils/build.mjs && playwright test",
"test:e2e:optimal": "npm run test:e2e:build && node src/test/e2e/utils/build.mjs && playwright test",
"test:e2e:ui": "npx tsx scripts/interactive-playwright.ts",
"test:e2e": "playwright install && vsce package --no-dependencies --allow-package-secrets sendgrid --out dist/e2e.vsix && node src/test/e2e/utils/build.mjs && playwright test",
"test:e2e:optimal": "vsce package --no-dependencies --allow-package-secrets sendgrid --out dist/e2e.vsix && node src/test/e2e/utils/build.mjs && playwright test",
"install:all": "npm install && cd webview-ui && npm install",
"dev:webview": "cd webview-ui && npm run dev",
"build:webview": "cd webview-ui && npm run build",
"test:webview": "cd webview-ui && npm run test",
"publish:marketplace": "vsce publish --allow-package-secrets sendgrid && ovsx publish",
"publish:marketplace:prerelease": "vsce publish --allow-package-secrets sendgrid --pre-release && ovsx publish --pre-release",
"publish:marketplace:nightly": "node ./scripts/publish-nightly.mjs",
"prepare": "husky",
"changeset": "changeset",
"version-packages": "changeset version",
@@ -347,7 +381,6 @@
"@biomejs/biome": "^2.1.4",
"@bufbuild/buf": "^1.54.0",
"@changesets/cli": "^2.27.12",
"@types/better-sqlite3": "^7.6.13",
"@types/chai": "^5.0.1",
"@types/clone-deep": "^4.0.4",
"@types/diff": "^5.2.1",
@@ -363,23 +396,19 @@
"@vscode/test-cli": "^0.0.10",
"@vscode/test-electron": "^2.5.2",
"@vscode/vsce": "^3.6.0",
"c8": "^10.1.3",
"chai": "^4.3.10",
"chalk": "5.6.2",
"chalk": "^5.3.0",
"esbuild": "^0.25.0",
"grpc-tools": "^1.13.0",
"husky": "^9.1.7",
"lint-staged": "^16.1.0",
"minimatch": "^3.0.3",
"npm-run-all": "^4.1.5",
"nyc": "^17.1.0",
"prebuild-install": "^7.1.3",
"protoc-gen-ts": "^0.8.7",
"proxyquire": "^2.1.3",
"rimraf": "^6.0.1",
"should": "^13.2.3",
"sinon": "^19.0.2",
"tree-kill": "^1.2.2",
"ts-node": "^10.9.2",
"ts-proto": "^2.6.1",
"tsconfig-paths": "^4.2.0",
@@ -390,6 +419,8 @@
"@anthropic-ai/vertex-sdk": "^0.6.4",
"@aws-sdk/client-bedrock-runtime": "^3.840.0",
"@aws-sdk/credential-providers": "^3.840.0",
"@sap-ai-sdk/ai-api": "^1.17.0",
"@sap-ai-sdk/orchestration": "^1.17.0",
"@bufbuild/protobuf": "^2.2.5",
"@cerebras/cerebras_cloud_sdk": "^1.35.0",
"@google-cloud/vertexai": "^1.9.3",
@@ -405,14 +436,12 @@
"@opentelemetry/sdk-trace-node": "^1.30.1",
"@opentelemetry/semantic-conventions": "^1.30.0",
"@playwright/test": "^1.53.2",
"@sap-ai-sdk/ai-api": "^1.17.0",
"@sap-ai-sdk/orchestration": "^1.17.0",
"@sentry/browser": "^9.12.0",
"@streamparser/json": "^0.0.22",
"@types/uuid": "^10.0.0",
"@vscode/codicons": "^0.0.36",
"archiver": "^7.0.1",
"axios": "^1.12.0",
"axios": "^1.8.2",
"cheerio": "^1.0.0",
"chokidar": "^4.0.1",
"chrome-launcher": "^1.1.2",
@@ -427,7 +456,6 @@
"get-folder-size": "^5.0.0",
"globby": "^14.0.2",
"grpc-health-check": "^2.0.2",
"https-proxy-agent": "^7.0.6",
"iconv-lite": "^0.6.3",
"ignore": "^7.0.3",
"image-size": "^2.0.2",
@@ -450,7 +478,7 @@
"reconnecting-eventsource": "^1.6.4",
"serialize-error": "^11.0.3",
"simple-git": "^3.27.0",
"strip-ansi": "^7.1.2",
"strip-ansi": "^7.1.0",
"tree-sitter-wasms": "^0.1.11",
"ts-morph": "^25.0.1",
"turndown": "^7.2.0",
@@ -459,40 +487,5 @@
"vscode-uri": "^3.1.0",
"web-tree-sitter": "^0.22.6",
"zod": "^3.24.2"
},
"c8": {
"reporter": [
"lcov",
"html"
],
"exclude": [
"**/testing-platform/**",
"**/webview-ui/**",
"**/.vscode-test/**",
"**/node_modules/**",
"node_modules",
"**/dist-standalone/src/**",
"**/dist-standalone/vsce-extension/https:/**",
"**/dist-standalone/vsce-extension/**",
"**/dist-standalone/https:/**",
"**/dist-standalone/LIB/src/**",
"**/dist-standalone/pdfjs-dist/**",
"**/*.d.ts",
"**/*.{test,spec}.{js,jsx,ts,tsx,mjs,cjs}",
"**/__tests__/**",
"**/test/**",
"**/tests/**",
"**/.nyc_output/**",
"**/tests-results/**",
"src/test/**",
"**/src/xml/**",
"**/standalone/**",
"**/src/generated/**",
"**/evals/cli/dist/**",
"**/evals/cli/src/**",
"dist"
],
"all": true,
"exclude-after-remap": true
}
}
-3
View File
@@ -38,9 +38,6 @@ service AccountService {
rpc setUserOrganization(UserOrganizationUpdateRequest) returns (Empty);
rpc openrouterAuthClicked(EmptyRequest) returns (Empty);
// Returns a link the webview can use to redirect back to the user's IDE.
rpc getRedirectUrl(EmptyRequest) returns (String);
}
message AuthStateChangedRequest {
+6 -1
View File
@@ -2,7 +2,6 @@ syntax = "proto3";
package cline;
import "cline/common.proto";
import "cline/state.proto";
option java_package = "bot.cline.proto";
option java_multiple_files = true;
@@ -11,6 +10,7 @@ service BrowserService {
rpc testBrowserConnection(StringRequest) returns (BrowserConnection);
rpc discoverBrowser(EmptyRequest) returns (BrowserConnection);
rpc getDetectedChromePath(EmptyRequest) returns (ChromePath);
rpc updateBrowserSettings(UpdateBrowserSettingsRequest) returns (Boolean);
rpc relaunchChromeDebugMode(EmptyRequest) returns (String);
}
@@ -31,6 +31,11 @@ message ChromePath {
bool is_bundled = 2;
}
message Viewport {
int32 width = 1;
int32 height = 2;
}
message BrowserSettings {
Viewport viewport = 1;
optional string remote_browser_host = 2;
+6
View File
@@ -8,16 +8,19 @@ message Metadata {
}
message EmptyRequest {
Metadata metadata = 1;
}
message Empty {
}
message StringRequest {
Metadata metadata = 1;
string value = 2;
}
message StringArrayRequest {
Metadata metadata = 1;
repeated string value = 2;
}
@@ -26,6 +29,7 @@ message String {
}
message Int64Request {
Metadata metadata = 1;
int64 value = 2;
}
@@ -34,6 +38,7 @@ message Int64 {
}
message BytesRequest {
Metadata metadata = 1;
bytes value = 2;
}
@@ -42,6 +47,7 @@ message Bytes {
}
message BooleanRequest {
Metadata metadata = 1;
bool value = 2;
}
-41
View File
@@ -1,41 +0,0 @@
syntax = "proto3";
package cline;
import "cline/common.proto";
option java_package = "bot.cline.proto";
option java_multiple_files = true;
service DictationService {
rpc startRecording(EmptyRequest) returns (RecordingResult);
rpc stopRecording(EmptyRequest) returns (RecordedAudio);
rpc cancelRecording(EmptyRequest) returns (RecordingResult);
rpc getRecordingStatus(EmptyRequest) returns (RecordingStatus);
rpc transcribeAudio(TranscribeAudioRequest) returns (Transcription);
}
message TranscribeAudioRequest {
string audio_base64 = 2;
string language = 3;
}
message RecordingResult {
bool success = 1;
string error = 2;
}
message RecordedAudio {
bool success = 1;
string audio_base64 = 2;
string error = 3;
}
message RecordingStatus {
bool is_recording = 1;
double duration_seconds = 2;
string error = 3;
}
message Transcription {
string text = 1;
string error = 2;
}
+1 -1
View File
@@ -50,7 +50,7 @@ service FileService {
rpc refreshRules(EmptyRequest) returns (RefreshedRules);
// Opens a task's conversation history file on disk
rpc openDiskConversationHistory(StringRequest) returns (Empty);
rpc openTaskHistory(StringRequest) returns (Empty);
// Toggles a workflow on or off
rpc toggleWorkflow(ToggleWorkflowRequest) returns (ClineRulesToggles);
+23 -83
View File
@@ -33,8 +33,6 @@ service ModelsService {
rpc refreshBasetenModels(EmptyRequest) returns (OpenRouterCompatibleModelInfo);
// Fetches available models from SAP AI Core
rpc getSapAiCoreModels(SapAiCoreModelsRequest) returns (SapAiCoreModelsResponse);
// Fetches available models from OCA
rpc refreshOcaModels(StringRequest) returns (OcaCompatibleModelInfo);
}
// List of VS Code LM models
@@ -110,16 +108,9 @@ message SapAiCoreModelsRequest {
string resource_group = 6;
}
// SAP AI Core model with deployment information
message SapAiCoreModelDeployment {
string model_name = 1;
string deployment_id = 2;
}
// Response for SAP AI Core models with orchestration availability
message SapAiCoreModelsResponse {
repeated SapAiCoreModelDeployment deployments = 1;
repeated string model_names = 1;
bool orchestration_available = 2;
}
@@ -129,48 +120,6 @@ message UpdateApiConfigurationRequest {
ModelsApiConfiguration api_configuration = 2;
}
// Model info for OCA (OpenAI-compatible) models exposed by the OCA provider
message OcaModelInfo {
// Maximum completion tokens per request supported by this model
optional int64 max_tokens = 1;
// Total context window in tokens (input + output)
optional int64 context_window = 2;
// Whether the model supports image inputs
optional bool supports_images = 3;
// Whether prompt caching is supported for this model
bool supports_prompt_cache = 4;
// Price per million input tokens (USD unless otherwise specified by provider)
optional double input_price = 5;
// Price per million output tokens (USD unless otherwise specified by provider)
optional double output_price = 6;
// Thinking/reasoning configuration if the model supports it
optional ThinkingConfig thinking_config = 7;
// Price per million tokens for prompt cache writes
optional double cache_writes_price = 9;
// Price per million tokens for prompt cache reads
optional double cache_reads_price = 10;
// Human-readable model description
optional string description = 11;
// Recommended default temperature for this model
optional double temperature = 13;
// Optional survey content to display in the UI
optional string survey_content = 14;
// Identifier for the survey associated with this model
optional string survey_id = 15;
// Optional banner content (e.g., deprecation or promotion notes)
optional string banner = 16;
// Canonical model identifier as reported by OCA
string model_name = 17;
}
// Aggregated OCA model catalog keyed by model identifier
message OcaCompatibleModelInfo {
// key: canonical model id as reported by OCA (e.g., "openai/gpt-4o-mini")
// value: OcaModelInfo describing that model
map<string, OcaModelInfo> models = 1;
optional string error = 2;
}
// API Provider enumeration
enum ApiProvider {
ANTHROPIC = 0;
@@ -208,7 +157,6 @@ enum ApiProvider {
VERCEL_AI_GATEWAY = 32;
QWEN_CODE = 33;
DIFY = 34;
OCA = 35;
}
// Model info for OpenAI-compatible models
@@ -321,9 +269,6 @@ message ModelsApiConfiguration {
optional string qwen_code_oauth_path = 70;
optional string dify_api_key = 71;
optional string dify_base_url = 72;
optional string oca_base_url = 73;
optional string oca_api_key = 74;
optional string oca_refresh_token = 75;
// Plan mode configurations
optional ApiProvider plan_mode_api_provider = 100;
@@ -346,20 +291,16 @@ message ModelsApiConfiguration {
optional string plan_mode_together_model_id = 117;
optional string plan_mode_fireworks_model_id = 118;
optional string plan_mode_sap_ai_core_model_id = 119;
optional string plan_mode_sap_ai_core_deployment_id = 120;
optional string plan_mode_groq_model_id = 121;
optional OpenRouterModelInfo plan_mode_groq_model_info = 122;
optional string plan_mode_hugging_face_model_id = 123;
optional OpenRouterModelInfo plan_mode_hugging_face_model_info = 124;
optional string plan_mode_huawei_cloud_maas_model_id = 125;
optional OpenRouterModelInfo plan_mode_huawei_cloud_maas_model_info = 126;
optional string plan_mode_baseten_model_id = 127;
optional OpenRouterModelInfo plan_mode_baseten_model_info = 128;
optional string plan_mode_vercel_ai_gateway_model_id = 129;
optional OpenRouterModelInfo plan_mode_vercel_ai_gateway_model_info = 130;
optional string plan_mode_oca_model_id = 131;
optional OcaModelInfo plan_mode_oca_model_info = 132;
optional string plan_mode_groq_model_id = 120;
optional OpenRouterModelInfo plan_mode_groq_model_info = 121;
optional string plan_mode_hugging_face_model_id = 122;
optional OpenRouterModelInfo plan_mode_hugging_face_model_info = 123;
optional string plan_mode_huawei_cloud_maas_model_id = 124;
optional OpenRouterModelInfo plan_mode_huawei_cloud_maas_model_info = 125;
optional string plan_mode_baseten_model_id = 126;
optional OpenRouterModelInfo plan_mode_baseten_model_info = 127;
optional string plan_mode_vercel_ai_gateway_model_id = 128;
optional OpenRouterModelInfo plan_mode_vercel_ai_gateway_model_info = 129;
// Act mode configurations
optional ApiProvider act_mode_api_provider = 200;
@@ -382,17 +323,16 @@ message ModelsApiConfiguration {
optional string act_mode_together_model_id = 217;
optional string act_mode_fireworks_model_id = 218;
optional string act_mode_sap_ai_core_model_id = 219;
optional string act_mode_sap_ai_core_deployment_id = 220;
optional string act_mode_groq_model_id = 221;
optional OpenRouterModelInfo act_mode_groq_model_info = 222;
optional string act_mode_hugging_face_model_id = 223;
optional OpenRouterModelInfo act_mode_hugging_face_model_info = 224;
optional string act_mode_huawei_cloud_maas_model_id = 225;
optional OpenRouterModelInfo act_mode_huawei_cloud_maas_model_info = 226;
optional string act_mode_baseten_model_id = 227;
optional OpenRouterModelInfo act_mode_baseten_model_info = 228;
optional string act_mode_vercel_ai_gateway_model_id = 229;
optional OpenRouterModelInfo act_mode_vercel_ai_gateway_model_info = 230;
optional string act_mode_oca_model_id = 231;
optional OcaModelInfo act_mode_oca_model_info = 232;
optional string act_mode_groq_model_id = 220;
optional OpenRouterModelInfo act_mode_groq_model_info = 221;
optional string act_mode_hugging_face_model_id = 222;
optional OpenRouterModelInfo act_mode_hugging_face_model_info = 223;
optional string act_mode_huawei_cloud_maas_model_id = 224;
optional OpenRouterModelInfo act_mode_huawei_cloud_maas_model_info = 225;
optional string act_mode_baseten_model_id = 226;
optional OpenRouterModelInfo act_mode_baseten_model_info = 227;
optional string act_mode_vercel_ai_gateway_model_id = 228;
optional OpenRouterModelInfo act_mode_vercel_ai_gateway_model_info = 229;
repeated string favorited_model_ids = 300;
}
-36
View File
@@ -1,36 +0,0 @@
syntax = "proto3";
package cline;
import "cline/common.proto";
option java_package = "bot.cline.proto";
option java_multiple_files = true;
// Service for account-related operations
service OcaAccountService {
// Handles the user clicking the login link in the UI.
// Generates a secure nonce for state validation, stores it in secrets,
// and opens the authentication URL in the external browser.
rpc ocaAccountLoginClicked(EmptyRequest) returns (String);
// Handles the user clicking the logout button in the UI.
// Clears API keys and user state.
rpc ocaAccountLogoutClicked(EmptyRequest) returns (Empty);
// Subscribe to auth status update events (when authentication state changes)
rpc ocaSubscribeToAuthStatusUpdate(EmptyRequest)
returns (stream OcaAuthState);
}
message OcaAuthState {
optional OcaUserInfo user = 1;
optional string api_key = 2;
}
// User's information
message OcaUserInfo {
string uid = 1;
optional string display_name = 2;
optional string email = 3;
}
+31 -63
View File
@@ -1,7 +1,6 @@
syntax = "proto3";
package cline;
import "cline/common.proto";
import "cline/models.proto";
option java_package = "bot.cline.proto";
option java_multiple_files = true;
@@ -9,6 +8,7 @@ service StateService {
rpc getLatestState(EmptyRequest) returns (State);
rpc updateTerminalConnectionTimeout(UpdateTerminalConnectionTimeoutRequest) returns (UpdateTerminalConnectionTimeoutResponse);
rpc updateTerminalReuseEnabled(BooleanRequest) returns (Empty);
rpc updateDefaultTerminalProfile(StringRequest) returns (TerminalProfileUpdateResponse);
rpc getAvailableTerminalProfiles(EmptyRequest) returns (TerminalProfiles);
rpc subscribeToState(EmptyRequest) returns (stream State);
rpc toggleFavoriteModel(StringRequest) returns (Empty);
@@ -18,14 +18,8 @@ service StateService {
rpc updateSettings(UpdateSettingsRequest) returns (Empty);
rpc updateTelemetrySetting(TelemetrySettingRequest) returns (Empty);
rpc setWelcomeViewCompleted(BooleanRequest) returns (Empty);
rpc updateInfoBannerVersion(Int64Request) returns (Empty);
rpc updateModelBannerVersion(Int64Request) returns (Empty);
}
message DictationSettings {
bool feature_enabled = 1;
bool dictation_enabled = 2;
string dictation_language = 3;
}
message State {
string state_json = 1;
}
@@ -62,7 +56,6 @@ enum OpenaiReasoningEffort {
LOW = 0;
MEDIUM = 1;
HIGH = 2;
MINIMAL = 3;
}
enum McpDisplayMode {
@@ -113,16 +106,6 @@ message TelemetrySettingRequest {
TelemetrySettingEnum setting = 2;
}
// Browser settings for UpdateSettingsRequest
message BrowserSettingsUpdate {
optional Viewport viewport = 1;
optional string remote_browser_host = 2;
optional bool remote_browser_enabled = 3;
optional string chrome_executable_path = 4;
optional bool disable_tool_use = 5;
optional string custom_args = 6;
}
// Message for updating settings
message UpdateSettingsRequest {
Metadata metadata = 1;
@@ -143,12 +126,6 @@ message UpdateSettingsRequest {
optional FocusChainSettings focus_chain_settings = 17;
optional bool use_auto_condense = 18;
optional string custom_prompt = 19;
optional BrowserSettingsUpdate browser_settings = 20;
optional string default_terminal_profile = 21;
optional bool yolo_mode_toggled = 22;
optional DictationSettings dictation_settings = 23;
optional int32 auto_condense_threshold = 24;
optional bool multi_root_enabled = 25;
}
// Complete API Configuration message
@@ -160,10 +137,10 @@ message ApiConfiguration {
optional string lite_llm_base_url = 4;
optional string lite_llm_api_key = 5;
optional bool lite_llm_use_prompt_cache = 6;
map<string, string> open_ai_headers = 7;
optional string openai_headers = 7; // JSON string
optional string anthropic_base_url = 8;
optional string open_router_api_key = 9;
optional string open_router_provider_sorting = 10;
optional string openrouter_api_key = 9;
optional string openrouter_provider_sorting = 10;
optional string aws_access_key = 11;
optional string aws_secret_key = 12;
optional string aws_session_token = 13;
@@ -176,14 +153,14 @@ message ApiConfiguration {
optional string claude_code_path = 20;
optional string vertex_project_id = 21;
optional string vertex_region = 22;
optional string open_ai_base_url = 23;
optional string open_ai_api_key = 24;
optional string openai_base_url = 23;
optional string openai_api_key = 24;
optional string ollama_base_url = 25;
optional string ollama_api_options_ctx_num = 26;
optional string lm_studio_base_url = 27;
optional string gemini_api_key = 28;
optional string gemini_base_url = 29;
optional string open_ai_native_api_key = 30;
optional string openai_native_api_key = 30;
optional string deep_seek_api_key = 31;
optional string requesty_api_key = 32;
optional string requesty_base_url = 33;
@@ -219,65 +196,61 @@ message ApiConfiguration {
optional string qwen_code_oauth_path = 63;
optional string dify_api_key = 64;
optional string dify_base_url = 65;
optional string oca_base_url = 66;
optional string oca_api_key = 67;
optional string oca_refresh_token = 68;
// Plan mode configurations
optional ApiProvider plan_mode_api_provider = 100;
optional string plan_mode_api_provider = 100;
optional string plan_mode_api_model_id = 101;
optional int32 plan_mode_thinking_budget_tokens = 102;
optional string plan_mode_reasoning_effort = 103;
optional LanguageModelChatSelector plan_mode_vs_code_lm_model_selector = 104;
optional string plan_mode_vscode_lm_model_selector = 104; // JSON string
optional bool plan_mode_aws_bedrock_custom_selected = 105;
optional string plan_mode_aws_bedrock_custom_model_base_id = 106;
optional string plan_mode_open_router_model_id = 107;
optional OpenRouterModelInfo plan_mode_open_router_model_info = 108;
optional string plan_mode_open_ai_model_id = 109;
optional OpenAiCompatibleModelInfo plan_mode_open_ai_model_info = 110;
optional string plan_mode_openrouter_model_id = 107;
optional string plan_mode_openrouter_model_info = 108; // JSON string
optional string plan_mode_openai_model_id = 109;
optional string plan_mode_openai_model_info = 110; // JSON string
optional string plan_mode_ollama_model_id = 111;
optional string plan_mode_lm_studio_model_id = 112;
optional string plan_mode_lite_llm_model_id = 113;
optional LiteLLMModelInfo plan_mode_lite_llm_model_info = 114;
optional string plan_mode_lite_llm_model_info = 114; // JSON string
optional string plan_mode_requesty_model_id = 115;
optional OpenRouterModelInfo plan_mode_requesty_model_info = 116;
optional string plan_mode_requesty_model_info = 116; // JSON string
optional string plan_mode_together_model_id = 117;
optional string plan_mode_fireworks_model_id = 118;
optional string plan_mode_sap_ai_core_model_id = 119;
optional string plan_mode_huawei_cloud_maas_model_id = 120;
optional OpenRouterModelInfo plan_mode_huawei_cloud_maas_model_info = 121;
optional string plan_mode_huawei_cloud_maas_model_info = 121;
optional string plan_mode_vercel_ai_gateway_model_id = 122;
optional OpenRouterModelInfo plan_mode_vercel_ai_gateway_model_info = 123;
optional string plan_mode_oca_model_id = 124;
optional OcaModelInfo plan_mode_oca_model_info = 125;
optional string plan_mode_vercel_ai_gateway_model_info = 123;
// Act mode configurations
optional ApiProvider act_mode_api_provider = 200;
optional string act_mode_api_provider = 200;
optional string act_mode_api_model_id = 201;
optional int32 act_mode_thinking_budget_tokens = 202;
optional string act_mode_reasoning_effort = 203;
optional LanguageModelChatSelector act_mode_vs_code_lm_model_selector = 204;
optional string act_mode_vscode_lm_model_selector = 204; // JSON string
optional bool act_mode_aws_bedrock_custom_selected = 205;
optional string act_mode_aws_bedrock_custom_model_base_id = 206;
optional string act_mode_open_router_model_id = 207;
optional OpenRouterModelInfo act_mode_open_router_model_info = 208;
optional string act_mode_open_ai_model_id = 209;
optional OpenAiCompatibleModelInfo act_mode_open_ai_model_info = 210;
optional string act_mode_openrouter_model_id = 207;
optional string act_mode_openrouter_model_info = 208; // JSON string
optional string act_mode_openai_model_id = 209;
optional string act_mode_openai_model_info = 210; // JSON string
optional string act_mode_ollama_model_id = 211;
optional string act_mode_lm_studio_model_id = 212;
optional string act_mode_lite_llm_model_id = 213;
optional LiteLLMModelInfo act_mode_lite_llm_model_info = 214;
optional string act_mode_lite_llm_model_info = 214; // JSON string
optional string act_mode_requesty_model_id = 215;
optional OpenRouterModelInfo act_mode_requesty_model_info = 216;
optional string act_mode_requesty_model_info = 216; // JSON string
optional string act_mode_together_model_id = 217;
optional string act_mode_fireworks_model_id = 218;
optional string act_mode_sap_ai_core_model_id = 219;
optional string act_mode_huawei_cloud_maas_model_id = 220;
optional OpenRouterModelInfo act_mode_huawei_cloud_maas_model_info = 221;
optional string act_mode_huawei_cloud_maas_model_info = 221;
optional string act_mode_vercel_ai_gateway_model_id = 222;
optional OpenRouterModelInfo act_mode_vercel_ai_gateway_model_info = 223;
optional string act_mode_oca_model_id = 224;
optional OcaModelInfo act_mode_oca_model_info = 225;
optional string act_mode_vercel_ai_gateway_model_info = 223;
// Favorited model IDs
repeated string favorited_model_ids = 300;
// Extension fields for Bedrock Api Keys
optional string aws_authentication = 301;
@@ -295,11 +268,6 @@ message FocusChainSettings {
int32 remind_cline_interval = 2;
}
message Viewport {
int32 width = 1;
int32 height = 2;
}
message UpdateTerminalConnectionTimeoutResponse {
optional int32 timeout_ms = 1;
}
+18 -6
View File
@@ -5,6 +5,18 @@ import "cline/common.proto";
option java_package = "bot.cline.proto";
option java_multiple_files = true;
// Enum for webview provider types
enum WebviewProviderType {
SIDEBAR = 0;
TAB = 1;
}
// Define a new message type for webview provider info
message WebviewProviderTypeRequest {
Metadata metadata = 1;
WebviewProviderType provider_type = 2;
}
// Enum for ClineMessage type
enum ClineMessageType {
ASK = 0;
@@ -217,13 +229,13 @@ service UiService {
rpc onDidShowAnnouncement(EmptyRequest) returns (Boolean);
// Subscribe to addToInput events (when user adds content via context menu)
rpc subscribeToAddToInput(EmptyRequest) returns (stream String);
rpc subscribeToAddToInput(StringRequest) returns (stream String);
// Subscribe to MCP button clicked events
rpc subscribeToMcpButtonClicked(EmptyRequest) returns (stream Empty);
rpc subscribeToMcpButtonClicked(WebviewProviderTypeRequest) returns (stream Empty);
// Subscribe to history button click events
rpc subscribeToHistoryButtonClicked(EmptyRequest) returns (stream Empty);
rpc subscribeToHistoryButtonClicked(WebviewProviderTypeRequest) returns (stream Empty);
// Subscribe to chat button clicked events (when the chat button is clicked in VSCode)
rpc subscribeToChatButtonClicked(EmptyRequest) returns (stream Empty);
@@ -232,7 +244,7 @@ service UiService {
rpc subscribeToAccountButtonClicked(EmptyRequest) returns (stream Empty);
// Subscribe to settings button clicked events
rpc subscribeToSettingsButtonClicked(EmptyRequest) returns (stream Empty);
rpc subscribeToSettingsButtonClicked(WebviewProviderTypeRequest) returns (stream Empty);
// Subscribe to partial message updates (streaming Cline messages as they're built)
rpc subscribeToPartialMessage(EmptyRequest) returns (stream ClineMessage);
@@ -243,8 +255,8 @@ service UiService {
// Subscribe to relinquish control events
rpc subscribeToRelinquishControl(EmptyRequest) returns (stream Empty);
// Subscribe to focus chat input events
rpc subscribeToFocusChatInput(EmptyRequest) returns (stream Empty);
// Subscribe to focus chat input events with client ID
rpc subscribeToFocusChatInput(StringRequest) returns (stream Empty);
// Subscribe to webview visibility change events
rpc subscribeToDidBecomeVisible(EmptyRequest) returns (stream Empty);
Binary file not shown.
+2 -34
View File
@@ -17,44 +17,12 @@ service EnvService {
// Returns a stable machine identifier for telemetry distinctId purposes.
rpc getMachineId(cline.EmptyRequest) returns (cline.String);
// Returns the name and version of the host IDE or environment.
rpc getHostVersion(cline.EmptyRequest) returns (GetHostVersionResponse);
// Returns a URI that will redirect to the host environment.
// e.g. vscode://saoudrizwan.claude-dev, idea://, pycharm://, etc.
// If the host does not support URIs it should return empty.
rpc getIdeRedirectUri(cline.EmptyRequest) returns (cline.String);
// Returns the telemetry settings of the host environment. This may return UNSUPPORTED
// if the host does not specify telemetry settings for the plugin.
rpc getTelemetrySettings(cline.EmptyRequest) returns (GetTelemetrySettingsResponse);
// Returns events when the telemetry settings change.
rpc subscribeToTelemetrySettings(cline.EmptyRequest) returns (stream TelemetrySettingsEvent);
}
message GetHostVersionResponse {
// The name of the host platform, e.g VSCode, IntelliJ Ultimate Edition, etc.
// The name of the host platform, e.g VSCode
optional string platform = 1;
// The version of the host platform, e.g. 1.103.0 for VSCode, or 2025.1.1.1 for JetBrains IDEs.
// The version of the host platform, e.g. 1.103.0
optional string version = 2;
// The type of the cline host environment, e.g. 'VSCode Extension', 'Cline for JetBrains', 'CLI'
// This is different from the platform because there are many JetBrains IDEs, but they all use the same
// plugin.
optional string cline_type = 3;
// The version of the cline host environment, e.g. 33.2.10 for extension, or 1.0.6 for JetBrains.
optional string cline_version = 4;
}
enum Setting {
UNSUPPORTED = 0; // This host does not support this setting.
ENABLED = 1;
DISABLED = 2;
}
message GetTelemetrySettingsResponse {
Setting is_enabled = 1;
}
message TelemetrySettingsEvent {
Setting is_enabled = 1;
}
+36
View File
@@ -0,0 +1,36 @@
syntax = "proto3";
package host;
option java_package = "bot.cline.host.proto";
option java_multiple_files = true;
import "cline/common.proto";
/**
* The watch service is only here as example of a streaming rpc in the host bridge.
* This being replaced with a native JS file watcher.
*/
// WatchService provides methods for watching files in the IDE
service WatchService {
// Subscribe to file changes
rpc subscribeToFile(SubscribeToFileRequest) returns (stream FileChangeEvent);
}
// Request to subscribe to file changes
message SubscribeToFileRequest {
cline.Metadata metadata = 1;
string path = 2;
}
// Event representing a file change
message FileChangeEvent {
enum ChangeType {
CREATED = 0;
CHANGED = 1;
DELETED = 2;
}
string path = 1;
ChangeType type = 2;
string content = 3; // Optional content of the file after change
}
+4
View File
@@ -4,6 +4,8 @@ package host;
option java_package = "bot.cline.host.proto";
option java_multiple_files = true;
import "cline/common.proto";
// Provides methods for working with IDE windows and editors.
service WindowService {
// Opens a text document in the IDE editor and returns editor information.
@@ -38,6 +40,7 @@ service WindowService {
}
message ShowTextDocumentRequest {
cline.Metadata metadata = 1;
string path = 2;
optional ShowTextDocumentOptions options = 3;
}
@@ -56,6 +59,7 @@ message TextEditorInfo {
}
message ShowOpenDialogueRequest {
cline.Metadata metadata = 1;
optional bool can_select_many = 2;
optional string open_label = 3;
optional ShowOpenDialogueFilterOption filters = 4;
+5 -5
View File
@@ -18,6 +18,8 @@ service WorkspaceService {
// Get diagnostics from the workspace.
rpc getDiagnostics(GetDiagnosticsRequest) returns (GetDiagnosticsResponse);
// Returns workspace items (files/folders) matching a query for mention autocomplete
rpc searchWorkspaceItems(SearchWorkspaceItemsRequest) returns (SearchWorkspaceItemsResponse);
// Makes the problems panel/pane visible in the IDE and focuses it.
rpc openProblemsPanel(OpenProblemsPanelRequest) returns (OpenProblemsPanelResponse);
@@ -27,9 +29,6 @@ service WorkspaceService {
// Opens and focuses the Cline sidebar panel in the host IDE.
rpc openClineSidebarPanel(OpenClineSidebarPanelRequest) returns (OpenClineSidebarPanelResponse);
// Opens and focuses the terminal panel.
rpc openTerminalPanel(OpenTerminalRequest) returns (OpenTerminalResponse);
}
message GetWorkspacePathsRequest {
@@ -85,11 +84,12 @@ message SearchWorkspaceItemsResponse {
message OpenProblemsPanelRequest {}
message OpenProblemsPanelResponse {}
message OpenInFileExplorerPanelRequest {
string path = 1;
}
message OpenInFileExplorerPanelResponse {}
// Request/response for opening the Cline sidebar
message OpenClineSidebarPanelRequest {}
message OpenClineSidebarPanelResponse {}
message OpenTerminalRequest {}
message OpenTerminalResponse {}
+49 -2
View File
@@ -10,6 +10,7 @@ import * as path from "path"
import { rmrf } from "./file-utils.mjs"
import { main as generateHostBridgeClient } from "./generate-host-bridge-client.mjs"
import { main as generateProtoBusSetup } from "./generate-protobus-setup.mjs"
import { loadProtoDescriptorSet } from "./proto-utils.mjs"
const require = createRequire(import.meta.url)
const PROTOC = path.join(require.resolve("grpc-tools"), "../bin/protoc")
@@ -30,13 +31,14 @@ const TS_PROTO_OPTIONS = [
"esModuleInterop=true",
"outputServices=generic-definitions", // output generic ServiceDefinitions
"outputIndex=true", // output an index file for each package which exports all protos in the package.
"useOptionals=none", // scalar and message fields are required unless they are marked as optional.
"useOptionals=messages", // Message fields are optional, scalars are not.
"useDate=false", // Timestamp fields will not be automatically converted to Date.
]
async function main() {
await cleanup()
await compileProtos()
await checkProtos()
await generateProtoBusSetup()
await generateHostBridgeClient()
}
@@ -57,7 +59,7 @@ async function compileProtos() {
tsProtoc(TS_OUT_DIR, protoFiles, TS_PROTO_OPTIONS)
// grpc-js is used to generate service impls for the ProtoBus service.
tsProtoc(GRPC_JS_OUT_DIR, protoFiles, ["outputServices=grpc-js", ...TS_PROTO_OPTIONS])
tsProtoc(GRPC_JS_OUT_DIR, protoFiles, ["outputServices=grpc-js,outputClientImpl=false", ...TS_PROTO_OPTIONS])
// nice-js is used for the Host Bridge client impls because it uses promises.
tsProtoc(NICE_JS_OUT_DIR, protoFiles, ["outputServices=nice-grpc,useExactTypes=false", ...TS_PROTO_OPTIONS])
@@ -185,6 +187,51 @@ function checkAppleSiliconCompatibility() {
}
}
const int64TypeNames = ["TYPE_INT64", "TYPE_UINT64", "TYPE_SINT64", "TYPE_FIXED64", "TYPE_SFIXED64"]
async function checkProtos() {
const proto = await loadProtoDescriptorSet()
const int64Fields = []
for (const [packageName, packageDef] of Object.entries(proto)) {
for (const [messageName, def] of Object.entries(packageDef)) {
// Skip service definitions
if (def && typeof def === "object" && "service" in def) {
continue
}
// Check message fields
if (def && def.type && def.type.field) {
for (const field of def.type.field) {
if (int64TypeNames.includes(field.type)) {
const name = `${packageName}.${messageName}.${field.name}`
int64Fields.push({
name: name,
type: field.type,
})
}
}
}
}
}
if (int64Fields.length > 0) {
console.log(chalk.yellow(`\nWarning: Found ${int64Fields.length} fields using 64-bit integer types`))
for (const field of int64Fields) {
const typeNames = {
TYPE_INT64: "int64",
TYPE_UINT64: "uint64",
TYPE_SINT64: "sint64",
TYPE_FIXED64: "fixed64",
TYPE_SFIXED64: "sfixed64",
}
log_verbose(chalk.yellow(` - ${field.name} (${typeNames[field.type]})`))
}
log_verbose(chalk.yellow("\nWARNING: 64-bit integer fields detected in proto definitions"))
log_verbose(chalk.yellow("JavaScript cannot safely represent integers larger than 2^53-1 (Number.MAX_SAFE_INTEGER)."))
log_verbose(chalk.yellow("Consider using string representation for large numbers or implementing BigInt support.\n"))
}
}
function log_verbose(s) {
if (process.argv.includes("-v") || process.argv.includes("--verbose")) {
console.log(s)
-112
View File
@@ -1,112 +0,0 @@
#!/usr/bin/env npx tsx
/**
* Interactive Playwright launcher for the Cline VS Code extension.
*
* Overview:
* - Starts the mock Cline API server (from the e2e test fixtures).
* - Downloads a stable build of VS Code (via @vscode/test-electron).
* - Creates a temporary VS Code user profile directory.
* - Installs and links the Cline extension (from dist/e2e.vsix and the dev path).
* - Opens a test workspace and automatically reveals the Cline sidebar.
* - Records **all gRPC calls** during the session for later inspection.
* - Keeps VS Code running for manual interactive testing until the window is closed or Ctrl+C is pressed.
* - Cleans up all resources (mock server, temp profile, Electron process) on exit.
*
* Usage:
* 1. (Optional) Build and install the e2e extension:
* npm run test:e2e:build
*
* 2. From the repo root, start the interactive session:
* npm run test:playwright:interactive
*
* 3. VS Code will launch with the Cline extension loaded and gRPC recording enabled.
*
* 4. Interact with the extension manually.
*
* 5. Close the VS Code window or press Ctrl+C to end the session and trigger cleanup.
*/
import { downloadAndUnzipVSCode, SilentReporter } from "@vscode/test-electron"
import { mkdtempSync } from "fs"
import os from "os"
import path from "path"
import { _electron } from "playwright"
import { ClineApiServerMock } from "../src/test/e2e/fixtures/server"
import { E2ETestHelper } from "../src/test/e2e/utils/helpers"
async function main() {
await ClineApiServerMock.startGlobalServer()
const userDataDir = mkdtempSync(path.join(os.tmpdir(), "vsce-interactive"))
const executablePath = await downloadAndUnzipVSCode("stable", undefined, new SilentReporter())
// launch VSCode
const app = await _electron.launch({
executablePath,
env: {
...process.env,
TEMP_PROFILE: "true",
E2E_TEST: "true",
CLINE_ENVIRONMENT: "local",
GRPC_RECORDER_ENABLED: "true",
GRPC_RECORDER_TESTS_FILTERS_ENABLED: "true",
},
args: [
"--no-sandbox",
"--disable-updates",
"--disable-workspace-trust",
"--disable-extensions",
"--skip-welcome",
"--skip-release-notes",
`--user-data-dir=${userDataDir}`,
`--install-extension=${path.join(E2ETestHelper.CODEBASE_ROOT_DIR, "dist", "e2e.vsix")}`,
`--extensionDevelopmentPath=${E2ETestHelper.CODEBASE_ROOT_DIR}`,
path.join(E2ETestHelper.E2E_TESTS_DIR, "fixtures", "workspace"),
],
})
const page = await app.firstWindow()
await E2ETestHelper.openClineSidebar(page)
console.log("VSCode with Cline extension is now running!")
console.log(`Temporary data directory on: ${userDataDir}`)
console.log("You can manually interact with the extension.")
console.log("Press Ctrl+C to close when done.")
async function teardown() {
console.log("Cleaning up resources...")
try {
await app?.close()
await ClineApiServerMock.stopGlobalServer?.()
await E2ETestHelper.rmForRetries(userDataDir, { recursive: true })
} catch (e) {
console.log(`We could teardown interactive playwright properly, error:${e}`)
}
console.log("Finished cleaning up resources...")
}
process.on("SIGINT", async () => {
await teardown()
process.exit(0)
})
process.on("SIGTERM", async () => {
await teardown()
process.exit(0)
})
const win = await app.firstWindow()
win.on("close", async () => {
console.log("VS Code window closed.")
await teardown()
process.exit(0)
})
process.stdin.resume()
}
main().catch((err) => {
console.error("Failed to start:", err)
process.exit(1)
})
+21 -87
View File
@@ -6,102 +6,40 @@ import fs from "fs"
import { cp } from "fs/promises"
import { glob } from "glob"
import minimatch from "minimatch"
import os from "os"
import path from "path"
import { rmrf } from "./file-utils.mjs"
const BUILD_DIR = "dist-standalone"
const BINARIES_DIR = `${BUILD_DIR}/binaries`
const RUNTIME_DEPS_DIR = "standalone/runtime-files"
const IS_DEBUG_BUILD = process.env.IS_DEBUG_BUILD === "true"
// This should match the node version packaged with the JetBrains plugin.
const TARGET_NODE_VERSION = "22.15.0"
const TARGET_PLATFORMS = [
{ platform: "win32", arch: "x64", targetDir: "win-x64" },
{ platform: "darwin", arch: "x64", targetDir: "darwin-x64" },
{ platform: "darwin", arch: "arm64", targetDir: "darwin-arm64" },
{ platform: "linux", arch: "x64", targetDir: "linux-x64" },
]
const SUPPORTED_BINARY_MODULES = ["better-sqlite3"]
const UNIVERSAL_BUILD = !process.argv.includes("-s")
const IS_VERBOSE = process.argv.includes("-v") || process.argv.includes("--verbose")
async function main() {
await installNodeDependencies()
if (UNIVERSAL_BUILD) {
console.log("Building universal package for all platforms...")
await packageAllBinaryDeps()
} else {
console.log(`Building package for ${os.platform()}-${os.arch()}...`)
}
await zipDistribution()
}
async function installNodeDependencies() {
// Clean modules from any previous builds
await rmrf(path.join(BUILD_DIR, "node_modules"))
await rmrf(path.join(BINARIES_DIR))
await cpr(RUNTIME_DEPS_DIR, BUILD_DIR)
console.log("Running npm install in distribution directory...")
execSync("npm install", { stdio: "inherit", cwd: BUILD_DIR })
const cwd = process.cwd()
process.chdir(BUILD_DIR)
// Move the vscode directory into node_modules.
// It can't be installed using npm because it will create a symlink which cannot be unzipped correctly on windows.
fs.renameSync(`${BUILD_DIR}/vscode`, `${BUILD_DIR}/node_modules/vscode`)
}
/**
* Downloads prebuilt binaries for each platform for the modules that include binaries. It uses `npx prebuild-install`
* to download the binary.
*
* The modules are downloaded to dist-standalone/binaries/{os}-{platform}/.
* When cline-core is installed, the installer should use the correct module for the current platform.
*/
async function packageAllBinaryDeps() {
// Check for native .node modules.
const allNativeModules = await glob("**/*.node", { cwd: path.join(BUILD_DIR, "node_modules"), nodir: true })
const isAllowed = (path) => SUPPORTED_BINARY_MODULES.some((allowed) => path.includes(allowed))
const blocked = allNativeModules.filter((x) => !isAllowed(x))
if (blocked.length > 0) {
console.error(`Error: Native node modules cannot be included in the standalone distribution:\n\n${blocked.join("\n")}`)
console.error(
"\nThese modules must support prebuilt-install and be added to the supported list in scripts/package-standalone.mjs",
)
try {
execSync("npm install", { stdio: "inherit" })
// Move the vscode directory into node_modules.
// It can't be installed using npm because it will create a symlink which cannot be unzipped correctly on windows.
fs.renameSync("vscode", path.join("node_modules", "vscode"))
} catch (error) {
console.error("Error during setup:", error)
process.exit(1)
} finally {
process.chdir(cwd)
}
for (const module of SUPPORTED_BINARY_MODULES) {
console.log(`Installing binaries for ${module}...`)
const src = path.join(BUILD_DIR, "node_modules", module)
if (!fs.existsSync(src)) {
console.warn(`Warning: Trying to install binaries for the module '${module}', but it is not being used by cline.`)
continue
}
for (const { platform, arch, targetDir } of TARGET_PLATFORMS) {
const binaryDir = `${BINARIES_DIR}/${targetDir}/node_modules`
fs.mkdirSync(binaryDir, { recursive: true })
// Copy the module from the build dir
const dest = path.join(binaryDir, module)
await cpr(src, dest)
// Download the binary libs
const v = IS_VERBOSE ? "--verbose" : ""
const cmd = `npx prebuild-install --platform=${platform} --arch=${arch} --target=${TARGET_NODE_VERSION} ${v}`
log_verbose(`${module}: ${cmd}`)
execSync(cmd, { cwd: dest, stdio: "inherit" })
log_verbose("")
}
// Remove the original module with the host platform binaries installed directly into node_modules.
log_verbose(`Cleaning up host version of ${module}`)
await rmrf(src)
log_verbose("")
// Check for native .node modules.
const nativeModules = await glob("**/*.node", { cwd: BUILD_DIR, nodir: true })
if (nativeModules.length > 0) {
console.error("Native node modules cannot be included in the standalone distribution:\n", nativeModules.join("\n"))
process.exit(1)
}
}
@@ -109,13 +47,10 @@ async function zipDistribution() {
// Zip the build directory (excluding any pre-existing output zip).
const zipPath = path.join(BUILD_DIR, "standalone.zip")
const output = fs.createWriteStream(zipPath)
const startTime = Date.now()
const archive = archiver("zip", { zlib: { level: 6 } })
const archive = archiver("zip", { zlib: { level: 3 } })
output.on("close", () => {
const endTime = Date.now()
const duration = (endTime - startTime) / 1000
console.log(`Created ${zipPath} (${(archive.pointer() / 1024 / 1024).toFixed(1)} MB) in ${duration.toFixed(2)} seconds`)
console.log(`Created ${zipPath} (${(archive.pointer() / 1024 / 1024).toFixed(1)} MB)`)
})
archive.on("warning", (err) => {
console.warn(`Warning: ${err}`)
@@ -138,7 +73,7 @@ async function zipDistribution() {
// Add the whole cline directory under "extension", except the for the ignored files.
archive.directory(process.cwd(), "extension", (entry) => {
if (isIgnored(entry.name)) {
//log_verbose("Ignoring", entry.name)
log_verbose("Ignoring", entry.name)
return false
}
return entry
@@ -210,7 +145,7 @@ function createIsIgnored(standaloneIgnores) {
let allIgnore = [...defaultIgnore, ...expandedIgnore, ...standaloneIgnores]
// Map files need to be included in the debug build. Remove .map ignores when IS_DEBUG_BUILD is set
if (IS_DEBUG_BUILD) {
if (process.env.IS_DEBUG_BUILD) {
allIgnore = allIgnore.filter((pattern) => !pattern.endsWith(".map"))
console.log("Debug build: Including .map files in package")
}
@@ -232,7 +167,6 @@ function createIsIgnored(standaloneIgnores) {
/* cp -r */
async function cpr(source, dest) {
log_verbose(`Copying ${source} -> ${dest}`)
await cp(source, dest, {
recursive: true,
preserveTimestamps: true,
@@ -241,7 +175,7 @@ async function cpr(source, dest) {
}
function log_verbose(...args) {
if (IS_VERBOSE) {
if (process.argv.includes("-v") || process.argv.includes("--verbose")) {
console.log(...args)
}
}
-377
View File
@@ -1,377 +0,0 @@
#!/usr/bin/env node
/**
* Nightly publish script for VS Code extension
* Converts package.json to testing version, packages, publishes, and restores
*
* This script:
* 1. Backs up the original package.json
* 2. Updates package.json with:
* - New version (major.minor.timestamp format)
* - Changes name to "cline-nightly"
* - Changes displayName to "Cline (Nightly)"
* 3. Packages the extension as a .vsix file
* 4. Publishes to VS Code Marketplace (if VSCE_PAT is set)
* 5. Publishes to OpenVSX Registry (if OVSX_PAT is set)
* 6. Restores the original package.json
*
* Usage:
* npm run publish:marketplace:nightly
* npm run publish:marketplace:nightly -- --dry-run
*
* Environment variables:
* VSCE_PAT - Personal Access Token for VS Code Marketplace
* OVSX_PAT - Personal Access Token for OpenVSX Registry
*
* Dependencies:
* - vsce (VS Code Extension Manager)
* - ovsx (OpenVSX CLI)
*/
import { execFileSync, execSync } from "node:child_process"
import fs from "node:fs"
import path from "node:path"
import { fileURLToPath } from "node:url"
// Get __dirname equivalent in ES modules
const __filename = fileURLToPath(import.meta.url)
const __dirname = path.dirname(__filename)
// ANSI color codes for console output
const colors = {
reset: "\x1b[0m",
red: "\x1b[31m",
green: "\x1b[32m",
yellow: "\x1b[33m",
}
// Logging utilities
const log = {
info: (msg) => console.log(`${colors.green}[INFO]${colors.reset} ${msg}`),
warn: (msg) => console.log(`${colors.yellow}[WARN]${colors.reset} ${msg}`),
error: (msg) => console.error(`${colors.red}[ERROR]${colors.reset} ${msg}`),
}
// Configuration
const config = {
// The name and display name for the nightly version
nightlyName: "cline-nightly",
nightlyDisplayName: "Cline (Nightly)",
projectRoot: path.join(__dirname, ".."),
get packageJsonPath() {
return path.join(this.projectRoot, "package.json")
},
get packageBackupPath() {
return path.join(this.projectRoot, "package.json.backup")
},
get distDir() {
return path.join(this.projectRoot, "dist")
},
get vsixPath() {
return path.join(this.distDir, "cline-nightly.vsix")
},
}
// Utility class for managing the publish process
class NightlyPublisher {
constructor() {
this.originalPackageJson = null
this.hasBackup = false
}
/**
* Check if required dependencies are installed
*/
checkDependencies() {
const dependencies = [
{ name: "vsce", check: "vsce --version" },
{ name: "npx", check: "npx --version" },
]
const missing = []
for (const dep of dependencies) {
try {
execSync(dep.check, { stdio: "ignore" })
} catch {
missing.push(dep.name)
}
}
if (missing.length > 0) {
throw new Error(
`Missing required dependencies: ${missing.join(", ")}. Please install them before running this script.`,
)
}
log.info("All dependencies are installed")
}
/**
* Check if a command exists
*/
commandExists(command) {
try {
execSync(`which ${command}`, { stdio: "ignore" })
return true
} catch {
return false
}
}
/**
* Create backup of package.json
*/
backupPackageJson() {
if (!fs.existsSync(config.packageJsonPath)) {
throw new Error(`package.json not found at ${config.packageJsonPath}`)
}
log.info("Backing up original package.json")
this.originalPackageJson = fs.readFileSync(config.packageJsonPath, "utf-8")
fs.writeFileSync(config.packageBackupPath, this.originalPackageJson)
this.hasBackup = true
}
/**
* Restore original package.json
*/
restorePackageJson() {
if (this.hasBackup && fs.existsSync(config.packageBackupPath)) {
log.info("Restoring original package.json")
fs.writeFileSync(config.packageJsonPath, this.originalPackageJson)
fs.unlinkSync(config.packageBackupPath)
this.hasBackup = false
}
}
/**
* Generate new version with timestamp
* Format: major.minor.timestamp
*/
generateVersion(currentVersion) {
// Extract major.minor from current version (e.g., "3.27.1" -> "3.27")
const versionParts = currentVersion.split(".")
if (versionParts.length < 2) {
throw new Error(`Invalid version format: ${currentVersion}`)
}
const major = versionParts[0]
const minor = versionParts[1]
const timestamp = Math.floor(Date.now() / 1000)
return `${major}.${minor}.${timestamp}`
}
/**
* Update package.json with nightly configuration
*/
updatePackageJson() {
// Replace any occurrences cline. or claude-dev with nightly name
const rawContent = fs.readFileSync(config.packageJsonPath, "utf-8")
const content = rawContent.replaceAll("claude-dev", config.nightlyName).replaceAll('"cline.', `"${config.nightlyName}.`)
const pkg = JSON.parse(content)
const currentVersion = pkg.version
if (!currentVersion) {
throw new Error("Could not read version from package.json")
}
log.info(`Current version: ${currentVersion}`)
const newVersion = this.generateVersion(currentVersion)
log.info(`New version: ${newVersion}`)
// Update package.json fields
pkg.version = newVersion
pkg.name = config.nightlyName
pkg.displayName = config.nightlyDisplayName
pkg.contributes.viewsContainers.activitybar.title = config.nightlyDisplayName
// Save updated package.json
log.info("Updating package.json for nightly build")
fs.writeFileSync(config.packageJsonPath, JSON.stringify(pkg, null, "\t"))
return newVersion
}
/**
* Package the extension
*/
packageExtension() {
// Ensure dist directory exists
if (!fs.existsSync(config.distDir)) {
fs.mkdirSync(config.distDir, { recursive: true })
}
log.info("Packaging extension")
const args = ["package", "--pre-release", "--no-update-package-json", "--no-git-tag-version", "--out", config.vsixPath]
try {
execFileSync("vsce", args, {
stdio: "inherit",
cwd: config.projectRoot,
})
log.info(`Package created: ${config.vsixPath}`)
} catch (error) {
throw new Error(`Failed to package extension: ${error.message}`)
}
}
/**
* Publish to VS Code Marketplace
*/
publishToVSCodeMarketplace() {
const token = process.env.VSCE_PAT
if (!token) {
log.warn("VSCE_PAT not set, skipping VS Code Marketplace publish")
return false
}
log.info("Publishing to VS Code Marketplace")
const args = ["publish", "--pre-release", "--no-git-tag-version", "--packagePath", config.vsixPath]
try {
execFileSync("vsce", args, {
env: { ...process.env, VSCE_PAT: token },
stdio: "inherit",
cwd: config.projectRoot,
})
log.info("Successfully published to VS Code Marketplace")
return true
} catch (error) {
throw new Error(`Failed to publish to VS Code Marketplace: ${error.message}`)
}
}
/**
* Publish to OpenVSX Registry
*/
publishToOpenVSX() {
const token = process.env.OVSX_PAT
if (!token) {
log.warn("OVSX_PAT not set, skipping OpenVSX Registry publish")
return false
}
log.info("Publishing to OpenVSX Registry")
const args = ["ovsx", "publish", "--pre-release", "--packagePath", config.vsixPath, "--pat", token]
try {
execFileSync("npx", args, {
stdio: "inherit",
cwd: config.projectRoot,
})
log.info("Successfully published to OpenVSX Registry")
return true
} catch (error) {
throw new Error(`Failed to publish to OpenVSX Registry: ${error.message}`)
}
}
/**
* Main execution flow
*/
async run(isDryRun = false) {
try {
log.info(`Starting nightly publish process${isDryRun ? " (dry run)" : ""}`)
// Step 1: Check dependencies
this.checkDependencies()
// Step 2: Backup package.json
this.backupPackageJson()
// Step 3: Update package.json
const newVersion = this.updatePackageJson()
// Step 4: Package extension
this.packageExtension()
// Step 5: Publish to marketplaces (skip if dry run)
let vsCodePublished = false
let openVSXPublished = false
if (isDryRun) {
log.info("Dry run mode: Skipping marketplace publishing")
} else {
vsCodePublished = this.publishToVSCodeMarketplace()
openVSXPublished = this.publishToOpenVSX()
}
// Summary
log.info(`Nightly publish process completed successfully${isDryRun ? " (dry run)" : ""}`)
log.info(`Package created for v${newVersion}: ${config.vsixPath}`)
if (!isDryRun && !vsCodePublished && !openVSXPublished) {
log.warn("Extension was packaged but not published to any marketplace")
log.warn("Set VSCE_PAT and/or OVSX_PAT environment variables to enable publishing")
}
} catch (error) {
log.error(`Publish failed: ${error.message}`)
process.exit(1)
} finally {
// Always restore package.json
this.restorePackageJson()
}
}
}
// Handle cleanup on process exit
const publisher = new NightlyPublisher()
process.on("exit", () => {
publisher.restorePackageJson()
})
process.on("SIGINT", () => {
log.info("\nInterrupted, cleaning up...")
publisher.restorePackageJson()
process.exit(130)
})
process.on("SIGTERM", () => {
log.info("\nTerminated, cleaning up...")
publisher.restorePackageJson()
process.exit(143)
})
// Parse command line arguments
const args = process.argv.slice(2)
const isDryRun = args.includes("--dry-run") || args.includes("-n")
const showHelp = args.includes("--help") || args.includes("-h")
if (showHelp) {
console.log(`
Nightly publish script for VS Code extension
Usage:
npm run publish:marketplace:nightly [options]
Options:
--dry-run, -n Run without actually publishing (package only)
--help, -h Show this help message
Environment variables:
VSCE_PAT Personal Access Token for VS Code Marketplace
OVSX_PAT Personal Access Token for OpenVSX Registry
Examples:
npm run publish:marketplace:nightly # Full publish
npm run publish:marketplace:nightly -- --dry-run # Package only
VSCE_PAT="token" npm run publish:marketplace:nightly # Publish to VS Code only
`)
process.exit(0)
}
// Run the publisher
publisher.run(isDryRun).catch((error) => {
log.error(error.message)
process.exit(1)
})
+1 -3
View File
@@ -9,7 +9,7 @@ if [[ "${1:-}" == "-h" ]]; then
fi
CORE_DIR=~/.cline/core
INSTALL_DIR=$CORE_DIR/dev-instance/
INSTALL_DIR=$CORE_DIR/0.0.1
LOG_FILE=~/.cline/cline-core-service.log
ZIP_FILE=standalone.zip
@@ -25,6 +25,4 @@ unp $ZIP_FILE > /dev/null
pkill -f cline-core.js || true
echo pwd: $(pwd)
set -x
NODE_PATH=./node_modules DEV_WORKSPACE_FOLDER=/tmp/ node cline-core.js 2>&1 | tee $LOG_FILE
+30
View File
@@ -0,0 +1,30 @@
#!/usr/bin/env node
const { execSync } = require("child_process")
const process = require("process")
try {
if (process.platform === "linux") {
console.log("Detected Linux environment.")
execSync("which xvfb-run", { stdio: "ignore" })
console.log("xvfb-run is installed. Running tests with xvfb-run...")
execSync("xvfb-run -a npm run test:coverage", { stdio: "inherit" })
} else {
console.log("Non-Linux environment detected. Running tests normally.")
execSync("npm run test:integration", { stdio: "inherit" })
}
} catch (error) {
if (process.platform === "linux") {
console.error(
`Error: xvfb-run is not installed.\n` +
`Please install it using the following command:\n` +
` Debian/Ubuntu: sudo apt install xvfb\n` +
` RHEL/CentOS: sudo yum install xvfb\n` +
` Arch Linux: sudo pacman -S xvfb`,
)
} else {
console.error("Error running tests:", error.message)
}
process.exit(1)
}
+9 -20
View File
@@ -3,11 +3,7 @@ import * as grpc from "@grpc/grpc-js"
import { ReflectionService } from "@grpc/reflection"
import * as health from "grpc-health-check"
import * as os from "os"
import { type DiffServiceServer, DiffServiceService } from "../src/generated/grpc-js/host/diff"
import { type EnvServiceServer, EnvServiceService } from "../src/generated/grpc-js/host/env"
import { type TestingServiceServer, TestingServiceService } from "../src/generated/grpc-js/host/testing"
import { type WindowServiceServer, WindowServiceService } from "../src/generated/grpc-js/host/window"
import { type WorkspaceServiceServer, WorkspaceServiceService } from "../src/generated/grpc-js/host/workspace"
import { host } from "src/generated/grpc-js/index"
import { getPackageDefinition } from "./proto-utils.mjs"
export async function startTestHostBridgeServer() {
@@ -18,11 +14,11 @@ export async function startTestHostBridgeServer() {
healthImpl.addToServer(server)
// Add host bridge services using the mock implementations
server.addService(WorkspaceServiceService, createMockService<WorkspaceServiceServer>("WorkspaceService"))
server.addService(WindowServiceService, createMockService<WindowServiceServer>("WindowService"))
server.addService(EnvServiceService, createMockService<EnvServiceServer>("EnvService"))
server.addService(DiffServiceService, createMockService<DiffServiceServer>("DiffService"))
server.addService(TestingServiceService, createMockService<TestingServiceServer>("TestingService"))
server.addService(host.WorkspaceServiceService, createMockService<host.WorkspaceServiceServer>("WorkspaceService"))
server.addService(host.WindowServiceService, createMockService<host.WindowServiceServer>("WindowService"))
server.addService(host.EnvServiceService, createMockService<host.EnvServiceServer>("EnvService"))
server.addService(host.DiffServiceService, createMockService<host.DiffServiceServer>("DiffService"))
server.addService(host.WatchServiceService, createMockService<host.WatchServiceServer>("WatchService"))
// Load package definition for reflection service
const packageDefinition = await getPackageDefinition()
@@ -62,9 +58,8 @@ function createMockService<T extends grpc.UntypedServiceImplementation>(serviceN
// Special cases that need specific return values
switch (prop) {
case "getWorkspacePaths":
const workspaceDir = process.env.TEST_HOSTBRIDGE_WORKSPACE_DIR || "/test-workspace"
callback(null, {
paths: [workspaceDir],
paths: ["/test-workspace"],
})
return
@@ -74,12 +69,6 @@ function createMockService<T extends grpc.UntypedServiceImplementation>(serviceN
})
return
case "getTelemetrySettings":
callback(null, {
isEnabled: 2, // Setting.DISABLED
})
return
case "clipboardReadText":
callback(null, {
value: "",
@@ -126,8 +115,8 @@ function createMockService<T extends grpc.UntypedServiceImplementation>(serviceN
})
return
// For streaming methods (like subscribeToTelemetrySettings)
case "subscribeToTelemetrySettings":
// For streaming methods (like subscribeToFile)
case "subscribeToFile":
// Just end the stream immediately
call.end()
return
-183
View File
@@ -1,183 +0,0 @@
#!/usr/bin/env npx tsx
/**
* Simple Cline gRPC Server
*
* This script provides a minimal way to run the Cline core gRPC service
* without requiring the full installation, while automatically mocking all external services. Simply run:
*
* # One-time setup (generates protobuf files)
* npm run compile-standalone
* npm run test:sca-server
*
* The following components are started automatically:
* 1. HostBridge test server
* 2. ClineApiServerMock (mock implementation of the Cline API)
* 3. AuthServiceMock (activated if E2E_TEST="true")
*
* Environment Variables for Customization:
* PROJECT_ROOT - Override project root directory (default: parent of scripts dir)
* CLINE_DIST_DIR - Override distribution directory (default: PROJECT_ROOT/dist-standalone)
* CLINE_CORE_FILE - Override core file name (default: cline-core.js)
* PROTOBUS_PORT - gRPC server port (default: 26040)
* HOSTBRIDGE_PORT - HostBridge server port (default: 26041)
* WORKSPACE_DIR - Working directory (default: current directory)
* E2E_TEST - Enable E2E test mode (default: true)
* CLINE_ENVIRONMENT - Environment setting (default: local)
*
* Ideal for local development, testing, or lightweight E2E scenarios.
*/
import * as fs from "node:fs"
import { mkdtempSync, rmSync } from "node:fs"
import * as os from "node:os"
import { ChildProcess, execSync, spawn } from "child_process"
import * as path from "path"
import { ClineApiServerMock } from "../src/test/e2e/fixtures/server/index"
const PROTOBUS_PORT = process.env.PROTOBUS_PORT || "26040"
const HOSTBRIDGE_PORT = process.env.HOSTBRIDGE_PORT || "26041"
const WORKSPACE_DIR = process.env.WORKSPACE_DIR || process.cwd()
const E2E_TEST = process.env.E2E_TEST || "true"
const CLINE_ENVIRONMENT = process.env.CLINE_ENVIRONMENT || "local"
const USE_C8 = process.env.USE_C8 === "true"
// Locate the standalone build directory and core file with flexible path resolution
const projectRoot = process.env.PROJECT_ROOT || path.resolve(__dirname, "..")
const distDir = process.env.CLINE_DIST_DIR || path.join(projectRoot, "dist-standalone")
const clineCoreFile = process.env.CLINE_CORE_FILE || "cline-core.js"
const coreFile = path.join(distDir, clineCoreFile)
const childProcesses: ChildProcess[] = []
async function main(): Promise<void> {
console.log("Starting Simple Cline gRPC Server...")
console.log(`Project Root: ${projectRoot}`)
console.log(`Workspace: ${WORKSPACE_DIR}`)
console.log(`ProtoBus Port: ${PROTOBUS_PORT}`)
console.log(`HostBridge Port: ${HOSTBRIDGE_PORT}`)
console.log(`Looking for standalone build at: ${coreFile}`)
if (!fs.existsSync(coreFile)) {
console.error(`Standalone build not found at: ${coreFile}`)
console.error("Available environment variables for customization:")
console.error(" PROJECT_ROOT - Override project root directory")
console.error(" CLINE_DIST_DIR - Override distribution directory")
console.error(" CLINE_CORE_FILE - Override core file name")
console.error("")
console.error("To build the standalone version, run: npm run compile-standalone")
process.exit(1)
}
try {
await ClineApiServerMock.startGlobalServer()
console.log("Cline API Server started in-process")
} catch (error) {
console.error("Failed to start Cline API Server:", error)
process.exit(1)
}
const extensionsDir = path.join(distDir, "vsce-extension")
const userDataDir = mkdtempSync(path.join(os.tmpdir(), "vsce"))
const clineTestWorkspace = mkdtempSync(path.join(os.tmpdir(), "cline-test-workspace-"))
console.log("Starting HostBridge test server...")
const hostbridge: ChildProcess = spawn("npx", ["tsx", path.join(__dirname, "test-hostbridge-server.ts")], {
stdio: "pipe",
env: {
...process.env,
TEST_HOSTBRIDGE_WORKSPACE_DIR: clineTestWorkspace,
HOST_BRIDGE_ADDRESS: `127.0.0.1:${HOSTBRIDGE_PORT}`,
},
})
childProcesses.push(hostbridge)
console.log(`Temp user data dir: ${userDataDir}`)
console.log(`Temp extensions dir: ${extensionsDir}`)
// Extract standalone.zip if needed
const standaloneZipPath = path.join(distDir, "standalone.zip")
if (!fs.existsSync(standaloneZipPath)) {
console.error(`standalone.zip not found at: ${standaloneZipPath}`)
process.exit(1)
}
console.log("Extracting standalone.zip to extensions directory...")
try {
if (!fs.existsSync(extensionsDir)) {
execSync(`unzip -q "${standaloneZipPath}" -d "${extensionsDir}"`, { stdio: "inherit" })
}
console.log(`Successfully extracted standalone.zip to: ${extensionsDir}`)
} catch (error) {
console.error("Failed to extract standalone.zip:", error)
process.exit(1)
}
const covDir = path.join(projectRoot, `coverage/coverage-core-${PROTOBUS_PORT}`)
const baseArgs = ["--enable-source-maps", path.join(distDir, "cline-core.js")]
const spawnArgs = USE_C8 ? ["c8", "--report-dir", covDir, "node", ...baseArgs] : ["node", ...baseArgs]
console.log(`Starting Cline Core Service... (useC8=${USE_C8})`)
const coreService: ChildProcess = spawn("npx", spawnArgs, {
cwd: projectRoot,
env: {
...process.env,
NODE_PATH: "./node_modules",
DEV_WORKSPACE_FOLDER: WORKSPACE_DIR,
PROTOBUS_ADDRESS: `127.0.0.1:${PROTOBUS_PORT}`,
HOST_BRIDGE_ADDRESS: `localhost:${HOSTBRIDGE_PORT}`,
E2E_TEST,
CLINE_ENVIRONMENT,
CLINE_DIR: userDataDir,
INSTALL_DIR: extensionsDir,
},
stdio: "inherit",
})
childProcesses.push(coreService)
const shutdown = async () => {
console.log("\nShutting down services...")
while (childProcesses.length > 0) {
const child = childProcesses.pop()
if (child && !child.killed) child.kill("SIGINT")
}
await ClineApiServerMock.stopGlobalServer()
try {
rmSync(userDataDir, { recursive: true, force: true })
rmSync(clineTestWorkspace, { recursive: true, force: true })
console.log("Cleaned up temporary directories")
} catch (err) {
console.warn("Failed to cleanup temp directories:", err)
}
process.exit(0)
}
process.on("SIGINT", shutdown)
process.on("SIGTERM", shutdown)
coreService.on("exit", (code) => {
console.log(`Core service exited with code ${code}`)
shutdown()
})
hostbridge.on("exit", (code) => {
console.log(`HostBridge exited with code ${code}`)
shutdown()
})
console.log(`Cline gRPC Server is running on 127.0.0.1:${PROTOBUS_PORT}`)
console.log("Press Ctrl+C to stop")
}
if (require.main === module) {
main().catch((err) => {
console.error("Failed to start simple Cline server:", err)
process.exit(1)
})
}
-225
View File
@@ -1,225 +0,0 @@
#!/usr/bin/env npx tsx
/**
* Test Orchestrator
*
* Automates server lifecycle for running spec files against the standalone server.
*
* Prerequisites:
* Build standalone first: `npm run compile-standalone`
*
* Usage:
* - Single file: `npm run test:tp-orchestrator path/to/spec.json`
* - All specs dir: `npm run test:tp-orchestrator tests/specs`
*
* Flags:
* --server-logs Show server logs (hidden by default)
* --count=<number> Repeat execution N times (default: 1)
* --fix Automatically update spec files with actual responses
* --coverage Generate integration test coverage information
*
*/
import { ChildProcess, spawn } from "child_process"
import fs from "fs"
import minimist from "minimist"
import net from "net"
import path from "path"
import kill from "tree-kill"
let showServerLogs = false
let fix = false
let coverage = false
const WAIT_SERVER_DEFAULT_TIMEOUT = 15000
const usedPorts = new Set<number>()
/**
* Find an available TCP port within the given range [min, max].
*
* - Ports are allocated sequentially (starting at `min`) rather than randomly,
* which avoids accidental reuse when running hundreds of tests in a row.
* - Each successfully allocated port is tracked in `usedPorts` to guarantee
* it is never handed out again within the lifetime of this orchestrator.
* - Before returning, the function binds a temporary server to the port to
* verify that the OS really considers it available, then immediately closes it.
*
* This approach makes the orchestrator much more robust on CI (e.g. GitHub Actions),
* where a just-terminated server may leave its socket in TIME_WAIT and cause
* flakiness if the same port is reallocated too soon.
*/
async function getAvailablePort(min = 20000, max = 49151): Promise<number> {
return new Promise((resolve, _) => {
const tryPort = (candidate?: number) => {
const port = candidate ?? Math.floor(Math.random() * (max - min + 1)) + min
if (usedPorts.has(port)) {
// already allocated in this run
return tryPort()
}
const server = net.createServer()
server.once("error", () => tryPort())
server.once("listening", () => {
server.close(() => {
usedPorts.add(port) // mark reserved
resolve(port)
})
})
server.listen(port, "127.0.0.1")
}
tryPort()
})
}
// Poll until a given TCP port on a host is accepting connections.
async function waitForPort(port: number, host = "127.0.0.1", timeout = 10000): Promise<void> {
const start = Date.now()
const waitForPortSleepMs = 100
while (Date.now() - start < timeout) {
await new Promise((res) => setTimeout(res, waitForPortSleepMs))
try {
await new Promise<void>((resolve, reject) => {
const socket = net.connect(port, host, () => {
socket.destroy()
resolve()
})
socket.on("error", reject)
})
return
} catch {
// try again
}
}
throw new Error(`Timeout waiting for ${host}:${port}`)
}
async function startServer(): Promise<{ server: ChildProcess; grpcPort: string }> {
const grpcPort = (await getAvailablePort()).toString()
const hostbridgePort = (await getAvailablePort()).toString()
const server = spawn("npx", ["tsx", "scripts/test-standalone-core-api-server.ts"], {
stdio: showServerLogs ? "inherit" : "pipe",
env: {
...process.env,
PROTOBUS_PORT: grpcPort,
HOSTBRIDGE_PORT: hostbridgePort,
USE_C8: coverage ? "true" : "false",
},
})
// Wait for either the server to become ready or fail on spawn error
await Promise.race([
waitForPort(Number(grpcPort), "127.0.0.1", WAIT_SERVER_DEFAULT_TIMEOUT),
new Promise((_, reject) => server.once("error", reject)),
])
return { server, grpcPort }
}
function stopServer(server: ChildProcess): Promise<void> {
return new Promise((resolve) => {
if (!server.pid) return resolve()
kill(server.pid, "SIGINT", (err) => {
if (err) console.warn("Failed to kill server process:", err)
server.once("exit", () => resolve())
})
})
}
function runTestingPlatform(specFile: string, grpcPort: string): Promise<void> {
return new Promise((resolve, reject) => {
const testProcess = spawn("npx", ["ts-node", "index.ts", specFile, ...(fix ? ["--fix"] : [])], {
cwd: path.join(process.cwd(), "testing-platform"),
stdio: "inherit",
env: {
...process.env,
STANDALONE_GRPC_SERVER_PORT: grpcPort,
},
})
testProcess.once("error", reject)
testProcess.once("exit", (code) => {
code === 0 ? resolve() : reject(new Error(`Exit code ${code}`))
})
})
}
async function runSpec(specFile: string): Promise<void> {
const { server, grpcPort } = await startServer()
try {
await runTestingPlatform(specFile, grpcPort)
console.log(`${path.basename(specFile)} passed`)
} finally {
await stopServer(server)
}
}
function collectSpecFiles(inputPath: string): string[] {
const fullPath = path.resolve(inputPath)
if (!fs.existsSync(fullPath)) throw new Error(`Path does not exist: ${fullPath}`)
const stat = fs.statSync(fullPath)
if (stat.isDirectory()) {
return fs
.readdirSync(fullPath)
.filter((f) => f.endsWith(".json"))
.map((f) => path.join(fullPath, f))
}
if (fullPath.endsWith(".json")) return [fullPath]
throw new Error("Spec path must be a JSON file or a folder containing JSON files")
}
async function runAll(inputPath: string, count: number) {
const specFiles = collectSpecFiles(inputPath)
if (specFiles.length === 0) {
console.warn(`⚠️ No spec files found in ${inputPath}`)
return
}
let success = 0
let failure = 0
const totalStart = Date.now()
for (let i = 0; i < count; i++) {
console.log(`\n🔁 Run #${i + 1} of ${count}`)
for (const specFile of specFiles) {
try {
await runSpec(specFile)
success++
} catch (err) {
console.error(`❌ run #${i + 1}: ${path.basename(specFile)} failed:`, (err as Error).message)
failure++
}
}
if (failure > 0) process.exitCode = 1
}
console.log(`✅ Passed: ${success}`)
if (failure > 0) console.log(`❌ Failed: ${failure}`)
console.log(`📋 Total specs: ${specFiles.length} Total runs: ${specFiles.length * count}`)
console.log(`🏁 All runs completed in ${((Date.now() - totalStart) / 1000).toFixed(2)}s`)
}
async function main() {
const args = minimist(process.argv.slice(2), { default: { count: 1 } })
const inputPath = args._[0]
const count = Number(args.count)
showServerLogs = Boolean(args["server-logs"])
fix = Boolean(args["fix"])
coverage = Boolean(args["coverage"])
if (!inputPath) {
console.error(
"Usage: npx tsx scripts/testing-platform-orchestrator.ts <spec-file-or-folder> [--count=N] [--server-logs] [--fix] [--coverage]",
)
process.exit(1)
}
await runAll(inputPath, count)
}
if (require.main === module) {
main().catch((err) => {
console.error("❌ Fatal error:", err)
process.exit(1)
})
}
+3 -8
View File
@@ -1,20 +1,15 @@
import { Anthropic } from "@anthropic-ai/sdk"
import { ModelInfo } from "@shared/api"
import { ApiHandlerOptions, ModelInfo } from "@shared/api"
import { ApiHandler } from "../../core/api/index"
import { ApiStream } from "../../core/api/transform/stream"
interface DifyHandlerOptions {
difyApiKey?: string
difyBaseUrl?: string
}
export class DifyHandler implements ApiHandler {
private options: DifyHandlerOptions
private options: ApiHandlerOptions
private baseUrl: string
private apiKey: string
private conversationId: string | null = null
constructor(options: DifyHandlerOptions) {
constructor(options: ApiHandlerOptions) {
this.options = options
this.apiKey = options.difyApiKey || ""
this.baseUrl = options.difyBaseUrl || ""
+7 -15
View File
@@ -7,13 +7,12 @@ import {
} from "./core/storage/state-migrations"
import { WebviewProvider } from "./core/webview"
import { Logger } from "./services/logging/Logger"
import { WebviewProviderType } from "./shared/webview/types"
import "./utils/path" // necessary to have access to String.prototype.toPosix
import { HostProvider } from "@/hosts/host-provider"
import { FileContextTracker } from "./core/context/context-tracking/FileContextTracker"
import { ExtensionRegistryInfo } from "./registry"
import { audioRecordingService } from "./services/dictation/AudioRecordingService"
import { ErrorService } from "./services/error"
import { errorService } from "./services/error"
import { featureFlagsService } from "./services/feature-flags"
import { initializeDistinctId } from "./services/logging/distinctId"
import { PostHogClientProvider } from "./services/posthog/PostHogClientProvider"
@@ -33,10 +32,6 @@ export async function initialize(context: vscode.ExtensionContext): Promise<Webv
// Initialize PostHog client provider
PostHogClientProvider.getInstance()
// Setup the external services
await ErrorService.initialize()
await featureFlagsService.poll()
// Migrate custom instructions to global Cline rules (one-time cleanup)
await migrateCustomInstructionsToGlobalRules(context)
@@ -52,18 +47,18 @@ export async function initialize(context: vscode.ExtensionContext): Promise<Webv
// Clean up orphaned file context warnings (startup cleanup)
await FileContextTracker.cleanupOrphanedWarnings(context)
const webview = HostProvider.get().createWebviewProvider()
const sidebarWebview = HostProvider.get().createWebviewProvider(WebviewProviderType.SIDEBAR)
await showVersionUpdateAnnouncement(context)
telemetryService.captureExtensionActivated()
return webview
return sidebarWebview
}
async function showVersionUpdateAnnouncement(context: vscode.ExtensionContext) {
// Version checking for autoupdate notification
const currentVersion = ExtensionRegistryInfo.version
const currentVersion = context.extension.packageJSON.version
const previousVersion = context.globalState.get<string>("clineVersion")
// Perform post-update actions if necessary
try {
@@ -72,7 +67,7 @@ async function showVersionUpdateAnnouncement(context: vscode.ExtensionContext) {
// Use the same condition as announcements: focus when there's a new announcement to show
const lastShownAnnouncementId = context.globalState.get<string>("lastShownAnnouncementId")
const latestAnnouncementId = getLatestAnnouncementId()
const latestAnnouncementId = getLatestAnnouncementId(context)
if (lastShownAnnouncementId !== latestAnnouncementId) {
// Focus Cline when there's a new announcement to show (major/minor updates or fresh installs)
@@ -99,12 +94,9 @@ async function showVersionUpdateAnnouncement(context: vscode.ExtensionContext) {
* Performs cleanup when Cline is deactivated that is common to all platforms.
*/
export async function tearDown(): Promise<void> {
// Clean up audio recording service to ensure no orphaned processes
audioRecordingService.cleanup()
PostHogClientProvider.getInstance().dispose()
telemetryService.dispose()
ErrorService.get().dispose()
errorService.dispose()
featureFlagsService.dispose()
// Dispose all webview instances
await WebviewProvider.disposeAllInstances()
+1 -1
View File
@@ -4,7 +4,7 @@ export enum Environment {
local = "local",
}
export interface EnvironmentConfig {
interface EnvironmentConfig {
appBaseUrl: string
apiBaseUrl: string
mcpBaseUrl: string
+5 -17
View File
@@ -21,7 +21,6 @@ import { LmStudioHandler } from "./providers/lmstudio"
import { MistralHandler } from "./providers/mistral"
import { MoonshotHandler } from "./providers/moonshot"
import { NebiusHandler } from "./providers/nebius"
import { OcaHandler } from "./providers/oca"
import { OllamaHandler } from "./providers/ollama"
import { OpenAiHandler } from "./providers/openai"
import { OpenAiNativeHandler } from "./providers/openai-native"
@@ -58,7 +57,6 @@ export interface ApiProviderInfo {
providerId: string
model: ApiHandlerModel
customPrompt?: string // "compact"
autoCondenseThreshold?: number // 0-1 range
}
export interface SingleCompletionHandler {
@@ -333,7 +331,6 @@ function createHandlerForProvider(
thinkingBudgetTokens:
mode === "plan" ? options.planModeThinkingBudgetTokens : options.actModeThinkingBudgetTokens,
reasoningEffort: mode === "plan" ? options.planModeReasoningEffort : options.actModeReasoningEffort,
deploymentId: mode === "plan" ? options.planModeSapAiCoreDeploymentId : options.actModeSapAiCoreDeploymentId,
sapAiCoreUseOrchestrationMode: options.sapAiCoreUseOrchestrationMode,
})
case "claude-code":
@@ -354,6 +351,10 @@ function createHandlerForProvider(
mode === "plan" ? options.planModeHuaweiCloudMaasModelInfo : options.actModeHuaweiCloudMaasModelInfo,
})
case "dify": // Add Dify.ai handler
console.log("[DIFY DEBUG] Instantiating DifyHandler with options:", {
difyApiKeyPresent: !!options.difyApiKey,
difyBaseUrl: options.difyBaseUrl,
})
return new DifyHandler({
difyApiKey: options.difyApiKey,
difyBaseUrl: options.difyBaseUrl,
@@ -374,19 +375,6 @@ function createHandlerForProvider(
zaiApiKey: options.zaiApiKey,
apiModelId: mode === "plan" ? options.planModeApiModelId : options.actModeApiModelId,
})
case "oca":
return new OcaHandler({
ocaBaseUrl: options.ocaBaseUrl,
ocaModelId: mode === "plan" ? options.planModeOcaModelId : options.actModeOcaModelId,
ocaModelInfo: mode === "plan" ? options.planModeOcaModelInfo : options.actModeOcaModelInfo,
thinkingBudgetTokens:
mode === "plan" ? options.planModeThinkingBudgetTokens : options.actModeThinkingBudgetTokens,
ocaUsePromptCache:
mode === "plan"
? options.planModeOcaModelInfo?.supportsPromptCache
: options.actModeOcaModelInfo?.supportsPromptCache,
taskId: options.ulid,
})
default:
return new AnthropicHandler({
onRetryAttempt: options.onRetryAttempt,
@@ -412,7 +400,7 @@ export function buildApiHandler(configuration: ApiConfiguration, mode: Mode): Ap
const handler = createHandlerForProvider(apiProvider, options, mode)
const modelInfo = handler.getModel().info
if (modelInfo?.maxTokens && modelInfo.maxTokens > 0 && thinkingBudgetTokens > modelInfo.maxTokens) {
if (modelInfo.maxTokens && thinkingBudgetTokens > modelInfo.maxTokens) {
const clippedValue = modelInfo.maxTokens - 1
if (mode === "plan") {
options.planModeThinkingBudgetTokens = clippedValue
@@ -1,7 +1,7 @@
import "should"
import { ConverseStreamCommand } from "@aws-sdk/client-bedrock-runtime"
import { ApiHandlerOptions } from "@shared/api"
import { Readable } from "stream"
import type { AwsBedrockHandlerOptions } from "../bedrock"
import { AwsBedrockHandler } from "../bedrock"
describe("AwsBedrockHandler", () => {
@@ -202,8 +202,8 @@ describe("AwsBedrockHandler", () => {
})
})
const mockOptions: AwsBedrockHandlerOptions = {
apiModelId: "anthropic.claude-3-7-sonnet-20250219-v1:0",
const mockOptions: ApiHandlerOptions = {
actModeApiModelId: "anthropic.claude-3-7-sonnet-20250219-v1:0",
awsRegion: "us-east-1",
awsAccessKey: "test-key",
awsSecretKey: "test-secret",
@@ -214,9 +214,9 @@ describe("AwsBedrockHandler", () => {
awsBedrockUsePromptCache: false,
awsUseCrossRegionInference: false,
awsBedrockEndpoint: "",
awsBedrockCustomSelected: false,
awsBedrockCustomModelBaseId: undefined,
thinkingBudgetTokens: 1600,
actModeAwsBedrockCustomSelected: false,
actModeAwsBedrockCustomModelBaseId: undefined,
actModeThinkingBudgetTokens: 1600,
}
const mockModelInfo = {
+12 -37
View File
@@ -1,6 +1,6 @@
import { Anthropic } from "@anthropic-ai/sdk"
import { Stream as AnthropicStream } from "@anthropic-ai/sdk/streaming"
import { AnthropicModelId, anthropicDefaultModelId, anthropicModels, CLAUDE_SONNET_1M_SUFFIX, ModelInfo } from "@shared/api"
import { AnthropicModelId, anthropicDefaultModelId, anthropicModels, CLAUDE_SONNET_4_1M_SUFFIX, ModelInfo } from "@shared/api"
import { ApiHandler, CommonApiHandlerOptions } from "../index"
import { withRetry } from "../retry"
import { ApiStream } from "../transform/stream"
@@ -44,18 +44,16 @@ export class AnthropicHandler implements ApiHandler {
const model = this.getModel()
let stream: AnthropicStream<Anthropic.RawMessageStreamEvent>
const modelId = model.id.endsWith(CLAUDE_SONNET_1M_SUFFIX) ? model.id.slice(0, -CLAUDE_SONNET_1M_SUFFIX.length) : model.id
const enable1mContextWindow = model.id.endsWith(CLAUDE_SONNET_1M_SUFFIX)
const modelId = model.id.endsWith(CLAUDE_SONNET_4_1M_SUFFIX)
? model.id.slice(0, -CLAUDE_SONNET_4_1M_SUFFIX.length)
: model.id
const enable1mContextWindow = model.id.endsWith(CLAUDE_SONNET_4_1M_SUFFIX)
const budget_tokens = this.options.thinkingBudgetTokens || 0
const reasoningOn = !!(
(modelId.includes("3-7") || modelId.includes("4-") || modelId.includes("4-5")) &&
budget_tokens !== 0
)
const reasoningOn = !!((modelId.includes("3-7") || modelId.includes("4-")) && budget_tokens !== 0)
switch (modelId) {
// 'latest' alias does not support cache_control
case "claude-sonnet-4-5-20250929":
case "claude-sonnet-4-20250514":
case "claude-3-7-sonnet-20250219":
case "claude-3-5-sonnet-20241022":
@@ -152,8 +150,6 @@ export class AnthropicHandler implements ApiHandler {
}
}
let thinkingDeltaAccumulator = ""
for await (const chunk of stream) {
switch (chunk?.type) {
case "message_start":
@@ -186,26 +182,14 @@ export class AnthropicHandler implements ApiHandler {
type: "reasoning",
reasoning: chunk.content_block.thinking || "",
}
const thinking = chunk.content_block.thinking
const signature = chunk.content_block.signature
if (thinking && signature) {
yield {
type: "ant_thinking",
thinking,
signature,
}
}
break
case "redacted_thinking":
// Content is encrypted, and we don't to pass placeholder text back to the API
// Handle redacted thinking blocks - we still mark it as reasoning
// but note that the content is encrypted
yield {
type: "reasoning",
reasoning: "[Redacted thinking block]",
}
yield {
type: "ant_redacted_thinking",
data: chunk.content_block.data,
}
break
case "text":
// we may receive multiple text blocks, in which case just insert a line break between them
@@ -225,23 +209,10 @@ export class AnthropicHandler implements ApiHandler {
case "content_block_delta":
switch (chunk.delta.type) {
case "thinking_delta":
// 'reasoning' type just displays in the UI, but ant_thinking will be used to send the thinking traces back to the API
yield {
type: "reasoning",
reasoning: chunk.delta.thinking,
}
thinkingDeltaAccumulator += chunk.delta.thinking
break
case "signature_delta":
// It's used when sending the thinking block back to the API
// API expects this in completed form, not as array of deltas
if (thinkingDeltaAccumulator && chunk.delta.signature) {
yield {
type: "ant_thinking",
thinking: thinkingDeltaAccumulator,
signature: chunk.delta.signature,
}
}
break
case "text_delta":
yield {
@@ -249,6 +220,10 @@ export class AnthropicHandler implements ApiHandler {
text: chunk.delta.text,
}
break
case "signature_delta":
// We don't need to do anything with the signature in the client
// It's used when sending the thinking block back to the API
break
}
break
case "content_block_stop":
+11 -6
View File
@@ -146,15 +146,20 @@ export class BasetenHandler implements ApiHandler {
}
}
/**
* Checks if the current model supports vision/images
*/
supportsImages(): boolean {
const model = this.getModel()
return model.info.supportsImages === true
}
/**
* Checks if the current model supports tools
*/
supportsTools(): boolean {
const model = this.getModel()
const modelInfo = model.info as any
// Use dynamic API data when available, fallback to true since all current Baseten models support tools
// (as of 2025-09-16 - could change if Baseten add non-tool models in future, currently no plans to do so)
return modelInfo.supportedFeatures ? modelInfo.supportedFeatures.includes("tools") : true
const _model = this.getModel()
// Baseten models support tools via OpenAI-compatible API
return true
}
}
+8 -11
View File
@@ -9,14 +9,14 @@ import {
InvokeModelWithResponseStreamCommand,
} from "@aws-sdk/client-bedrock-runtime"
import { fromNodeProviderChain } from "@aws-sdk/credential-providers"
import { BedrockModelId, bedrockDefaultModelId, bedrockModels, CLAUDE_SONNET_1M_SUFFIX, ModelInfo } from "@shared/api"
import { BedrockModelId, bedrockDefaultModelId, bedrockModels, CLAUDE_SONNET_4_1M_SUFFIX, ModelInfo } from "@shared/api"
import { calculateApiCostOpenAI } from "@utils/cost"
import { ApiHandler, CommonApiHandlerOptions } from "../"
import { withRetry } from "../retry"
import { convertToR1Format } from "../transform/r1-format"
import { ApiStream } from "../transform/stream"
export interface AwsBedrockHandlerOptions extends CommonApiHandlerOptions {
interface AwsBedrockHandlerOptions extends CommonApiHandlerOptions {
apiModelId?: string
awsAccessKey?: string
awsSecretKey?: string
@@ -30,7 +30,7 @@ export interface AwsBedrockHandlerOptions extends CommonApiHandlerOptions {
awsProfile?: string
awsBedrockEndpoint?: string
awsBedrockCustomSelected?: boolean
awsBedrockCustomModelBaseId?: string
awsBedrockCustomModelBaseId?: BedrockModelId
thinkingBudgetTokens?: number
}
@@ -119,11 +119,11 @@ export class AwsBedrockHandler implements ApiHandler {
// cross region inference requires prefixing the model id with the region
const rawModelId = await this.getModelId()
const modelId = rawModelId.endsWith(CLAUDE_SONNET_1M_SUFFIX)
? rawModelId.slice(0, -CLAUDE_SONNET_1M_SUFFIX.length)
const modelId = rawModelId.endsWith(CLAUDE_SONNET_4_1M_SUFFIX)
? rawModelId.slice(0, -CLAUDE_SONNET_4_1M_SUFFIX.length)
: rawModelId
const enable1mContextWindow = rawModelId.endsWith(CLAUDE_SONNET_1M_SUFFIX)
const enable1mContextWindow = rawModelId.endsWith(CLAUDE_SONNET_4_1M_SUFFIX)
const model = this.getModel()
@@ -170,7 +170,7 @@ export class AwsBedrockHandler implements ApiHandler {
if (baseModel && baseModel in bedrockModels) {
return {
id: modelId,
info: bedrockModels[baseModel as BedrockModelId],
info: bedrockModels[baseModel],
}
}
// For custom models without valid base model in bedrock model list, use default model's capabilities
@@ -741,10 +741,7 @@ export class AwsBedrockHandler implements ApiHandler {
*/
private shouldEnableReasoning(baseModelId: string, budgetTokens: number): boolean {
return (
(baseModelId.includes("3-7") ||
baseModelId.includes("sonnet-4") ||
baseModelId.includes("opus-4") ||
baseModelId.includes("sonnet-4-5")) &&
(baseModelId.includes("3-7") || baseModelId.includes("sonnet-4") || baseModelId.includes("opus-4")) &&
budgetTokens !== 0
)
}
+12 -49
View File
@@ -6,8 +6,8 @@ import OpenAI from "openai"
import { clineEnvConfig } from "@/config"
import { ClineAccountService } from "@/services/account/ClineAccountService"
import { AuthService } from "@/services/auth/AuthService"
import { buildClineExtraHeaders } from "@/services/EnvUtils"
import { CLINE_ACCOUNT_AUTH_ERROR_MESSAGE } from "@/shared/ClineAccount"
import { version as extensionVersion } from "../../../../package.json"
import { ApiHandler, CommonApiHandlerOptions } from "../"
import { withRetry } from "../retry"
import { createOpenRouterStream } from "../transform/openrouter-stream"
@@ -32,7 +32,6 @@ export class ClineHandler implements ApiHandler {
private client: OpenAI | undefined
private readonly _baseUrl = clineEnvConfig.apiBaseUrl
lastGenerationId?: string
private lastRequestId?: string
constructor(options: ClineHandlerOptions) {
this.options = options
@@ -46,41 +45,14 @@ export class ClineHandler implements ApiHandler {
}
if (!this.client) {
try {
const defaultHeaders: Record<string, string> = {
"HTTP-Referer": "https://cline.bot",
"X-Title": "Cline",
"X-Task-ID": this.options.ulid || "",
}
Object.assign(defaultHeaders, await buildClineExtraHeaders())
this.client = new OpenAI({
baseURL: `${this._baseUrl}/api/v1`,
apiKey: clineAccountAuthToken,
defaultHeaders,
// Capture real HTTP request ID from initial streaming response headers
fetch: async (...args: Parameters<typeof fetch>): Promise<Awaited<ReturnType<typeof fetch>>> => {
const [input, init] = args
const resp = await fetch(input, init)
try {
let urlStr = ""
if (typeof input === "string") {
urlStr = input
} else if (input instanceof URL) {
urlStr = input.toString()
} else if (typeof (input as { url?: unknown }).url === "string") {
urlStr = (input as { url: string }).url
}
// Only record for chat completions (the primary streaming request)
if (urlStr.includes("/chat/completions")) {
const rid = resp.headers.get("x-request-id") || resp.headers.get("request-id")
if (rid) {
this.lastRequestId = rid
}
}
} catch {
// ignore header capture errors
}
return resp
defaultHeaders: {
"HTTP-Referer": "https://cline.bot",
"X-Title": "Cline",
"X-Task-ID": this.options.ulid || "",
"X-Cline-Version": extensionVersion,
},
})
} catch (error: any) {
@@ -98,7 +70,6 @@ export class ClineHandler implements ApiHandler {
const client = await this.ensureClient()
this.lastGenerationId = undefined
this.lastRequestId = undefined
let didOutputUsage: boolean = false
@@ -121,7 +92,6 @@ export class ClineHandler implements ApiHandler {
const metadataStr = error.metadata ? `\nMetadata: ${JSON.stringify(error.metadata, null, 2)}` : ""
throw new Error(`Cline API Error ${error.code}: ${error.message}${metadataStr}`)
}
if (!this.lastGenerationId && chunk.id) {
this.lastGenerationId = chunk.id
}
@@ -164,7 +134,7 @@ export class ClineHandler implements ApiHandler {
// @ts-ignore-next-line
let totalCost = (chunk.usage.cost || 0) + (chunk.usage.cost_details?.upstream_inference_cost || 0)
if (this.getModel().id === "cline/code-supernova-1-million") {
if (this.getModel().id === "cline/sonic") {
totalCost = 0
}
@@ -202,18 +172,16 @@ export class ClineHandler implements ApiHandler {
async getApiStreamUsage(): Promise<ApiStreamUsageChunk | undefined> {
if (this.lastGenerationId) {
try {
// TODO: replace this with firebase auth
// TODO: use global API Host
const clineAccountAuthToken = await this._authService.getAuthToken()
if (!clineAccountAuthToken) {
throw new Error(CLINE_ACCOUNT_AUTH_ERROR_MESSAGE)
}
const headers: Record<string, string> = {
// Align with backend auth expectations
Authorization: `Bearer ${clineAccountAuthToken}`,
}
Object.assign(headers, await buildClineExtraHeaders())
const response = await axios.get(`${this.clineAccountService.baseUrl}/generation?id=${this.lastGenerationId}`, {
headers,
headers: {
Authorization: `Bearer ${clineAccountAuthToken}`,
},
timeout: 15_000, // this request hangs sometimes
})
@@ -235,11 +203,6 @@ export class ClineHandler implements ApiHandler {
return undefined
}
// Expose the last HTTP request ID captured from response headers (X-Request-ID)
getLastRequestId(): string | undefined {
return this.lastRequestId
}
getModel(): { id: string; info: ModelInfo } {
const modelId = this.options.openRouterModelId
const modelInfo = this.options.openRouterModelInfo
+3 -8
View File
@@ -1,13 +1,8 @@
import { Anthropic } from "@anthropic-ai/sdk"
import { ModelInfo } from "../../../shared/api"
import { ApiHandlerOptions, ModelInfo } from "../../../shared/api"
import { ApiHandler } from "../index"
import { ApiStream } from "../transform/stream"
interface DifyHandlerOptions {
difyApiKey?: string
difyBaseUrl?: string
}
// Dify API Response Types
export interface DifyFileResponse {
id: string
@@ -71,14 +66,14 @@ interface DifyConversationResponse {
}
export class DifyHandler implements ApiHandler {
private options: DifyHandlerOptions
private options: ApiHandlerOptions
private baseUrl: string
private apiKey: string
private conversationId: string | null = null
private currentTaskId: string | null = null
private abortController: AbortController | null = null
constructor(options: DifyHandlerOptions) {
constructor(options: ApiHandlerOptions) {
this.options = options
this.apiKey = options.difyApiKey || ""
this.baseUrl = options.difyBaseUrl || ""
+2 -3
View File
@@ -1,7 +1,6 @@
import { Anthropic } from "@anthropic-ai/sdk"
import { LiteLLMModelInfo, liteLlmDefaultModelId, liteLlmModelInfoSaneDefaults } from "@shared/api"
import OpenAI from "openai"
import { isAnthropicModelId } from "@/utils/model-utils"
import { ApiHandler, CommonApiHandlerOptions } from ".."
import { withRetry } from "../retry"
import { convertToOpenAiMessages } from "../transform/openai-format"
@@ -198,8 +197,8 @@ export class LiteLlmHandler implements ApiHandler {
let temperature: number | undefined = this.options.liteLlmModelInfo?.temperature ?? 0
if ((isOminiModel || isAnthropicModelId(modelId)) && reasoningOn) {
temperature = undefined // OAI omni and Anthropic extended thinking mode doesn't support temperature
if (isOminiModel && reasoningOn) {
temperature = undefined // Thinking mode doesn't support temperature
}
const modelInfo = await this.modelInfo(modelId)
-1
View File
@@ -49,7 +49,6 @@ export class MoonshotHandler implements ApiHandler {
model: model.id,
messages: openAiMessages,
temperature: 0,
max_tokens: model.info.maxTokens,
stream: true,
stream_options: { include_usage: true },
})
-261
View File
@@ -1,261 +0,0 @@
import { Anthropic } from "@anthropic-ai/sdk"
import { LiteLLMModelInfo, liteLlmDefaultModelId, liteLlmModelInfoSaneDefaults } from "@shared/api"
import OpenAI, { APIError, OpenAIError } from "openai"
import type { FinalRequestOptions, Headers as OpenAIHeaders } from "openai/core"
import { OcaAuthService } from "@/services/auth/oca/OcaAuthService"
import { DEFAULT_OCA_BASE_URL, OCI_HEADER_OPC_REQUEST_ID } from "@/services/auth/oca/utils/constants"
import { createOcaHeaders } from "@/services/auth/oca/utils/utils"
import { Logger } from "@/services/logging/Logger"
import { ApiHandler, type CommonApiHandlerOptions } from ".."
import { withRetry } from "../retry"
import { convertToOpenAiMessages } from "../transform/openai-format"
import { ApiStream } from "../transform/stream"
export interface OcaHandlerOptions extends CommonApiHandlerOptions {
ocaBaseUrl?: string
ocaModelId?: string
ocaModelInfo?: LiteLLMModelInfo
thinkingBudgetTokens?: number
ocaUsePromptCache?: boolean
taskId?: string
}
export class OcaHandler implements ApiHandler {
protected options: OcaHandlerOptions
protected client: OpenAI | undefined
constructor(options: OcaHandlerOptions) {
this.options = options
}
protected initializeClient(options: OcaHandlerOptions) {
return new (class OCIOpenAI extends OpenAI {
protected override async prepareOptions(opts: FinalRequestOptions<unknown>): Promise<void> {
const token = await OcaAuthService.getInstance().getAuthToken()
if (!token) {
throw new OpenAIError("Unable to handle auth, Oracle Code Assist (OCA) access token is not available")
}
opts.headers ??= {}
// OCA Headers
const ociHeaders = await createOcaHeaders(token, options.taskId!)
opts.headers = { ...opts.headers, ...ociHeaders }
Logger.log(`Making request with customer opc-request-id: ${opts.headers?.["opc-request-id"]}`)
return super.prepareOptions(opts)
}
protected override makeStatusError(
status: number | undefined,
error: Object | undefined,
message: string | undefined,
headers: OpenAIHeaders | undefined,
): APIError {
interface OciError {
code?: string
message?: string
}
let ociErrorMessage = message
if (typeof error === "object" && error !== null) {
try {
ociErrorMessage = JSON.stringify(error)
const ociErr = error as OciError
if (ociErr.code !== undefined && ociErr.message !== undefined) {
ociErrorMessage = `${ociErr.code}: ${ociErr.message}`
}
} catch {}
}
const opcRequestId = headers?.[OCI_HEADER_OPC_REQUEST_ID]
if (opcRequestId) {
ociErrorMessage += `\n(${OCI_HEADER_OPC_REQUEST_ID}: ${opcRequestId})`
}
return super.makeStatusError(status, error, ociErrorMessage, headers)
}
})({
baseURL: options.ocaBaseUrl || DEFAULT_OCA_BASE_URL,
apiKey: "noop",
})
}
protected ensureClient(): OpenAI {
if (!this.client) {
if (!this.options.ocaModelId) {
throw new Error("Oracle Code Assist (OCA) model is not selected")
}
try {
this.client = this.initializeClient(this.options)
} catch (error) {
throw new Error(`Error creating Oracle Code Assist (OCA) client: ${error.message}`)
}
}
return this.client
}
async calculateCost(prompt_tokens: number, completion_tokens: number): Promise<number | undefined> {
// Reference: https://github.com/BerriAI/litellm/blob/122ee634f434014267af104814022af1d9a0882f/litellm/proxy/spend_tracking/spend_management_endpoints.py#L1473
const client = this.ensureClient()
const modelId = this.options.ocaModelId || liteLlmDefaultModelId
const token = await OcaAuthService.getInstance().getAuthToken()
if (!token) {
throw new OpenAIError("Unable to handle auth, Oracle Code Assist (OCA) access token is not available")
}
const ociHeaders = await createOcaHeaders(token, this.options.taskId!)
Logger.log(`Making calculate cost request with customer opc-request-id: ${ociHeaders["opc-request-id"]}`)
try {
const response = await fetch(`${client.baseURL}/spend/calculate`, {
method: "POST",
headers: ociHeaders,
body: JSON.stringify({
completion_response: {
model: modelId,
usage: {
prompt_tokens,
completion_tokens,
},
},
}),
})
if (response.ok) {
const data: { cost: number } = await response.json()
return data.cost
} else {
console.error("Error calculating spend:", response.statusText)
return undefined
}
} catch (error) {
console.error("Error calculating spend:", error)
return undefined
}
}
@withRetry()
async *createMessage(systemPrompt: string, messages: Anthropic.Messages.MessageParam[]): ApiStream {
const client = this.ensureClient()
const formattedMessages = convertToOpenAiMessages(messages)
const systemMessage: OpenAI.Chat.ChatCompletionSystemMessageParam = {
role: "system",
content: systemPrompt,
}
const modelId = this.options.ocaModelId || liteLlmDefaultModelId
const isOminiModel = modelId.includes("o1-mini") || modelId.includes("o3-mini") || modelId.includes("o4-mini")
// Configuration for extended thinking
const budgetTokens = this.options.thinkingBudgetTokens || 0
const reasoningOn = budgetTokens !== 0 ? true : false
const thinkingConfig = reasoningOn ? { type: "enabled", budget_tokens: budgetTokens } : undefined
let temperature: number | undefined = this.options.ocaModelInfo?.temperature ?? 0
const maxTokens: number | undefined = this.options.ocaModelInfo?.maxTokens
if (isOminiModel && reasoningOn) {
temperature = undefined // Thinking mode doesn't support temperature
}
// Define cache control object if prompt caching is enabled
const cacheControl = this.options.ocaUsePromptCache ? { cache_control: { type: "ephemeral" } } : undefined
// Add cache_control to system message if enabled
const enhancedSystemMessage = {
...systemMessage,
...(cacheControl && cacheControl),
}
// Find the last two user messages to apply caching
const userMsgIndices = formattedMessages.reduce((acc, msg, index) => {
if (msg.role === "user") {
acc.push(index)
}
return acc
}, [] as number[])
const lastUserMsgIndex = userMsgIndices[userMsgIndices.length - 1] ?? -1
const secondLastUserMsgIndex = userMsgIndices[userMsgIndices.length - 2] ?? -1
// Apply cache_control to the last two user messages if enabled
const enhancedMessages = formattedMessages.map((message, index) => {
if ((index === lastUserMsgIndex || index === secondLastUserMsgIndex) && cacheControl) {
return {
...message,
...cacheControl,
}
}
return message
})
const stream = await client.chat.completions.create({
model: this.options.ocaModelId || liteLlmDefaultModelId,
messages: [enhancedSystemMessage, ...enhancedMessages],
temperature,
stream: true,
max_completion_tokens: maxTokens,
max_tokens: maxTokens,
stream_options: { include_usage: true },
...(thinkingConfig && { thinking: thinkingConfig }), // Add thinking configuration when applicable
...(this.options.taskId && {
litellm_session_id: `cline-${this.options.taskId}`,
}), // Add session ID for LiteLLM tracking
})
const inputCost = (await this.calculateCost(1e6, 0)) || 0
const outputCost = (await this.calculateCost(0, 1e6)) || 0
for await (const chunk of stream) {
const delta = chunk.choices[0]?.delta
// Handle normal text content
if (delta?.content) {
yield {
type: "text",
text: delta.content,
}
}
// Handle reasoning events (thinking)
// Thinking is not in the standard types but may be in the response
interface ThinkingDelta {
thinking?: string
}
if ((delta as ThinkingDelta)?.thinking) {
yield {
type: "reasoning",
reasoning: (delta as ThinkingDelta).thinking || "",
}
}
// Handle token usage information
if (chunk.usage) {
const totalCost =
(inputCost * chunk.usage.prompt_tokens) / 1e6 + (outputCost * chunk.usage.completion_tokens) / 1e6
// Extract cache-related information if available
// Need to use type assertion since these properties are not in the standard OpenAI types
const usage = chunk.usage as {
prompt_tokens: number
completion_tokens: number
cache_creation_input_tokens?: number
prompt_cache_miss_tokens?: number
cache_read_input_tokens?: number
prompt_cache_hit_tokens?: number
}
const cacheWriteTokens = usage.cache_creation_input_tokens || usage.prompt_cache_miss_tokens || 0
const cacheReadTokens = usage.cache_read_input_tokens || usage.prompt_cache_hit_tokens || 0
yield {
type: "usage",
inputTokens: usage.prompt_tokens || 0,
outputTokens: usage.completion_tokens || 0,
cacheWriteTokens: cacheWriteTokens > 0 ? cacheWriteTokens : undefined,
cacheReadTokens: cacheReadTokens > 0 ? cacheReadTokens : undefined,
totalCost,
}
}
}
}
getModel() {
return {
id: this.options.ocaModelId || liteLlmDefaultModelId,
info: this.options.ocaModelInfo || liteLlmModelInfoSaneDefaults,
}
}
}
-15
View File
@@ -122,21 +122,6 @@ export class OpenRouterHandler implements ApiHandler {
}
}
// OpenRouter passes reasoning details that we can pass back unmodified in api requests to preserve reasoning traces for model
// See: https://openrouter.ai/docs/use-cases/reasoning-tokens#preserving-reasoning-blocks
if (
"reasoning_details" in delta &&
delta.reasoning_details &&
// @ts-ignore-next-line
delta.reasoning_details.length && // exists and non-0
!shouldSkipReasoningForModel(this.options.openRouterModelId)
) {
yield {
type: "reasoning_details",
reasoning_details: delta.reasoning_details,
}
}
if (!didOutputUsage && chunk.usage) {
yield {
type: "usage",
+2 -2
View File
@@ -2,7 +2,6 @@ import { Anthropic } from "@anthropic-ai/sdk"
import { ModelInfo, requestyDefaultModelId, requestyDefaultModelInfo } from "@shared/api"
import { calculateApiCostOpenAI } from "@utils/cost"
import OpenAI from "openai"
import { toRequestyServiceStringUrl } from "@/shared/providers/requesty"
import { ApiHandler, CommonApiHandlerOptions } from "../index"
import { withRetry } from "../retry"
import { convertToOpenAiMessages } from "../transform/openai-format"
@@ -42,7 +41,7 @@ export class RequestyHandler implements ApiHandler {
}
try {
this.client = new OpenAI({
baseURL: toRequestyServiceStringUrl(this.options.requestyBaseUrl),
baseURL: this.options.requestyBaseUrl || "https://router.requesty.ai/v1",
apiKey: this.options.requestyApiKey,
defaultHeaders: {
"HTTP-Referer": "https://cline.bot",
@@ -83,6 +82,7 @@ export class RequestyHandler implements ApiHandler {
? thinking
: {}
// @ts-ignore-next-line
const stream = await client.chat.completions.create({
model: model.id,
max_tokens: model.info.maxTokens || undefined,
+13 -16
View File
@@ -9,7 +9,6 @@ import { ModelInfo, SapAiCoreModelId, sapAiCoreDefaultModelId, sapAiCoreModels }
import axios from "axios"
import OpenAI from "openai"
import { ApiHandler, CommonApiHandlerOptions } from "../"
import { withRetry } from "../retry"
import { convertToOpenAiMessages } from "../transform/openai-format"
import { ApiStream } from "../transform/stream"
@@ -22,7 +21,6 @@ interface SapAiCoreHandlerOptions extends CommonApiHandlerOptions {
apiModelId?: string
sapAiCoreUseOrchestrationMode?: boolean
thinkingBudgetTokens?: number
deploymentId?: string
reasoningEffort?: string
}
@@ -30,7 +28,6 @@ interface Deployment {
id: string
name: string
}
interface Token {
access_token: string
expires_in: number
@@ -397,8 +394,11 @@ export class SapAiCoreHandler implements ApiHandler {
return this.token.access_token
}
// TODO: these fallback fetching deployment id methods can be removed in future version if decided that users migration to fetching deployment id in design-time (open SAP AI Core provider UI) considered as completed.
private async getAiCoreDeployments(): Promise<Deployment[]> {
if (this.options.sapAiCoreClientSecret === "") {
return [{ id: "notconfigured", name: "ai-core-not-configured" }]
}
const token = await this.getToken()
const headers = {
Authorization: `Bearer ${token}`,
@@ -455,9 +455,8 @@ export class SapAiCoreHandler implements ApiHandler {
return this.deployments?.some((d) => d.name.split(":")[0].toLowerCase() === modelId.split(":")[0].toLowerCase()) ?? false
}
@withRetry()
async *createMessage(systemPrompt: string, messages: Anthropic.Messages.MessageParam[]): ApiStream {
if (this.options.sapAiCoreUseOrchestrationMode) {
if (this.options.sapAiCoreUseOrchestrationMode ?? true) {
yield* this.createMessageWithOrchestration(systemPrompt, messages)
} else {
yield* this.createMessageWithDeployments(systemPrompt, messages)
@@ -497,6 +496,7 @@ export class SapAiCoreHandler implements ApiHandler {
// Define the LLM to be used by the Orchestration pipeline
const llm: LlmModuleConfig = {
model_name: model.id,
model_params: { max_tokens: model.info.maxTokens },
}
const templating: TemplatingModuleConfig = {
@@ -546,13 +546,7 @@ export class SapAiCoreHandler implements ApiHandler {
}
const model = this.getModel()
let deploymentId = this.options.deploymentId
if (!deploymentId) {
// Fallback to runtime deployment id fetching for users who haven't opened the SAP provider UI
console.log(`No pre-configured deployment ID found for model ${model.id}, falling back to runtime fetching`)
deploymentId = await this.getDeploymentForModel(model.id)
}
const deploymentId = await this.getDeploymentForModel(model.id)
const anthropicModels = [
"anthropic--claude-4-sonnet",
@@ -825,13 +819,16 @@ export class SapAiCoreHandler implements ApiHandler {
// Handle metadata (token usage)
if (data.metadata?.usage) {
// inputTokens does not include cached write/read tokens
let inputTokens = data.metadata.usage.inputTokens || 0
const outputTokens = data.metadata.usage.outputTokens || 0
// calibrate input token
const totalTokens = data.metadata.usage.totalTokens || 0
const cacheReadInputTokens = data.metadata.usage.cacheReadInputTokens || 0
const cacheWriteInputTokens = data.metadata.usage.cacheWriteInputTokens || 0
inputTokens = inputTokens + cacheReadInputTokens + cacheWriteInputTokens
const cacheWriteOutputTokens = data.metadata.usage.cacheWriteOutputTokens || 0
if (inputTokens + outputTokens + cacheReadInputTokens + cacheWriteOutputTokens !== totalTokens) {
inputTokens = totalTokens - outputTokens - cacheReadInputTokens - cacheWriteOutputTokens
}
yield {
type: "usage",
+1
View File
@@ -85,6 +85,7 @@ export class ZAiHandler implements ApiHandler {
messages: openAiMessages,
stream: true,
stream_options: { include_usage: true },
temperature: 0,
})
for await (const chunk of stream) {
+19 -40
View File
@@ -1,13 +1,8 @@
import { describe, it } from "mocha"
import "should"
import sinon from "sinon"
import { withRetry } from "./retry"
describe("Retry Decorator", () => {
afterEach(() => {
sinon.restore()
})
describe("withRetry", () => {
it("should not retry on success", async () => {
let callCount = 0
@@ -78,11 +73,9 @@ describe("Retry Decorator", () => {
it("should respect retry-after header with delta seconds", async () => {
let callCount = 0
const setTimeoutSpy = sinon.spy(global, "setTimeout")
const baseDelay = 1000
const startTime = Date.now()
class TestClass {
@withRetry({ maxRetries: 2, baseDelay }) // Use large baseDelay to ensure header takes precedence
@withRetry({ maxRetries: 2, baseDelay: 1000 }) // Use large baseDelay to ensure header takes precedence
async *failMethod() {
callCount++
if (callCount === 1) {
@@ -101,23 +94,19 @@ describe("Retry Decorator", () => {
result.push(value)
}
const duration = Date.now() - startTime
duration.should.be.approximately(10, 10) // Allow 10ms variance
callCount.should.equal(2)
setTimeoutSpy.calledOnce.should.be.true
const [_, delay] = setTimeoutSpy.getCall(0).args
delay?.should.equal(0)
result.should.deepEqual(["success after retry"])
})
it("should respect retry-after header with Unix timestamp", async () => {
const setTimeoutSpy = sinon.spy(global, "setTimeout")
let callCount = 0
const fixedDate = new Date("2010-01-01T00:00:00.000Z")
const retryTimestamp = Math.floor(fixedDate.getTime() / 1000) + 0.01 // 10ms in the future
const baseDelay = 1000
const startTime = Date.now()
const retryTimestamp = Math.floor(Date.now() / 1000) + 0.01 // 10ms in the future
class TestClass {
@withRetry({ maxRetries: 2, baseDelay }) // Use large baseDelay to ensure header takes precedence
@withRetry({ maxRetries: 2, baseDelay: 1000 }) // Use large baseDelay to ensure header takes precedence
async *failMethod() {
callCount++
if (callCount === 1) {
@@ -136,22 +125,17 @@ describe("Retry Decorator", () => {
result.push(value)
}
const duration = Date.now() - startTime
duration.should.be.approximately(10, 10) // Allow 10ms variance
callCount.should.equal(2)
setTimeoutSpy.calledOnce.should.be.true
const [_, delay] = setTimeoutSpy.getCall(0).args
delay?.should.equal(fixedDate.getTime())
result.should.deepEqual(["success after retry"])
})
it("should use exponential backoff when no retry-after header", async () => {
const setTimeoutSpy = sinon.spy(global, "setTimeout")
let callCount = 0
const baseDelay = 10
const startTime = Date.now()
class TestClass {
@withRetry({ maxRetries: 2, baseDelay, maxDelay: 100 })
@withRetry({ maxRetries: 2, baseDelay: 10, maxDelay: 100 })
async *failMethod() {
callCount++
if (callCount === 1) {
@@ -169,22 +153,18 @@ describe("Retry Decorator", () => {
result.push(value)
}
const duration = Date.now() - startTime
// First retry should be after baseDelay (10ms)
duration.should.be.approximately(10, 10)
callCount.should.equal(2)
setTimeoutSpy.calledOnce.should.be.true
const [_, delay] = setTimeoutSpy.getCall(0).args
delay?.should.equal(baseDelay)
result.should.deepEqual(["success after retry"])
})
it("should respect maxDelay", async () => {
const setTimeoutSpy = sinon.spy(global, "setTimeout")
let callCount = 0
const baseDelay = 50
const maxDelay = 10
const startTime = Date.now()
class TestClass {
@withRetry({ maxRetries: 3, baseDelay, maxDelay })
@withRetry({ maxRetries: 3, baseDelay: 50, maxDelay: 10 })
async *failMethod() {
callCount++
if (callCount < 3) {
@@ -202,11 +182,10 @@ describe("Retry Decorator", () => {
result.push(value)
}
const duration = Date.now() - startTime
// Both retries should be capped at maxDelay (10ms each)
duration.should.be.approximately(20, 20)
callCount.should.equal(3)
setTimeoutSpy.calledOnce.should.be.true
const [_, delay] = setTimeoutSpy.getCall(0).args
delay?.should.equal(maxDelay)
result.should.deepEqual(["success after retries"])
})
-10
View File
@@ -115,15 +115,7 @@ export function convertToOpenAiMessages(
// Process non-tool messages
let content: string | undefined
const reasoningDetails: any[] = []
if (nonToolMessages.length > 0) {
nonToolMessages.forEach((part) => {
// @ts-ignore-next-line
if (part.type === "text" && part.reasoning_details) {
// @ts-ignore-next-line
reasoningDetails.push(part.reasoning_details)
}
})
content = nonToolMessages
.map((part) => {
if (part.type === "image") {
@@ -150,8 +142,6 @@ export function convertToOpenAiMessages(
content,
// Cannot be an empty array. API expects an array with minimum length 1, and will respond with an error if it's empty
tool_calls: tool_calls.length > 0 ? tool_calls : undefined,
// @ts-ignore-next-line
reasoning_details: reasoningDetails.length > 0 ? reasoningDetails : undefined,
})
}
}

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