mirror of
https://github.com/cline/cline.git
synced 2026-09-09 06:45:53 +08:00
Compare commits
157
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7734f04e2a | ||
|
|
3ef7d0f5d2 | ||
|
|
9463b4ac72 | ||
|
|
b858277da3 | ||
|
|
f152301ca9 | ||
|
|
0d13ae1fa4 | ||
|
|
0cefe107b8 | ||
|
|
43a6e85d7a | ||
|
|
7a27f09224 | ||
|
|
0936634fe5 | ||
|
|
7ec918261c | ||
|
|
9ac17c2ec8 | ||
|
|
ee68fac5b8 | ||
|
|
3bcb1bacb7 | ||
|
|
6392043f51 | ||
|
|
92177ac2ea | ||
|
|
318f5a7829 | ||
|
|
f98aa0fb50 | ||
|
|
0bc9326b62 | ||
|
|
92d7cdf593 | ||
|
|
6cc867ccb5 | ||
|
|
e4325812d0 | ||
|
|
8e0a70e38d | ||
|
|
272e162952 | ||
|
|
78b47e3ebd | ||
|
|
8a97a88fb8 | ||
|
|
1caaf7d6ca | ||
|
|
f1cd1518fb | ||
|
|
97dadea068 | ||
|
|
28b5c1de24 | ||
|
|
6cd99c7738 | ||
|
|
9b750783c9 | ||
|
|
592e1a6d49 | ||
|
|
c30b2158e3 | ||
|
|
26a47722aa | ||
|
|
ce426c0344 | ||
|
|
461f02bd25 | ||
|
|
9fe16941a3 | ||
|
|
b93adc20af | ||
|
|
7ccf7a8bb5 | ||
|
|
8f9de630b3 | ||
|
|
87c4965110 | ||
|
|
4f35a5975a | ||
|
|
17fd4ceb7f | ||
|
|
a231ee4d5c | ||
|
|
531a272a63 | ||
|
|
6b9ac49d0a | ||
|
|
6d42a3fe0c | ||
|
|
5c9c37a075 | ||
|
|
d08c394f68 | ||
|
|
c0ca9889ff | ||
|
|
fc19697fad | ||
|
|
f64e8ddbf7 | ||
|
|
70d1dce34f | ||
|
|
950142fdfb | ||
|
|
41765fc29a | ||
|
|
e5f8c048ce | ||
|
|
83de7bb2f1 | ||
|
|
6c842c145f | ||
|
|
09adaca575 | ||
|
|
0b1a237290 | ||
|
|
cb1bda9b5c | ||
|
|
5dfd16359d | ||
|
|
64a8096f96 | ||
|
|
e5a1d11179 | ||
|
|
5af6e8d5ed | ||
|
|
6ecadfc7a1 | ||
|
|
eb3158c83d | ||
|
|
625b701a68 | ||
|
|
dd59acf0fb | ||
|
|
335d0ffa05 | ||
|
|
3f341d9cf7 | ||
|
|
0adb1046e4 | ||
|
|
324564af72 | ||
|
|
291287c8e4 | ||
|
|
d69fb10cfd | ||
|
|
0f6eab2bfe | ||
|
|
016ac1eade | ||
|
|
2606ed7abf | ||
|
|
3ed4d55a36 | ||
|
|
a3b4ad53dc | ||
|
|
bd98955f57 | ||
|
|
297cfbb895 | ||
|
|
b4c95fbeab | ||
|
|
5e8102e588 | ||
|
|
60f2c3a22b | ||
|
|
7472b1cb4a | ||
|
|
794d8bccd3 | ||
|
|
0db3cfe34d | ||
|
|
5c878b5b84 | ||
|
|
e3bc5f0143 | ||
|
|
f2dbab814e | ||
|
|
b3abbd886e | ||
|
|
8cdc4a936d | ||
|
|
ecc58178dc | ||
|
|
ca3f0f1abd | ||
|
|
987812a886 | ||
|
|
0e6afd9848 | ||
|
|
359e0e070d | ||
|
|
b02ad8377d | ||
|
|
8fdf5ab8c5 | ||
|
|
aceaeb069b | ||
|
|
e39e58b5e2 | ||
|
|
717be3f026 | ||
|
|
5595d12dc3 | ||
|
|
c230de0a14 | ||
|
|
2ecb87ac5a | ||
|
|
2315fc6769 | ||
|
|
6449c36849 | ||
|
|
8f93e9cc40 | ||
|
|
3a52baac14 | ||
|
|
35f08731f6 | ||
|
|
2c866c9265 | ||
|
|
10cfd8ba1e | ||
|
|
da4d88fd84 | ||
|
|
889ed95840 | ||
|
|
716e6cd6ab | ||
|
|
45871a962e | ||
|
|
c6aa47095e | ||
|
|
8c1093cfdc | ||
|
|
31161f894b | ||
|
|
20e5ae7b23 | ||
|
|
22f306e79e | ||
|
|
553b56336c | ||
|
|
a3fa8cf7b9 | ||
|
|
4628eca3dc | ||
|
|
518e624086 | ||
|
|
fa4fa01ec3 | ||
|
|
f526317796 | ||
|
|
550883df6a | ||
|
|
3d5605f5d7 | ||
|
|
1b48f06898 | ||
|
|
b17631900d | ||
|
|
3d8d83568d | ||
|
|
3d95adb0f3 | ||
|
|
971ac0fdeb | ||
|
+2 |
2888af54f3 | ||
|
|
190d4a2c52 | ||
|
|
4d5ab59923 | ||
|
|
f0ad29accb | ||
|
|
0ba45084a0 | ||
|
|
213591a169 | ||
|
|
70fd35df6d | ||
|
|
bd526cb2d2 | ||
|
|
2fbebec7ae | ||
|
|
ca1e008714 | ||
|
|
1ab3de8911 | ||
|
|
47f75225e8 | ||
|
|
15f6577cb9 | ||
|
|
7c5d56a5c1 | ||
|
|
cdc24890ee | ||
|
|
ef5465b667 | ||
|
|
d4ba4fd98a | ||
|
|
074e5d7002 | ||
|
|
18e164fe81 | ||
|
|
82be7c4ed5 | ||
|
|
702dd75291 |
@@ -1,5 +0,0 @@
|
||||
---
|
||||
"claude-dev": patch
|
||||
---
|
||||
|
||||
Fix Ollama connection issue to default endpoint at port 11434
|
||||
@@ -1,5 +0,0 @@
|
||||
---
|
||||
"claude-dev": patch
|
||||
---
|
||||
|
||||
Optimized Cline for GPT-5 model family with an aligned system prompt
|
||||
@@ -1,5 +0,0 @@
|
||||
---
|
||||
"claude-dev": patch
|
||||
---
|
||||
|
||||
Dify.ai api integration
|
||||
@@ -1,5 +0,0 @@
|
||||
---
|
||||
"claude-dev": patch
|
||||
---
|
||||
|
||||
Add speech-to-text dictation feature for Cline account users
|
||||
@@ -1,5 +0,0 @@
|
||||
---
|
||||
"claude-dev": patch
|
||||
---
|
||||
|
||||
Prompt changes for deep-planning in windows/powershell
|
||||
@@ -1,64 +1,69 @@
|
||||
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 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
|
||||
- type: markdown
|
||||
attributes:
|
||||
value: |
|
||||
**Important:** All bug reports must be reproducible using Claude Sonnet 4. 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, 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
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
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
|
||||
@@ -95,6 +95,8 @@ 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"
|
||||
|
||||
+2
-1
@@ -10,5 +10,6 @@
|
||||
"source-map-support/register",
|
||||
"./src/test/requires.ts"
|
||||
],
|
||||
"recursive": true
|
||||
"recursive": true,
|
||||
"exit": true
|
||||
}
|
||||
|
||||
Vendored
+55
-8
@@ -12,6 +12,7 @@
|
||||
"args": [
|
||||
"--extensionDevelopmentPath=${workspaceFolder}",
|
||||
"--disable-workspace-trust",
|
||||
"--disable-extensions", // Avoid conflicts with installed extensions
|
||||
"${workspaceFolder}"
|
||||
],
|
||||
"outFiles": [
|
||||
@@ -31,6 +32,7 @@
|
||||
"args": [
|
||||
"--extensionDevelopmentPath=${workspaceFolder}",
|
||||
"--disable-workspace-trust",
|
||||
"--disable-extensions", // Avoid conflicts with installed extensions
|
||||
"${workspaceFolder}"
|
||||
],
|
||||
"outFiles": [
|
||||
@@ -50,6 +52,7 @@
|
||||
"args": [
|
||||
"--extensionDevelopmentPath=${workspaceFolder}",
|
||||
"--disable-workspace-trust",
|
||||
"--disable-extensions", // Avoid conflicts with installed extensions
|
||||
"${workspaceFolder}"
|
||||
],
|
||||
"outFiles": [
|
||||
@@ -71,7 +74,7 @@
|
||||
"--user-data-dir=${workspaceFolder}/dist/tmp/user",
|
||||
"--profile-temp",
|
||||
"--sync=off",
|
||||
"--disable-extensions",
|
||||
"--disable-extensions", // Avoid conflicts with installed extensions
|
||||
"--extensionDevelopmentPath=${workspaceFolder}",
|
||||
"${workspaceFolder}"
|
||||
],
|
||||
@@ -91,7 +94,7 @@
|
||||
{
|
||||
"type": "node",
|
||||
"request": "launch",
|
||||
"name": "Run cline-core service",
|
||||
"name": "Debug Test Standalone Core Api Server (test:sca-server)",
|
||||
"skipFiles": [
|
||||
"<node_internals>/**"
|
||||
],
|
||||
@@ -100,18 +103,62 @@
|
||||
"${workspaceFolder}/**",
|
||||
"!**/node_modules/**"
|
||||
],
|
||||
"cwd": "${workspaceFolder}/dist-standalone",
|
||||
"cwd": "${workspaceFolder}",
|
||||
"outFiles": [
|
||||
"${workspaceFolder}/dist/**/*.js",
|
||||
"${workspaceFolder}/dist-standalone/**/*.js"
|
||||
],
|
||||
"preLaunchTask": "compile-standalone",
|
||||
"runtimeExecutable": "npx",
|
||||
"runtimeArgs": [
|
||||
"tsx"
|
||||
],
|
||||
"program": "scripts/test-standalone-core-api-server.ts",
|
||||
"env": {
|
||||
// Turns on grpc debug log.
|
||||
//"GRPC_TRACE": "all",
|
||||
//"GRPC_VERBOSITY": "DEBUG",
|
||||
"NODE_PATH": "${workspaceFolder}/dist-standalone/node_modules"
|
||||
"PROTOBUS_PORT": "26040",
|
||||
"HOSTBRIDGE_PORT": "26041",
|
||||
"WORKSPACE_DIR": "${workspaceFolder}",
|
||||
"E2E_TEST": "true",
|
||||
"CLINE_ENVIRONMENT": "local"
|
||||
},
|
||||
"program": "cline-core.js"
|
||||
"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"
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
Vendored
+6
-11
@@ -21,16 +21,11 @@
|
||||
},
|
||||
// Enable Lint and format using Biome
|
||||
"biome.enabled": true,
|
||||
"[typescript]": {
|
||||
"editor.defaultFormatter": "biomejs.biome"
|
||||
},
|
||||
"[typescriptreact]": {
|
||||
"editor.defaultFormatter": "biomejs.biome"
|
||||
},
|
||||
"[jsonc]": {
|
||||
"editor.defaultFormatter": "biomejs.biome"
|
||||
},
|
||||
"[json]": {
|
||||
"editor.defaultFormatter": "biomejs.biome"
|
||||
"editor.defaultFormatter": "biomejs.biome",
|
||||
"editor.codeActionsOnSave": {
|
||||
"source.fixAll.biome": "explicit",
|
||||
"source.removeUnused.biome": "always",
|
||||
"source.removeUnusedImports": "always",
|
||||
"source.organizeImports.biome": "always"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,42 @@
|
||||
# Changelog
|
||||
|
||||
## [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
|
||||
- Add call to action for trying free `grok-code-fast-1` in Announcement banner
|
||||
|
||||
## [3.26.7]
|
||||
|
||||
- Add 200k context window variant for Claude Sonnet 4 to OpenRouter and Cline providers
|
||||
|
||||
## [3.26.6]
|
||||
|
||||
- Add free Grok Coder model to Cline provider for users looking for a fast, free coding model option
|
||||
|
||||
@@ -30,9 +30,9 @@ English | <a href="https://github.com/cline/cline/blob/main/locales/es/README.md
|
||||
</table>
|
||||
</div>
|
||||
|
||||
Meet Cline (pronounced /klaɪn/, like "Klein"), an AI assistant that can use your **CLI** a**N**d **E**ditor.
|
||||
Meet Cline, an AI assistant that can use your **CLI** a**N**d **E**ditor.
|
||||
|
||||
Thanks to [Claude 3.7 Sonnet's agentic coding capabilities](https://www.anthropic.com/claude/sonnet), Cline can handle complex software development tasks step-by-step. With tools that let him create & edit files, explore large projects, use the browser, and execute terminal commands (after you grant permission), he can assist you in ways that go beyond code completion or tech support. Cline can even use the Model Context Protocol (MCP) to create new tools and extend his own capabilities. While autonomous AI scripts traditionally run in sandboxed environments, this extension provides a human-in-the-loop GUI to approve every file change and terminal command, providing a safe and accessible way to explore the potential of agentic AI.
|
||||
Thanks to [Claude Sonnet's agentic coding capabilities](https://www.anthropic.com/claude/sonnet), Cline can handle complex software development tasks step-by-step. With tools that let him create & edit files, explore large projects, use the browser, and execute terminal commands (after you grant permission), he can assist you in ways that go beyond code completion or tech support. Cline can even use the Model Context Protocol (MCP) to create new tools and extend his own capabilities. While autonomous AI scripts traditionally run in sandboxed environments, this extension provides a human-in-the-loop GUI to approve every file change and terminal command, providing a safe and accessible way to explore the potential of agentic AI.
|
||||
|
||||
1. Enter your task and add images to convert mockups into functional apps or fix bugs with screenshots.
|
||||
2. Cline starts by analyzing your file structure & source code ASTs, running regex searches, and reading relevant files to get up to speed in existing projects. By carefully managing what information is added to context, Cline can provide valuable assistance even for large, complex projects without overwhelming the context window.
|
||||
@@ -87,7 +87,7 @@ All changes made by Cline are recorded in your file's Timeline, providing an eas
|
||||
|
||||
### Use the Browser
|
||||
|
||||
With Claude 3.5 Sonnet's new [Computer Use](https://www.anthropic.com/news/3-5-models-and-computer-use) capability, Cline can launch a browser, click elements, type text, and scroll, capturing screenshots and console logs at each step. This allows for interactive debugging, end-to-end testing, and even general web use! This gives him autonomy to fixing visual bugs and runtime issues without you needing to handhold and copy-pasting error logs yourself.
|
||||
With Claude Sonnet's new [Computer Use](https://www.anthropic.com/news/3-5-models-and-computer-use) capability, Cline can launch a browser, click elements, type text, and scroll, capturing screenshots and console logs at each step. This allows for interactive debugging, end-to-end testing, and even general web use! This gives him autonomy to fixing visual bugs and runtime issues without you needing to handhold and copy-pasting error logs yourself.
|
||||
|
||||
Try asking Cline to "test the app", and watch as he runs a command like `npm run dev`, launches your locally running dev server in a browser, and performs a series of tests to confirm that everything works. [See a demo here.](https://x.com/sdrzn/status/1850880547825823989)
|
||||
|
||||
|
||||
+9
-2
@@ -37,7 +37,8 @@
|
||||
"useYield": "off",
|
||||
"noConstructorReturn": "off",
|
||||
"noInvalidPositionAtImportRule": "off",
|
||||
"noSwitchDeclarations": "off"
|
||||
"noSwitchDeclarations": "off",
|
||||
"noUnusedImports": "error"
|
||||
},
|
||||
"a11y": "off",
|
||||
"style": {
|
||||
@@ -134,7 +135,12 @@
|
||||
"**",
|
||||
"!**/hosts/vscode/**",
|
||||
"!**/test/**",
|
||||
"!src/extension.ts"
|
||||
"!**/*.test.ts",
|
||||
"!src/dev/**",
|
||||
"!src/extension.ts",
|
||||
"!src/integrations/git/commit-message-generator.ts",
|
||||
"!src/integrations/terminal/**",
|
||||
"!src/core/controller/ui/openWalkthrough.ts"
|
||||
],
|
||||
"plugins": [
|
||||
"src/dev/grit/vscode-api.grit"
|
||||
@@ -147,6 +153,7 @@
|
||||
"!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"
|
||||
],
|
||||
|
||||
+1
-1
@@ -60,6 +60,7 @@
|
||||
"getting-started/what-is-cline",
|
||||
"getting-started/model-selection-guide",
|
||||
"getting-started/installing-cline",
|
||||
"getting-started/installing-cline-jetbrains",
|
||||
"getting-started/task-management",
|
||||
"getting-started/understanding-context-management",
|
||||
{
|
||||
@@ -90,7 +91,6 @@
|
||||
"features/focus-chain",
|
||||
"features/auto-compact",
|
||||
"features/editing-messages",
|
||||
"features/dictation",
|
||||
{
|
||||
"group": "@ Mentions",
|
||||
"pages": [
|
||||
|
||||
@@ -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/Cline.ts).
|
||||
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).
|
||||
|
||||
Cline has access to the following tools for various tasks:
|
||||
|
||||
|
||||
@@ -1,60 +0,0 @@
|
||||
---
|
||||
title: Dictation
|
||||
description:
|
||||
---
|
||||
|
||||
Cline lets you transcribe speech to text in an easy, built-in service
|
||||
|
||||
## Get Started
|
||||
|
||||
1. **Enable Dictation** in Feature Settings.
|
||||
2. **Click the microphone** in the chat input area.
|
||||
3. **Speak** - the button turns red while recording.
|
||||
4. **Click Stop Recording** when done.
|
||||
5. **Wait for transcription** - "[Transcribing...]" will appear and then the finished transcription will appear.
|
||||
|
||||
## Settings
|
||||
|
||||
Enable or disable dictation in Feature Settings by toggling "Enable Dictation." You can also change the transcription language to one of the supported languages.
|
||||
|
||||
## Requirements
|
||||
|
||||
Cline 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.
|
||||
|
||||
## Technical Details
|
||||
|
||||
### Independent from Chat Provider
|
||||
|
||||
The voice transcription feature works completely independently from whatever chat provider you're using. You can use Claude, GPT-4, or any other model for your conversations, and voice transcription will always use Cline's own transcription service. As long as you have a valid Cline account with enough credits, dictation will work regardless of your chat model choice.
|
||||
|
||||
### Audio Format
|
||||
|
||||
Voice recordings are captured in WebM format using the Opus codec for optimal compression. The system records in mono (single channel) at a 16kHz sample rate, which is specifically optimized for voice recognition. The bitrate is set to 32kbps to keep file sizes efficient while maintaining good audio quality.
|
||||
|
||||
### Privacy & Security
|
||||
|
||||
Your audio is recorded locally on your machine and only the audio file itself is sent to Cline's transcription service for processing. No audio is stored anywhere after transcription is complete, and all temporary files are automatically cleaned up to protect your privacy.
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
`Failed to start recording` - Audio recording tools aren't installed. Cline will prompt you to install FFmpeg - just follow the chat instructions.
|
||||
|
||||
`Invalid audio format or request data` - Usually an audio recording issue. Make sure FFmpeg is properly installed and working.
|
||||
|
||||
`Authentication failed` - You need to reauthenticate your Cline account. Sign out and back in, then check your internet connection.
|
||||
|
||||
`Insufficient credits for transcription service` - Your Cline account doesn't have enough credits. Check your balance and purchase more if needed.
|
||||
|
||||
`Cannot connect to transcription service` - Connection issue. Check your internet connection and firewall settings aren't blocking Cline's servers.
|
||||
|
||||
## API Usage
|
||||
|
||||
Voice transcription uses Cline's transcription service, which requires credits from your Cline account. Currently, voice transcription is billed at $0.006 per minute of audio.
|
||||
|
||||
**Note:** We are still experimenting with this feature and pricing may change in the future.
|
||||
@@ -0,0 +1,135 @@
|
||||
---
|
||||
title: "Installing Cline for JetBrains (Early Access)"
|
||||
description: "Get early access to Cline 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 in early access. All core features are functional, with ongoing improvements based on user feedback.</Note>
|
||||
|
||||
## Installation
|
||||
|
||||
As part of our early access program, Cline for JetBrains is available through direct download before its official marketplace release. 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/eap](https://plugins.jetbrains.com/plugin/28247-cline/versions/eap)
|
||||
- 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
|
||||
@@ -0,0 +1,14 @@
|
||||
// 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)
|
||||
}
|
||||
})()
|
||||
@@ -7,12 +7,13 @@ SAP AI Core and the generative AI hub help you to integrate LLMs and AI into new
|
||||
|
||||
**Website:** [SAP Help Portal](https://help.sap.com/docs/sap-ai-core/sap-ai-core-service-guide/what-is-sap-ai-core)
|
||||
|
||||
### Getting a Service Binding
|
||||
|
||||
> 💡 **Information**
|
||||
>
|
||||
> SAP AI Core, and Generative AI Hub, are offerings from SAP BTP.
|
||||
> You need an active SAP BTP contract and a existing subaccount with a SAP AI Core instance to perform these steps.
|
||||
> You need an active SAP BTP contract and a existing subaccount with a SAP AI Core instance with the `extended` service plan (For more details about SAP AI Core service plans and their capabilities, see the [Service Plans documentation](https://help.sap.com/docs/sap-ai-core/sap-ai-core-service-guide/service-plans)) to perform these steps.
|
||||
|
||||
### Getting a Service Binding
|
||||
|
||||
1. **Access:** Go to your subaccount via [BTP Cloud Cockpit](cockpit.btp.cloud.sap/cockpit)
|
||||
2. **Create a Service Binding:** Go to "Instances and Subscriptions", select your SAP AI Core service instance and click on Service Bindings > Create.
|
||||
@@ -32,14 +33,30 @@ Refer to the [Generative AI Hub Supported Models page](https://me.sap.com/notes/
|
||||
5. **Enter Base URL:** Add the `.serviceurls.AI_API_URL` field from the service binding into the "AI Core Base URL" field.
|
||||
6. **Enter Auth URL:** Add the `.url` field from the service binding into the "AI Core Auth URL" field.
|
||||
7. **Enter Resource Group:** Add the resource group where you have your model deployments. See [Create a Deployment for a Generative AI Model](https://help.sap.com/docs/sap-ai-core/sap-ai-core-service-guide/create-deployment-for-generative-ai-model-in-sap-ai-core).
|
||||
8. **Select Model:** Choose your desired model from the "Model" dropdown.
|
||||
8. **Configure Orchestration Mode:** If you have an `extended` service plan, the "Orchestration Mode" checkbox will automatically appear.
|
||||
9. **Select Model:** Choose your desired model from the "Model" dropdown.
|
||||
|
||||
### Orchestration Mode vs Native API
|
||||
|
||||
**Orchestration Mode:**
|
||||
- **Simplified usage:** Provides access to all available models without requiring individual deployments using the [Harmonized API](https://help.sap.com/docs/sap-ai-core/sap-ai-core-service-guide/harmonized-api)
|
||||
|
||||
**Native API Mode:**
|
||||
- **Manual deployments:** Requires manual model deployment and management in your SAP AI Core service instance
|
||||
|
||||
### Tips and Notes
|
||||
|
||||
- **Model Selection:** The model dropdown displays models in two separate lists:
|
||||
- **Deployed Models:** These models are already deployed in your specified resource group and are ready to use immediately.
|
||||
- **Not Deployed Models:** These models don't have active deployments in your specified resource group. You won't be able to use these models until you create deployments for them in SAP AI Core.
|
||||
- **Creating Deployments:** To use a not deployed model, you'll need to create a deployment in your resource group in sap ai core service instance. See [Create a Deployment for a Generative AI Model](https://help.sap.com/docs/sap-ai-core/sap-ai-core-service-guide/create-deployment-for-generative-ai-model-in-sap-ai-core) for instructions.
|
||||
- **Service Plan Requirement:** You must have the SAP AI Core `extended` service plan to use LLMs with Cline. Other service plans do not provide access to Generative AI Hub.
|
||||
|
||||
- **Orchestration Mode (Recommended):** Keep Orchestration Mode enabled for the simplest setup. It provides automatic access to all available models without requiring manual deployments.
|
||||
|
||||
- **Native API Mode:** Only disable Orchestration Mode if you have specific requirements that necessitate direct AI Core API access or need features not supported by the orchestration mode.
|
||||
|
||||
- **When using Native API Mode:**
|
||||
- **Model Selection:** The model dropdown displays models in two separate lists:
|
||||
- **Deployed Models:** These models are already deployed in your specified resource group and are ready to use immediately.
|
||||
- **Not Deployed Models:** These models don't have active deployments in your specified resource group. You won't be able to use these models until you create deployments for them in SAP AI Core.
|
||||
- **Creating Deployments:** To use a model that has not been deployed yet, you'll need to create a deployment in your SAP AI Core service instance. See [Create a Deployment for a Generative AI Model](https://help.sap.com/docs/sap-ai-core/sap-ai-core-service-guide/create-deployment-for-generative-ai-model-in-sap-ai-core) for instructions.
|
||||
|
||||
#### Configuring Reasoning Effort for OpenAI Models
|
||||
|
||||
|
||||
@@ -49,6 +49,44 @@ 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:
|
||||
|
||||
+2
-2
@@ -160,9 +160,9 @@ const standaloneConfig = {
|
||||
...baseConfig,
|
||||
entryPoints: ["src/standalone/cline-core.ts"],
|
||||
outfile: `${destDir}/cline-core.js`,
|
||||
// These gRPC protos need to load files from the module directory at runtime,
|
||||
// These modules need to load files from the module directory at runtime,
|
||||
// so they cannot be bundled.
|
||||
external: ["vscode", "@grpc/reflection", "grpc-health-check"],
|
||||
external: ["vscode", "@grpc/reflection", "grpc-health-check", "better-sqlite3"],
|
||||
}
|
||||
|
||||
// E2E build script configuration
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { Anthropic } from "@anthropic-ai/sdk"
|
||||
import { ToolUseName, ToolParamName } from "../../src/core/assistant-message"
|
||||
import { ToolParamName } from "../../src/core/assistant-message"
|
||||
import { ClineDefaultTool } from "../../src/shared/tools"
|
||||
|
||||
export interface InputMessage {
|
||||
role: "user" | "assistant"
|
||||
@@ -88,7 +89,7 @@ export interface TestResult {
|
||||
}
|
||||
|
||||
export interface ExtractedToolCall {
|
||||
name: ToolUseName
|
||||
name: ClineDefaultTool
|
||||
input: Partial<Record<ToolParamName, string>>
|
||||
}
|
||||
|
||||
|
||||
Generated
+467
-65
File diff suppressed because it is too large
Load Diff
+17
-15
@@ -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.26.6",
|
||||
"version": "3.28.0",
|
||||
"icon": "assets/icons/icon.png",
|
||||
"engines": {
|
||||
"vscode": "^1.84.0"
|
||||
@@ -102,15 +102,8 @@
|
||||
"activitybar": [
|
||||
{
|
||||
"id": "claude-dev-ActivityBar",
|
||||
"title": "Cline (⌘+')",
|
||||
"icon": "assets/icons/icon.svg",
|
||||
"when": "isMac"
|
||||
},
|
||||
{
|
||||
"id": "claude-dev-ActivityBar",
|
||||
"title": "Cline (Ctrl+')",
|
||||
"icon": "assets/icons/icon.svg",
|
||||
"when": "!isMac"
|
||||
"title": "Cline",
|
||||
"icon": "assets/icons/icon.svg"
|
||||
}
|
||||
]
|
||||
},
|
||||
@@ -348,7 +341,9 @@
|
||||
"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": "rimraf dist dist-standalone webview-ui/build src/generated out/",
|
||||
"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",
|
||||
"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",
|
||||
@@ -362,15 +357,18 @@
|
||||
"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": "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",
|
||||
"test:e2e": "playwright install && vsce package --allow-package-secrets sendgrid --out dist/e2e.vsix && node src/test/e2e/utils/build.mjs && playwright test",
|
||||
"test:e2e:optimal": "vsce package --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",
|
||||
@@ -388,6 +386,7 @@
|
||||
"@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",
|
||||
@@ -411,6 +410,7 @@
|
||||
"lint-staged": "^16.1.0",
|
||||
"minimatch": "^3.0.3",
|
||||
"npm-run-all": "^4.1.5",
|
||||
"prebuild-install": "^7.1.3",
|
||||
"protoc-gen-ts": "^0.8.7",
|
||||
"proxyquire": "^2.1.3",
|
||||
"rimraf": "^6.0.1",
|
||||
@@ -429,7 +429,7 @@
|
||||
"@bufbuild/protobuf": "^2.2.5",
|
||||
"@cerebras/cerebras_cloud_sdk": "^1.35.0",
|
||||
"@google-cloud/vertexai": "^1.9.3",
|
||||
"@google/genai": "1.0.0",
|
||||
"@google/genai": "^1.11.0",
|
||||
"@grpc/grpc-js": "^1.9.15",
|
||||
"@grpc/reflection": "^1.0.4",
|
||||
"@mistralai/mistralai": "^1.5.0",
|
||||
@@ -441,6 +441,8 @@
|
||||
"@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",
|
||||
@@ -477,7 +479,7 @@
|
||||
"p-timeout": "^6.1.4",
|
||||
"p-wait-for": "^5.0.2",
|
||||
"pdf-parse": "^1.1.1",
|
||||
"posthog-node": "^4.8.1",
|
||||
"posthog-node": "^5.8.0",
|
||||
"puppeteer-chromium-resolver": "^23.0.0",
|
||||
"puppeteer-core": "^23.4.0",
|
||||
"reconnecting-eventsource": "^1.6.4",
|
||||
|
||||
@@ -2,6 +2,7 @@ syntax = "proto3";
|
||||
|
||||
package cline;
|
||||
import "cline/common.proto";
|
||||
import "cline/state.proto";
|
||||
option java_package = "bot.cline.proto";
|
||||
option java_multiple_files = true;
|
||||
|
||||
@@ -10,7 +11,6 @@ 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,11 +31,6 @@ 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;
|
||||
|
||||
@@ -8,19 +8,16 @@ 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;
|
||||
}
|
||||
|
||||
@@ -29,7 +26,6 @@ message String {
|
||||
}
|
||||
|
||||
message Int64Request {
|
||||
Metadata metadata = 1;
|
||||
int64 value = 2;
|
||||
}
|
||||
|
||||
@@ -38,7 +34,6 @@ message Int64 {
|
||||
}
|
||||
|
||||
message BytesRequest {
|
||||
Metadata metadata = 1;
|
||||
bytes value = 2;
|
||||
}
|
||||
|
||||
@@ -47,7 +42,6 @@ message Bytes {
|
||||
}
|
||||
|
||||
message BooleanRequest {
|
||||
Metadata metadata = 1;
|
||||
bool value = 2;
|
||||
}
|
||||
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
+68
-50
@@ -32,7 +32,7 @@ service ModelsService {
|
||||
// Refreshes and returns Baseten models
|
||||
rpc refreshBasetenModels(EmptyRequest) returns (OpenRouterCompatibleModelInfo);
|
||||
// Fetches available models from SAP AI Core
|
||||
rpc getSapAiCoreModels(SapAiCoreModelsRequest) returns (StringArray);
|
||||
rpc getSapAiCoreModels(SapAiCoreModelsRequest) returns (SapAiCoreModelsResponse);
|
||||
}
|
||||
|
||||
// List of VS Code LM models
|
||||
@@ -50,20 +50,20 @@ message LanguageModelChatSelector {
|
||||
|
||||
// Price tier for tiered pricing models
|
||||
message PriceTier {
|
||||
int32 token_limit = 1; // Upper limit (inclusive) of input tokens for this price
|
||||
int64 token_limit = 1; // Upper limit (inclusive) of input tokens for this price
|
||||
double price = 2; // Price per million tokens for this tier
|
||||
}
|
||||
|
||||
// Thinking configuration for models that support thinking/reasoning
|
||||
message ThinkingConfig {
|
||||
optional int32 max_budget = 1; // Max allowed thinking budget tokens
|
||||
optional int64 max_budget = 1; // Max allowed thinking budget tokens
|
||||
optional double output_price = 2; // Output price per million tokens when budget > 0
|
||||
repeated PriceTier output_price_tiers = 3; // Optional: Tiered output price when budget > 0
|
||||
}
|
||||
|
||||
// Model tier for tiered pricing structures
|
||||
message ModelTier {
|
||||
int32 context_window = 1;
|
||||
int64 context_window = 1;
|
||||
optional double input_price = 2;
|
||||
optional double output_price = 3;
|
||||
optional double cache_writes_price = 4;
|
||||
@@ -108,6 +108,19 @@ 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;
|
||||
bool orchestration_available = 2;
|
||||
}
|
||||
|
||||
// Request for updating API configuration
|
||||
message UpdateApiConfigurationRequest {
|
||||
Metadata metadata = 1;
|
||||
@@ -155,8 +168,8 @@ enum ApiProvider {
|
||||
|
||||
// Model info for OpenAI-compatible models
|
||||
message OpenAiCompatibleModelInfo {
|
||||
optional int32 max_tokens = 1;
|
||||
optional int32 context_window = 2;
|
||||
optional int64 max_tokens = 1;
|
||||
optional int64 context_window = 2;
|
||||
optional bool supports_images = 3;
|
||||
bool supports_prompt_cache = 4;
|
||||
optional double input_price = 5;
|
||||
@@ -173,8 +186,8 @@ message OpenAiCompatibleModelInfo {
|
||||
|
||||
// Model info for LiteLLM models
|
||||
message LiteLLMModelInfo {
|
||||
optional int32 max_tokens = 1;
|
||||
optional int32 context_window = 2;
|
||||
optional int64 max_tokens = 1;
|
||||
optional int64 context_window = 2;
|
||||
optional bool supports_images = 3;
|
||||
bool supports_prompt_cache = 4;
|
||||
optional double input_price = 5;
|
||||
@@ -226,8 +239,8 @@ message ModelsApiConfiguration {
|
||||
optional string requesty_base_url = 33;
|
||||
optional string together_api_key = 34;
|
||||
optional string fireworks_api_key = 35;
|
||||
optional int32 fireworks_model_max_completion_tokens = 36;
|
||||
optional int32 fireworks_model_max_tokens = 37;
|
||||
optional int64 fireworks_model_max_completion_tokens = 36;
|
||||
optional int64 fireworks_model_max_tokens = 37;
|
||||
optional string qwen_api_key = 38;
|
||||
optional string doubao_api_key = 39;
|
||||
optional string mistral_api_key = 40;
|
||||
@@ -239,34 +252,35 @@ message ModelsApiConfiguration {
|
||||
optional string xai_api_key = 46;
|
||||
optional string sambanova_api_key = 47;
|
||||
optional string cerebras_api_key = 48;
|
||||
optional int32 request_timeout_ms = 49;
|
||||
optional int64 request_timeout_ms = 49;
|
||||
optional string sap_ai_core_client_id = 50;
|
||||
optional string sap_ai_core_client_secret = 51;
|
||||
optional string sap_ai_resource_group = 52;
|
||||
optional string sap_ai_core_token_url = 53;
|
||||
optional string sap_ai_core_base_url = 54;
|
||||
optional string moonshot_api_key = 55;
|
||||
optional string moonshot_api_line = 56;
|
||||
optional string aws_authentication = 57;
|
||||
optional string aws_bedrock_api_key = 58;
|
||||
optional string cline_account_id = 59;
|
||||
optional string groq_api_key = 60;
|
||||
optional string hugging_face_api_key = 61;
|
||||
optional string huawei_cloud_maas_api_key = 62;
|
||||
optional string baseten_api_key = 63;
|
||||
optional string ollama_api_key = 64;
|
||||
optional string zai_api_key = 65;
|
||||
optional string zai_api_line = 66;
|
||||
optional string lm_studio_max_tokens = 67;
|
||||
optional string vercel_ai_gateway_api_key = 68;
|
||||
optional string qwen_code_oauth_path = 69;
|
||||
optional string dify_api_key = 70;
|
||||
optional string dify_base_url = 71;
|
||||
optional bool sap_ai_core_use_orchestration_mode = 55;
|
||||
optional string moonshot_api_key = 56;
|
||||
optional string moonshot_api_line = 57;
|
||||
optional string aws_authentication = 58;
|
||||
optional string aws_bedrock_api_key = 59;
|
||||
optional string cline_account_id = 60;
|
||||
optional string groq_api_key = 61;
|
||||
optional string hugging_face_api_key = 62;
|
||||
optional string huawei_cloud_maas_api_key = 63;
|
||||
optional string baseten_api_key = 64;
|
||||
optional string ollama_api_key = 65;
|
||||
optional string zai_api_key = 66;
|
||||
optional string zai_api_line = 67;
|
||||
optional string lm_studio_max_tokens = 68;
|
||||
optional string vercel_ai_gateway_api_key = 69;
|
||||
optional string qwen_code_oauth_path = 70;
|
||||
optional string dify_api_key = 71;
|
||||
optional string dify_base_url = 72;
|
||||
|
||||
// Plan mode configurations
|
||||
optional ApiProvider plan_mode_api_provider = 100;
|
||||
optional string plan_mode_api_model_id = 101;
|
||||
optional int32 plan_mode_thinking_budget_tokens = 102;
|
||||
optional int64 plan_mode_thinking_budget_tokens = 102;
|
||||
optional string plan_mode_reasoning_effort = 103;
|
||||
optional LanguageModelChatSelector plan_mode_vs_code_lm_model_selector = 104;
|
||||
optional bool plan_mode_aws_bedrock_custom_selected = 105;
|
||||
@@ -284,21 +298,23 @@ 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_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;
|
||||
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;
|
||||
|
||||
|
||||
// Act mode configurations
|
||||
optional ApiProvider act_mode_api_provider = 200;
|
||||
optional string act_mode_api_model_id = 201;
|
||||
optional int32 act_mode_thinking_budget_tokens = 202;
|
||||
optional int64 act_mode_thinking_budget_tokens = 202;
|
||||
optional string act_mode_reasoning_effort = 203;
|
||||
optional LanguageModelChatSelector act_mode_vs_code_lm_model_selector = 204;
|
||||
optional bool act_mode_aws_bedrock_custom_selected = 205;
|
||||
@@ -316,16 +332,18 @@ 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_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;
|
||||
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;
|
||||
|
||||
|
||||
repeated string favorited_model_ids = 300;
|
||||
}
|
||||
|
||||
+21
-10
@@ -8,7 +8,6 @@ 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);
|
||||
@@ -56,6 +55,7 @@ enum OpenaiReasoningEffort {
|
||||
LOW = 0;
|
||||
MEDIUM = 1;
|
||||
HIGH = 2;
|
||||
MINIMAL = 3;
|
||||
}
|
||||
|
||||
enum McpDisplayMode {
|
||||
@@ -106,6 +106,16 @@ 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;
|
||||
@@ -123,10 +133,11 @@ message UpdateSettingsRequest {
|
||||
optional string preferred_language = 14;
|
||||
optional OpenaiReasoningEffort openai_reasoning_effort = 15;
|
||||
optional bool strict_plan_mode_enabled = 16;
|
||||
optional DictationSettings dictation_settings = 17;
|
||||
optional FocusChainSettings focus_chain_settings = 18;
|
||||
optional bool use_auto_condense = 19;
|
||||
optional string custom_prompt = 20;
|
||||
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;
|
||||
}
|
||||
|
||||
// Complete API Configuration message
|
||||
@@ -264,16 +275,16 @@ message UpdateTerminalConnectionTimeoutRequest {
|
||||
optional int32 timeout_ms = 1;
|
||||
}
|
||||
|
||||
message DictationSettings {
|
||||
bool dictation_enabled = 1;
|
||||
string dictation_language = 2;
|
||||
}
|
||||
|
||||
message FocusChainSettings {
|
||||
bool enabled = 1;
|
||||
int32 remind_cline_interval = 2;
|
||||
}
|
||||
|
||||
message Viewport {
|
||||
int32 width = 1;
|
||||
int32 height = 2;
|
||||
}
|
||||
|
||||
message UpdateTerminalConnectionTimeoutResponse {
|
||||
optional int32 timeout_ms = 1;
|
||||
}
|
||||
|
||||
@@ -18,6 +18,10 @@ service EnvService {
|
||||
rpc getMachineId(cline.EmptyRequest) returns (cline.String);
|
||||
|
||||
rpc getHostVersion(cline.EmptyRequest) returns (GetHostVersionResponse);
|
||||
|
||||
rpc getTelemetrySettings(cline.EmptyRequest) returns (GetTelemetrySettingsResponse);
|
||||
|
||||
rpc subscribeToTelemetrySettings(cline.EmptyRequest) returns (stream TelemetrySettingsEvent);
|
||||
}
|
||||
|
||||
message GetHostVersionResponse {
|
||||
@@ -26,3 +30,16 @@ message GetHostVersionResponse {
|
||||
// The version of the host platform, e.g. 1.103.0
|
||||
optional string version = 2;
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
@@ -1,36 +0,0 @@
|
||||
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,8 +4,6 @@ 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.
|
||||
@@ -40,7 +38,6 @@ service WindowService {
|
||||
}
|
||||
|
||||
message ShowTextDocumentRequest {
|
||||
cline.Metadata metadata = 1;
|
||||
string path = 2;
|
||||
optional ShowTextDocumentOptions options = 3;
|
||||
}
|
||||
@@ -59,7 +56,6 @@ message TextEditorInfo {
|
||||
}
|
||||
|
||||
message ShowOpenDialogueRequest {
|
||||
cline.Metadata metadata = 1;
|
||||
optional bool can_select_many = 2;
|
||||
optional string open_label = 3;
|
||||
optional ShowOpenDialogueFilterOption filters = 4;
|
||||
|
||||
@@ -18,14 +18,15 @@ 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);
|
||||
|
||||
// Opens the IDE file explorer panel and selects a file or directory.
|
||||
rpc openInFileExplorerPanel(OpenInFileExplorerPanelRequest) returns (OpenInFileExplorerPanelResponse);
|
||||
|
||||
// Opens and focuses the Cline sidebar panel in the host IDE.
|
||||
rpc openClineSidebarPanel(OpenClineSidebarPanelRequest) returns (OpenClineSidebarPanelResponse);
|
||||
}
|
||||
|
||||
message GetWorkspacePathsRequest {
|
||||
@@ -86,3 +87,7 @@ message OpenInFileExplorerPanelRequest {
|
||||
string path = 1;
|
||||
}
|
||||
message OpenInFileExplorerPanelResponse {}
|
||||
|
||||
// Request/response for opening the Cline sidebar
|
||||
message OpenClineSidebarPanelRequest {}
|
||||
message OpenClineSidebarPanelResponse {}
|
||||
|
||||
+2
-49
@@ -10,7 +10,6 @@ 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")
|
||||
@@ -31,14 +30,13 @@ 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=messages", // Message fields are optional, scalars are not.
|
||||
"useOptionals=none", // scalar and message fields are required unless they are marked as optional.
|
||||
"useDate=false", // Timestamp fields will not be automatically converted to Date.
|
||||
]
|
||||
|
||||
async function main() {
|
||||
await cleanup()
|
||||
await compileProtos()
|
||||
await checkProtos()
|
||||
await generateProtoBusSetup()
|
||||
await generateHostBridgeClient()
|
||||
}
|
||||
@@ -59,7 +57,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,outputClientImpl=false", ...TS_PROTO_OPTIONS])
|
||||
tsProtoc(GRPC_JS_OUT_DIR, protoFiles, ["outputServices=grpc-js", ...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])
|
||||
|
||||
@@ -187,51 +185,6 @@ 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)
|
||||
|
||||
@@ -6,40 +6,102 @@ 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...")
|
||||
const cwd = process.cwd()
|
||||
process.chdir(BUILD_DIR)
|
||||
execSync("npm install", { stdio: "inherit", cwd: BUILD_DIR })
|
||||
|
||||
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)
|
||||
// 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",
|
||||
)
|
||||
process.exit(1)
|
||||
} finally {
|
||||
process.chdir(cwd)
|
||||
}
|
||||
|
||||
// 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)
|
||||
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("")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -47,10 +109,13 @@ 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 archive = archiver("zip", { zlib: { level: 3 } })
|
||||
const startTime = Date.now()
|
||||
const archive = archiver("zip", { zlib: { level: 6 } })
|
||||
|
||||
output.on("close", () => {
|
||||
console.log(`Created ${zipPath} (${(archive.pointer() / 1024 / 1024).toFixed(1)} MB)`)
|
||||
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`)
|
||||
})
|
||||
archive.on("warning", (err) => {
|
||||
console.warn(`Warning: ${err}`)
|
||||
@@ -73,7 +138,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
|
||||
@@ -145,7 +210,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 (process.env.IS_DEBUG_BUILD) {
|
||||
if (IS_DEBUG_BUILD) {
|
||||
allIgnore = allIgnore.filter((pattern) => !pattern.endsWith(".map"))
|
||||
console.log("Debug build: Including .map files in package")
|
||||
}
|
||||
@@ -167,6 +232,7 @@ function createIsIgnored(standaloneIgnores) {
|
||||
|
||||
/* cp -r */
|
||||
async function cpr(source, dest) {
|
||||
log_verbose(`Copying ${source} -> ${dest}`)
|
||||
await cp(source, dest, {
|
||||
recursive: true,
|
||||
preserveTimestamps: true,
|
||||
@@ -175,7 +241,7 @@ async function cpr(source, dest) {
|
||||
}
|
||||
|
||||
function log_verbose(...args) {
|
||||
if (process.argv.includes("-v") || process.argv.includes("--verbose")) {
|
||||
if (IS_VERBOSE) {
|
||||
console.log(...args)
|
||||
}
|
||||
}
|
||||
|
||||
Executable
+377
@@ -0,0 +1,377 @@
|
||||
#!/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)
|
||||
})
|
||||
@@ -3,7 +3,11 @@ 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 { host } from "src/generated/grpc-js/index"
|
||||
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 { getPackageDefinition } from "./proto-utils.mjs"
|
||||
|
||||
export async function startTestHostBridgeServer() {
|
||||
@@ -14,11 +18,11 @@ export async function startTestHostBridgeServer() {
|
||||
healthImpl.addToServer(server)
|
||||
|
||||
// Add host bridge services using the mock implementations
|
||||
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"))
|
||||
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"))
|
||||
|
||||
// Load package definition for reflection service
|
||||
const packageDefinition = await getPackageDefinition()
|
||||
@@ -58,8 +62,9 @@ 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: ["/test-workspace"],
|
||||
paths: [workspaceDir],
|
||||
})
|
||||
return
|
||||
|
||||
@@ -69,6 +74,12 @@ function createMockService<T extends grpc.UntypedServiceImplementation>(serviceN
|
||||
})
|
||||
return
|
||||
|
||||
case "getTelemetrySettings":
|
||||
callback(null, {
|
||||
isEnabled: 2, // Setting.DISABLED
|
||||
})
|
||||
return
|
||||
|
||||
case "clipboardReadText":
|
||||
callback(null, {
|
||||
value: "",
|
||||
@@ -115,8 +126,8 @@ function createMockService<T extends grpc.UntypedServiceImplementation>(serviceN
|
||||
})
|
||||
return
|
||||
|
||||
// For streaming methods (like subscribeToFile)
|
||||
case "subscribeToFile":
|
||||
// For streaming methods (like subscribeToTelemetrySettings)
|
||||
case "subscribeToTelemetrySettings":
|
||||
// Just end the stream immediately
|
||||
call.end()
|
||||
return
|
||||
|
||||
@@ -0,0 +1,178 @@
|
||||
#!/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 { mkdtempSync, rmSync } from "node:fs"
|
||||
import * as os from "node:os"
|
||||
import { ChildProcess, execSync, spawn } from "child_process"
|
||||
import * as fs from "fs"
|
||||
import * as path from "path"
|
||||
import { ClineApiServerMock } from "../src/test/e2e/fixtures/server/index"
|
||||
|
||||
// Configuration
|
||||
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"
|
||||
|
||||
// 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)
|
||||
|
||||
async function main(): Promise<void> {
|
||||
console.log("Starting Simple Cline gRPC Server...")
|
||||
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)
|
||||
}
|
||||
|
||||
// Create temporary directories like e2e tests
|
||||
const userDataDir = mkdtempSync(path.join(os.tmpdir(), "vsce"))
|
||||
const extensionsDir = mkdtempSync(path.join(os.tmpdir(), "vsce"))
|
||||
const clineTestWorkspace = mkdtempSync(path.join(os.tmpdir(), "cline-test-workspace-"))
|
||||
|
||||
// Start hostbridge test server in background.
|
||||
// We run it as a child process to emulate how the extension currently operates
|
||||
console.log("Starting HostBridge test server...")
|
||||
const hostbridge: ChildProcess = spawn("npx", ["tsx", path.join(__dirname, "test-hostbridge-server.ts")], {
|
||||
stdio: "pipe",
|
||||
detached: false,
|
||||
env: {
|
||||
...process.env,
|
||||
TEST_HOSTBRIDGE_WORKSPACE_DIR: clineTestWorkspace,
|
||||
},
|
||||
})
|
||||
|
||||
console.log(`Temp user data dir: ${userDataDir}`)
|
||||
console.log(`Temp extensions dir: ${extensionsDir}`)
|
||||
|
||||
// Extract standalone.zip to the extensions directory
|
||||
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 {
|
||||
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)
|
||||
}
|
||||
|
||||
// Start the core service
|
||||
// We run it as a child process to emulate how the extension currently operates
|
||||
console.log("Starting Cline Core Service...")
|
||||
const coreService: ChildProcess = spawn("node", [clineCoreFile], {
|
||||
cwd: distDir,
|
||||
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: E2E_TEST,
|
||||
CLINE_ENVIRONMENT: CLINE_ENVIRONMENT,
|
||||
CLINE_DIR: userDataDir,
|
||||
INSTALL_DIR: extensionsDir,
|
||||
},
|
||||
stdio: "inherit",
|
||||
})
|
||||
|
||||
// Handle graceful shutdown
|
||||
const shutdown = async (): Promise<void> => {
|
||||
console.log(`\n Shutting down services...\n${userDataDir}\n${extensionsDir}\n${clineTestWorkspace}\n`)
|
||||
hostbridge.kill()
|
||||
coreService.kill()
|
||||
await ClineApiServerMock.stopGlobalServer()
|
||||
|
||||
// Cleanup temp directories
|
||||
try {
|
||||
rmSync(userDataDir, { recursive: true, force: true })
|
||||
rmSync(extensionsDir, { recursive: true, force: true })
|
||||
rmSync(clineTestWorkspace, { recursive: true, force: true })
|
||||
console.log("Cleaned up temporary directories")
|
||||
} catch (error) {
|
||||
console.warn("Failed to cleanup temp directories:", error)
|
||||
}
|
||||
|
||||
process.exit(0)
|
||||
}
|
||||
|
||||
process.on("SIGINT", shutdown)
|
||||
process.on("SIGTERM", shutdown)
|
||||
|
||||
coreService.on("exit", (code) => {
|
||||
console.log(`Core service exited with code ${code}`)
|
||||
hostbridge.kill()
|
||||
process.exit(code || 0)
|
||||
})
|
||||
|
||||
hostbridge.on("exit", (code) => {
|
||||
console.log(`HostBridge exited with code ${code}`)
|
||||
coreService.kill()
|
||||
process.exit(code || 0)
|
||||
})
|
||||
|
||||
console.log("Cline gRPC Server is running!")
|
||||
console.log(`Connect to: 127.0.0.1:${PROTOBUS_PORT}`)
|
||||
console.log("Press Ctrl+C to stop")
|
||||
}
|
||||
|
||||
if (require.main === module) {
|
||||
main().catch((error) => {
|
||||
console.error("Failed to start simple Cline server:", error)
|
||||
process.exit(1)
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,159 @@
|
||||
#!/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)
|
||||
*
|
||||
* Environment Variables:
|
||||
* HOSTBRIDGE_PORT gRPC server port (default: 26040)
|
||||
* SERVER_BOOT_DELAY Server startup delay in ms (default: 3000)
|
||||
*/
|
||||
|
||||
import { ChildProcess, spawn } from "child_process"
|
||||
import fs from "fs"
|
||||
import minimist from "minimist"
|
||||
import path from "path"
|
||||
|
||||
const STANDALONE_GRPC_SERVER_PORT = process.env.STANDALONE_GRPC_SERVER_PORT || "26040"
|
||||
const SERVER_BOOT_DELAY = Number(process.env.SERVER_BOOT_DELAY) || 3000
|
||||
|
||||
let showServerLogs = false
|
||||
|
||||
function startServer(): Promise<ChildProcess> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const server = spawn("npx", ["tsx", "scripts/test-standalone-core-api-server.ts"], {
|
||||
stdio: showServerLogs ? "inherit" : "ignore",
|
||||
})
|
||||
|
||||
server.once("error", reject)
|
||||
|
||||
setTimeout(() => {
|
||||
if (server.killed) {
|
||||
reject(new Error("Server died during startup"))
|
||||
} else {
|
||||
resolve(server)
|
||||
}
|
||||
}, SERVER_BOOT_DELAY)
|
||||
})
|
||||
}
|
||||
|
||||
function stopServer(server: ChildProcess): Promise<void> {
|
||||
return new Promise((resolve) => {
|
||||
server.once("exit", () => resolve())
|
||||
server.kill("SIGINT")
|
||||
setTimeout(() => {
|
||||
if (!server.killed) {
|
||||
server.kill("SIGKILL")
|
||||
resolve()
|
||||
}
|
||||
}, 5000)
|
||||
})
|
||||
}
|
||||
|
||||
function runTestingPlatform(specFile: string): Promise<void> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const testProcess = spawn("npx", ["ts-node", "index.ts", specFile], {
|
||||
cwd: path.join(process.cwd(), "testing-platform"),
|
||||
stdio: "inherit",
|
||||
env: {
|
||||
...process.env,
|
||||
HOSTBRIDGE_PORT: STANDALONE_GRPC_SERVER_PORT,
|
||||
},
|
||||
})
|
||||
|
||||
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 = await startServer()
|
||||
try {
|
||||
await runTestingPlatform(specFile)
|
||||
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}`)
|
||||
const totalElapsed = ((Date.now() - totalStart) / 1000).toFixed(2)
|
||||
console.log(`\n🏁 All runs completed in ${totalElapsed}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"])
|
||||
|
||||
if (!inputPath) {
|
||||
console.error("Usage: npx tsx scripts/testing-platform-orchestrator.ts <spec-file-or-folder> [--count=N] [--server-logs]")
|
||||
process.exit(1)
|
||||
}
|
||||
|
||||
await runAll(inputPath, count)
|
||||
}
|
||||
|
||||
if (require.main === module) {
|
||||
main().catch((err) => {
|
||||
console.error("❌ Fatal error:", err)
|
||||
process.exit(1)
|
||||
})
|
||||
}
|
||||
+20
-16
@@ -1,19 +1,22 @@
|
||||
import * as vscode from "vscode"
|
||||
import {
|
||||
migrateCustomInstructionsToGlobalRules,
|
||||
migrateTaskHistoryToFile,
|
||||
migrateWelcomeViewCompleted,
|
||||
migrateWorkspaceToGlobalStorage,
|
||||
} from "./core/storage/state-migrations"
|
||||
import { WebviewProvider } from "./core/webview"
|
||||
import { Logger } from "./services/logging/Logger"
|
||||
import { PostHogClientProvider } from "./services/posthog/PostHogClientProvider"
|
||||
import { EmptyRequest } from "./shared/proto/cline/common"
|
||||
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 { telemetryService } from "./services/posthog/PostHogClientProvider"
|
||||
import { ErrorService } from "./services/error"
|
||||
import { featureFlagsService } from "./services/feature-flags"
|
||||
import { initializeDistinctId } from "./services/logging/distinctId"
|
||||
import { PostHogClientProvider } from "./services/posthog/PostHogClientProvider"
|
||||
import { telemetryService } from "./services/telemetry"
|
||||
import { ShowMessageType } from "./shared/proto/host/window"
|
||||
import { getLatestAnnouncementId } from "./utils/announcements"
|
||||
/**
|
||||
@@ -23,18 +26,14 @@ import { getLatestAnnouncementId } from "./utils/announcements"
|
||||
* @returns The webview provider
|
||||
*/
|
||||
export async function initialize(context: vscode.ExtensionContext): Promise<WebviewProvider> {
|
||||
// Set the distinct ID for logging and telemetry
|
||||
await initializeDistinctId(context)
|
||||
|
||||
// Initialize PostHog client provider
|
||||
let distinctId = context.globalState.get<string>("cline.distinctId")
|
||||
if (!distinctId) {
|
||||
try {
|
||||
const response = await HostProvider.env.getMachineId(EmptyRequest.create({}))
|
||||
distinctId = response.value
|
||||
} catch (e) {
|
||||
Logger.warn(`Failed to get machine ID: ${e instanceof Error ? e.message : String(e)}`)
|
||||
// PostHogProvider will fall back to uuid
|
||||
}
|
||||
}
|
||||
PostHogClientProvider.getInstance(distinctId)
|
||||
PostHogClientProvider.getInstance()
|
||||
|
||||
// Setup the ErrorService
|
||||
await ErrorService.initialize()
|
||||
|
||||
// Migrate custom instructions to global Cline rules (one-time cleanup)
|
||||
await migrateCustomInstructionsToGlobalRules(context)
|
||||
@@ -45,6 +44,9 @@ export async function initialize(context: vscode.ExtensionContext): Promise<Webv
|
||||
// Migrate workspace storage values back to global storage (reverting previous migration)
|
||||
await migrateWorkspaceToGlobalStorage(context)
|
||||
|
||||
// Ensure taskHistory.json exists and migrate legacy state (runs once)
|
||||
await migrateTaskHistoryToFile(context)
|
||||
|
||||
// Clean up orphaned file context warnings (startup cleanup)
|
||||
await FileContextTracker.cleanupOrphanedWarnings(context)
|
||||
|
||||
@@ -75,7 +77,7 @@ async function showVersionUpdateAnnouncement(context: vscode.ExtensionContext) {
|
||||
const message = previousVersion
|
||||
? `Cline has been updated to v${currentVersion}`
|
||||
: `Welcome to Cline v${currentVersion}`
|
||||
await vscode.commands.executeCommand("claude-dev.SidebarProvider.focus")
|
||||
await HostProvider.workspace.openClineSidebarPanel({})
|
||||
await new Promise((resolve) => setTimeout(resolve, 200))
|
||||
HostProvider.window.showMessage({
|
||||
type: ShowMessageType.INFORMATION,
|
||||
@@ -96,7 +98,9 @@ async function showVersionUpdateAnnouncement(context: vscode.ExtensionContext) {
|
||||
*/
|
||||
export async function tearDown(): Promise<void> {
|
||||
PostHogClientProvider.getInstance().dispose()
|
||||
|
||||
telemetryService.dispose()
|
||||
ErrorService.get().dispose()
|
||||
featureFlagsService.dispose()
|
||||
// Dispose all webview instances
|
||||
await WebviewProvider.disposeAllInstances()
|
||||
}
|
||||
|
||||
+10
-3
@@ -54,9 +54,9 @@ export interface ApiHandlerModel {
|
||||
}
|
||||
|
||||
export interface ApiProviderInfo {
|
||||
modelId: string
|
||||
providerId: string
|
||||
customPrompt?: string
|
||||
model: ApiHandlerModel
|
||||
customPrompt?: string // "compact"
|
||||
}
|
||||
|
||||
export interface SingleCompletionHandler {
|
||||
@@ -210,6 +210,7 @@ function createHandlerForProvider(
|
||||
})
|
||||
case "qwen-code":
|
||||
return new QwenCodeHandler({
|
||||
onRetryAttempt: options.onRetryAttempt,
|
||||
qwenCodeOauthPath: options.qwenCodeOauthPath,
|
||||
apiModelId: mode === "plan" ? options.planModeApiModelId : options.actModeApiModelId,
|
||||
})
|
||||
@@ -312,6 +313,7 @@ function createHandlerForProvider(
|
||||
})
|
||||
case "baseten":
|
||||
return new BasetenHandler({
|
||||
onRetryAttempt: options.onRetryAttempt,
|
||||
basetenApiKey: options.basetenApiKey,
|
||||
basetenModelId: mode === "plan" ? options.planModeBasetenModelId : options.actModeBasetenModelId,
|
||||
basetenModelInfo: mode === "plan" ? options.planModeBasetenModelInfo : options.actModeBasetenModelInfo,
|
||||
@@ -329,6 +331,8 @@ 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":
|
||||
return new ClaudeCodeHandler({
|
||||
@@ -340,6 +344,7 @@ function createHandlerForProvider(
|
||||
})
|
||||
case "huawei-cloud-maas":
|
||||
return new HuaweiCloudMaaSHandler({
|
||||
onRetryAttempt: options.onRetryAttempt,
|
||||
huaweiCloudMaasApiKey: options.huaweiCloudMaasApiKey,
|
||||
huaweiCloudMaasModelId:
|
||||
mode === "plan" ? options.planModeHuaweiCloudMaasModelId : options.actModeHuaweiCloudMaasModelId,
|
||||
@@ -357,6 +362,7 @@ function createHandlerForProvider(
|
||||
})
|
||||
case "vercel-ai-gateway":
|
||||
return new VercelAIGatewayHandler({
|
||||
onRetryAttempt: options.onRetryAttempt,
|
||||
vercelAiGatewayApiKey: options.vercelAiGatewayApiKey,
|
||||
vercelAiGatewayModelId:
|
||||
mode === "plan" ? options.planModeVercelAiGatewayModelId : options.actModeVercelAiGatewayModelId,
|
||||
@@ -365,6 +371,7 @@ function createHandlerForProvider(
|
||||
})
|
||||
case "zai":
|
||||
return new ZAiHandler({
|
||||
onRetryAttempt: options.onRetryAttempt,
|
||||
zaiApiLine: options.zaiApiLine,
|
||||
zaiApiKey: options.zaiApiKey,
|
||||
apiModelId: mode === "plan" ? options.planModeApiModelId : options.actModeApiModelId,
|
||||
@@ -394,7 +401,7 @@ export function buildApiHandler(configuration: ApiConfiguration, mode: Mode): Ap
|
||||
const handler = createHandlerForProvider(apiProvider, options, mode)
|
||||
|
||||
const modelInfo = handler.getModel().info
|
||||
if (modelInfo.maxTokens && thinkingBudgetTokens > modelInfo.maxTokens) {
|
||||
if (modelInfo?.maxTokens && modelInfo.maxTokens > 0 && thinkingBudgetTokens > modelInfo.maxTokens) {
|
||||
const clippedValue = modelInfo.maxTokens - 1
|
||||
if (mode === "plan") {
|
||||
options.planModeThinkingBudgetTokens = clippedValue
|
||||
|
||||
@@ -0,0 +1,248 @@
|
||||
import { Anthropic } from "@anthropic-ai/sdk"
|
||||
import { afterEach, beforeEach, describe, it } from "mocha"
|
||||
import sinon from "sinon"
|
||||
import "should"
|
||||
import { ClaudeCodeHandler } from "@core/api/providers/claude-code"
|
||||
|
||||
describe("ClaudeCodeHandler", () => {
|
||||
let handler: ClaudeCodeHandler
|
||||
let sandbox: sinon.SinonSandbox
|
||||
|
||||
beforeEach(() => {
|
||||
sandbox = sinon.createSandbox()
|
||||
handler = new ClaudeCodeHandler({
|
||||
claudeCodePath: "/mock/path",
|
||||
apiModelId: "claude-3-5-sonnet-20241022",
|
||||
})
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
sandbox.restore()
|
||||
})
|
||||
|
||||
describe("token counting", () => {
|
||||
it("should correctly handle token usage from assistant messages", async () => {
|
||||
// The 'input_tokens' field represents the TOTAL number of input tokens used.
|
||||
// See https://docs.anthropic.com/en/api/messages#usage-object
|
||||
|
||||
// Mock the runClaudeCode function
|
||||
const runClaudeCodeModule = await import("@/integrations/claude-code/run")
|
||||
const runClaudeCodeStub = sandbox.stub(runClaudeCodeModule, "runClaudeCode")
|
||||
|
||||
// Create a proper async generator mock for the Claude Code response
|
||||
async function* mockGenerator() {
|
||||
// First yield the system init
|
||||
yield {
|
||||
type: "system",
|
||||
subtype: "init",
|
||||
apiKeySource: "api",
|
||||
}
|
||||
|
||||
// Yield assistant message with usage data
|
||||
// Example: If base input is 70 tokens, cache read is 20, and cache creation is 10,
|
||||
// then input_tokens from Anthropic API will be 100 (70 + 20 + 10)
|
||||
yield {
|
||||
type: "assistant",
|
||||
message: {
|
||||
content: [
|
||||
{
|
||||
type: "text",
|
||||
text: "Test response",
|
||||
},
|
||||
],
|
||||
usage: {
|
||||
input_tokens: 100, // Total including cache (per Anthropic docs)
|
||||
output_tokens: 50,
|
||||
cache_read_input_tokens: 20, // Already included in input_tokens
|
||||
cache_creation_input_tokens: 10, // Already included in input_tokens
|
||||
},
|
||||
stop_reason: "end_turn",
|
||||
},
|
||||
}
|
||||
|
||||
// Yield result with cost
|
||||
yield {
|
||||
type: "result",
|
||||
result: {},
|
||||
total_cost_usd: 0.005,
|
||||
}
|
||||
}
|
||||
|
||||
runClaudeCodeStub.returns(mockGenerator() as any)
|
||||
|
||||
const systemPrompt = "You are a helpful assistant."
|
||||
const messages: Anthropic.Messages.MessageParam[] = [{ role: "user", content: "Hello" }]
|
||||
|
||||
const usageData: any[] = []
|
||||
|
||||
// Collect the results
|
||||
for await (const chunk of handler.createMessage(systemPrompt, messages)) {
|
||||
if (chunk.type === "usage") {
|
||||
usageData.push({
|
||||
inputTokens: chunk.inputTokens,
|
||||
outputTokens: chunk.outputTokens,
|
||||
cacheReadTokens: chunk.cacheReadTokens,
|
||||
cacheWriteTokens: chunk.cacheWriteTokens,
|
||||
totalCost: chunk.totalCost,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Verify token counting follows Anthropic API specification
|
||||
usageData.should.have.length(1)
|
||||
usageData[0].should.deepEqual({
|
||||
inputTokens: 100, // Total including cache tokens (per Anthropic API docs)
|
||||
outputTokens: 50,
|
||||
cacheReadTokens: 20, // Tracked separately for reporting
|
||||
cacheWriteTokens: 10, // Tracked separately for reporting
|
||||
totalCost: 0.005,
|
||||
})
|
||||
|
||||
// CRITICAL ASSERTION: Verify that input_tokens is NOT inflated by re-adding cache tokens
|
||||
// The bug would have caused inputTokens to be incorrectly calculated as 130 (100 + 20 + 10)
|
||||
// The fix ensures it remains 100, as per Anthropic's specification
|
||||
usageData[0].inputTokens.should.equal(100) // Correct: matches API response
|
||||
usageData[0].inputTokens.should.not.equal(130) // Would be wrong: double-counting cache tokens
|
||||
})
|
||||
|
||||
it("should handle missing usage fields with nullish coalescing", async () => {
|
||||
// Mock the runClaudeCode function
|
||||
const runClaudeCodeModule = await import("@/integrations/claude-code/run")
|
||||
const runClaudeCodeStub = sandbox.stub(runClaudeCodeModule, "runClaudeCode")
|
||||
|
||||
// Create a proper async generator mock with missing/undefined usage fields
|
||||
async function* mockGenerator() {
|
||||
yield {
|
||||
type: "assistant",
|
||||
message: {
|
||||
content: [
|
||||
{
|
||||
type: "text",
|
||||
text: "Test response",
|
||||
},
|
||||
],
|
||||
usage: {
|
||||
input_tokens: 100,
|
||||
output_tokens: 50,
|
||||
// cache fields are undefined/missing
|
||||
},
|
||||
stop_reason: "end_turn",
|
||||
},
|
||||
}
|
||||
|
||||
yield {
|
||||
type: "result",
|
||||
result: {},
|
||||
total_cost_usd: 0.005,
|
||||
}
|
||||
}
|
||||
|
||||
runClaudeCodeStub.returns(mockGenerator() as any)
|
||||
|
||||
const systemPrompt = "You are a helpful assistant."
|
||||
const messages: Anthropic.Messages.MessageParam[] = [{ role: "user", content: "Hello" }]
|
||||
|
||||
const usageData: any[] = []
|
||||
|
||||
// Collect the results
|
||||
for await (const chunk of handler.createMessage(systemPrompt, messages)) {
|
||||
if (chunk.type === "usage") {
|
||||
usageData.push({
|
||||
inputTokens: chunk.inputTokens,
|
||||
outputTokens: chunk.outputTokens,
|
||||
cacheReadTokens: chunk.cacheReadTokens,
|
||||
cacheWriteTokens: chunk.cacheWriteTokens,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Verify that undefined cache tokens default to 0
|
||||
usageData.should.have.length(1)
|
||||
usageData[0].should.deepEqual({
|
||||
inputTokens: 100,
|
||||
outputTokens: 50,
|
||||
cacheReadTokens: 0, // Should default to 0
|
||||
cacheWriteTokens: 0, // Should default to 0
|
||||
})
|
||||
})
|
||||
|
||||
it("should handle completely missing usage object", async () => {
|
||||
// Mock the runClaudeCode function
|
||||
const runClaudeCodeModule = await import("@/integrations/claude-code/run")
|
||||
const runClaudeCodeStub = sandbox.stub(runClaudeCodeModule, "runClaudeCode")
|
||||
|
||||
// Create a proper async generator mock with missing usage object
|
||||
async function* mockGenerator() {
|
||||
yield {
|
||||
type: "assistant",
|
||||
message: {
|
||||
content: [
|
||||
{
|
||||
type: "text",
|
||||
text: "Test response",
|
||||
},
|
||||
],
|
||||
// usage is undefined
|
||||
usage: undefined,
|
||||
stop_reason: "end_turn",
|
||||
},
|
||||
}
|
||||
|
||||
// Need to yield a result chunk to trigger usage data emission
|
||||
yield {
|
||||
type: "result",
|
||||
result: {},
|
||||
total_cost_usd: 0,
|
||||
}
|
||||
}
|
||||
|
||||
runClaudeCodeStub.returns(mockGenerator() as any)
|
||||
|
||||
const systemPrompt = "You are a helpful assistant."
|
||||
const messages: Anthropic.Messages.MessageParam[] = [{ role: "user", content: "Hello" }]
|
||||
|
||||
const usageData: any[] = []
|
||||
|
||||
// Collect the results
|
||||
for await (const chunk of handler.createMessage(systemPrompt, messages)) {
|
||||
if (chunk.type === "usage") {
|
||||
usageData.push({
|
||||
inputTokens: chunk.inputTokens,
|
||||
outputTokens: chunk.outputTokens,
|
||||
cacheReadTokens: chunk.cacheReadTokens,
|
||||
cacheWriteTokens: chunk.cacheWriteTokens,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// All token counts should default to 0 when usage is undefined
|
||||
usageData.should.have.length(1)
|
||||
usageData[0].should.deepEqual({
|
||||
inputTokens: 0,
|
||||
outputTokens: 0,
|
||||
cacheReadTokens: 0,
|
||||
cacheWriteTokens: 0,
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe("getModel", () => {
|
||||
it("should return the correct model when specified", () => {
|
||||
const handler = new ClaudeCodeHandler({
|
||||
apiModelId: "claude-3-5-sonnet-20241022",
|
||||
})
|
||||
|
||||
const model = handler.getModel()
|
||||
model.id.should.equal("claude-3-5-sonnet-20241022")
|
||||
})
|
||||
|
||||
it("should return default model when not specified", () => {
|
||||
const handler = new ClaudeCodeHandler({})
|
||||
|
||||
const model = handler.getModel()
|
||||
// The default model should be set
|
||||
model.id.should.be.type("string")
|
||||
model.info.should.be.type("object")
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,243 @@
|
||||
import Anthropic from "@anthropic-ai/sdk"
|
||||
import { LiteLlmHandler, type LiteLlmModelInfoResponse } from "@core/api/providers/litellm"
|
||||
import { convertToOpenAiMessages } from "@core/api/transform/openai-format"
|
||||
import { expect } from "chai"
|
||||
import sinon from "sinon"
|
||||
|
||||
const fakeClient = {
|
||||
chat: {
|
||||
completions: {
|
||||
create: sinon.stub(),
|
||||
},
|
||||
},
|
||||
baseURL: "fake",
|
||||
}
|
||||
|
||||
describe("LiteLlmHandler", () => {
|
||||
const originalFetch = global.fetch
|
||||
const mockFetch = sinon.stub()
|
||||
|
||||
const mockModelFetch = (modelInfo: LiteLlmModelInfoResponse["data"][number]) => {
|
||||
mockFetch.resolves({
|
||||
ok: true,
|
||||
json: () =>
|
||||
Promise.resolve({
|
||||
data: [modelInfo],
|
||||
}),
|
||||
})
|
||||
}
|
||||
|
||||
let handler: LiteLlmHandler
|
||||
|
||||
const mockHandlerChat = () => {
|
||||
sinon.stub(handler, "ensureClient" as any).returns(fakeClient)
|
||||
}
|
||||
|
||||
const initializeHandler = (model: string) => {
|
||||
handler = new LiteLlmHandler({
|
||||
liteLlmApiKey: "test-api-key",
|
||||
liteLlmBaseUrl: "http://localhost:4000",
|
||||
liteLlmUsePromptCache: true,
|
||||
liteLlmModelId: model,
|
||||
})
|
||||
|
||||
mockHandlerChat()
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
global.fetch = mockFetch
|
||||
|
||||
// Configure the stub to return a stream that closes immediately with usage data
|
||||
fakeClient.chat.completions.create.resolves(
|
||||
createAsyncIterable([
|
||||
{
|
||||
choices: [{ delta: { content: "test response" } }],
|
||||
},
|
||||
{
|
||||
choices: [{}],
|
||||
usage: {
|
||||
prompt_tokens: 100,
|
||||
completion_tokens: 50,
|
||||
cache_creation_input_tokens: 20,
|
||||
cache_read_input_tokens: 10,
|
||||
},
|
||||
},
|
||||
]),
|
||||
)
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
sinon.reset()
|
||||
|
||||
global.fetch = originalFetch
|
||||
})
|
||||
|
||||
const createAsyncIterable = (data: any[] = []) => {
|
||||
return {
|
||||
[Symbol.asyncIterator]: async function* () {
|
||||
yield* data
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
describe("prompt cache", () => {
|
||||
const setModelData = (model: string, supportsPromptCaching: boolean) => {
|
||||
mockModelFetch({
|
||||
model_name: model,
|
||||
litellm_params: {
|
||||
model,
|
||||
},
|
||||
model_info: {
|
||||
supports_prompt_caching: supportsPromptCaching,
|
||||
input_cost_per_token: 0.01,
|
||||
output_cost_per_token: 0.02,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
describe("when the model doesn't support prompt caching", () => {
|
||||
const model = "openai/gpt-5"
|
||||
|
||||
beforeEach(() => {
|
||||
initializeHandler(model)
|
||||
setModelData(model, false)
|
||||
})
|
||||
|
||||
it("sends the system prompt and messages with the openai format", async () => {
|
||||
const systemPrompt = "Test System Prompt"
|
||||
const messages: Anthropic.Messages.MessageParam[] = [
|
||||
{
|
||||
role: "user",
|
||||
content: "first message",
|
||||
},
|
||||
{
|
||||
role: "assistant",
|
||||
content: "first response",
|
||||
},
|
||||
{
|
||||
role: "user",
|
||||
content: [
|
||||
{
|
||||
type: "text",
|
||||
text: "test",
|
||||
},
|
||||
{
|
||||
type: "text",
|
||||
text: "second message",
|
||||
},
|
||||
],
|
||||
},
|
||||
]
|
||||
|
||||
for await (const _ of handler.createMessage(systemPrompt, messages)) {
|
||||
}
|
||||
|
||||
sinon.assert.calledOnce(fakeClient.chat.completions.create)
|
||||
|
||||
const callArgs = fakeClient.chat.completions.create.getCall(0).args[0]
|
||||
|
||||
const systemPromptMessage = callArgs.messages.shift()
|
||||
expect(systemPromptMessage).to.deep.equal({
|
||||
role: "system",
|
||||
content: systemPrompt,
|
||||
})
|
||||
|
||||
expect(callArgs.messages).to.deep.equal(convertToOpenAiMessages(messages))
|
||||
})
|
||||
})
|
||||
|
||||
describe("when the model supports prompt caching", () => {
|
||||
const model = "anthropic/claude-sonnet-4-20250514"
|
||||
|
||||
beforeEach(() => {
|
||||
initializeHandler(model)
|
||||
|
||||
setModelData(model, true)
|
||||
})
|
||||
|
||||
it("inserts the cache control in the system prompt and the last two user messages", async () => {
|
||||
const systemPrompt = "Test System Prompt"
|
||||
const messages: Anthropic.Messages.MessageParam[] = [
|
||||
{
|
||||
role: "user",
|
||||
content: "first message",
|
||||
},
|
||||
{
|
||||
role: "assistant",
|
||||
content: "first response",
|
||||
},
|
||||
{
|
||||
role: "user",
|
||||
content: [
|
||||
{
|
||||
type: "text",
|
||||
text: "test",
|
||||
},
|
||||
{
|
||||
type: "text",
|
||||
text: "second message",
|
||||
},
|
||||
],
|
||||
},
|
||||
]
|
||||
|
||||
for await (const _ of handler.createMessage(systemPrompt, messages)) {
|
||||
}
|
||||
|
||||
sinon.assert.calledOnce(fakeClient.chat.completions.create)
|
||||
|
||||
const callArgs = fakeClient.chat.completions.create.getCall(0).args[0]
|
||||
|
||||
expect(callArgs.messages[0]).to.deep.equal({
|
||||
role: "system",
|
||||
content: [
|
||||
{
|
||||
text: systemPrompt,
|
||||
type: "text",
|
||||
cache_control: {
|
||||
type: "ephemeral",
|
||||
},
|
||||
},
|
||||
],
|
||||
})
|
||||
|
||||
const sentMessages = callArgs.messages
|
||||
expect(sentMessages.length).to.equal(4)
|
||||
|
||||
const firstUserMessage = sentMessages[1]
|
||||
|
||||
expect(firstUserMessage).to.deep.equal({
|
||||
role: "user",
|
||||
content: [
|
||||
{
|
||||
type: "text",
|
||||
text: "first message",
|
||||
cache_control: {
|
||||
type: "ephemeral",
|
||||
},
|
||||
},
|
||||
],
|
||||
})
|
||||
|
||||
const lastUserMessage = sentMessages[3]
|
||||
expect(lastUserMessage.content[0]).to.deep.equal({
|
||||
type: "text",
|
||||
text: "test",
|
||||
})
|
||||
|
||||
const lastContentBlock = lastUserMessage.content[lastUserMessage.content.length - 1]
|
||||
expect(lastContentBlock).to.deep.equal({
|
||||
type: "text",
|
||||
text: "second message",
|
||||
cache_control: {
|
||||
type: "ephemeral",
|
||||
},
|
||||
})
|
||||
|
||||
expect(callArgs.model).to.be.a("string")
|
||||
expect(callArgs.stream).to.equal(true)
|
||||
expect(callArgs.stream_options).to.deep.equal({ include_usage: true })
|
||||
})
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -2,12 +2,12 @@ import { Anthropic } from "@anthropic-ai/sdk"
|
||||
import { BasetenModelId, basetenDefaultModelId, basetenModels, ModelInfo } from "@shared/api"
|
||||
import { calculateApiCostOpenAI } from "@utils/cost"
|
||||
import OpenAI from "openai"
|
||||
import { ApiHandler } from "../"
|
||||
import { ApiHandler, CommonApiHandlerOptions } from "../"
|
||||
import { withRetry } from "../retry"
|
||||
import { convertToOpenAiMessages } from "../transform/openai-format"
|
||||
import { ApiStream } from "../transform/stream"
|
||||
|
||||
interface BasetenHandlerOptions {
|
||||
interface BasetenHandlerOptions extends CommonApiHandlerOptions {
|
||||
basetenApiKey?: string
|
||||
basetenModelId?: string
|
||||
basetenModelInfo?: ModelInfo
|
||||
|
||||
@@ -118,10 +118,14 @@ export class ClaudeCodeHandler implements ApiHandler {
|
||||
}
|
||||
}
|
||||
|
||||
usage.inputTokens += message.usage.input_tokens
|
||||
usage.outputTokens += message.usage.output_tokens
|
||||
usage.cacheReadTokens = (usage.cacheReadTokens || 0) + (message.usage.cache_read_input_tokens || 0)
|
||||
usage.cacheWriteTokens = (usage.cacheWriteTokens || 0) + (message.usage.cache_creation_input_tokens || 0)
|
||||
// According to Anthropic's API documentation:
|
||||
// https://docs.anthropic.com/en/api/messages#usage-object
|
||||
// The `input_tokens` field already includes both `cache_read_input_tokens` and `cache_creation_input_tokens`.
|
||||
// Therefore, we should not add cache tokens to the input_tokens count again, as this would result in double-counting.
|
||||
usage.inputTokens = message.usage?.input_tokens ?? 0
|
||||
usage.outputTokens = message.usage?.output_tokens ?? 0
|
||||
usage.cacheReadTokens = message.usage?.cache_read_input_tokens ?? 0
|
||||
usage.cacheWriteTokens = message.usage?.cache_creation_input_tokens ?? 0
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
@@ -32,6 +32,7 @@ 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
|
||||
@@ -54,6 +55,31 @@ export class ClineHandler implements ApiHandler {
|
||||
"X-Task-ID": this.options.ulid || "",
|
||||
"X-Cline-Version": extensionVersion,
|
||||
},
|
||||
// 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
|
||||
},
|
||||
})
|
||||
} catch (error: any) {
|
||||
throw new Error(`Error creating Cline client: ${error.message}`)
|
||||
@@ -70,6 +96,7 @@ export class ClineHandler implements ApiHandler {
|
||||
const client = await this.ensureClient()
|
||||
|
||||
this.lastGenerationId = undefined
|
||||
this.lastRequestId = undefined
|
||||
|
||||
let didOutputUsage: boolean = false
|
||||
|
||||
@@ -92,6 +119,7 @@ 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
|
||||
}
|
||||
@@ -138,6 +166,10 @@ export class ClineHandler implements ApiHandler {
|
||||
totalCost = 0
|
||||
}
|
||||
|
||||
if (this.getModel().id === "x-ai/grok-code-fast-1") {
|
||||
totalCost = 0
|
||||
}
|
||||
|
||||
yield {
|
||||
type: "usage",
|
||||
cacheWriteTokens: 0,
|
||||
@@ -199,6 +231,11 @@ 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
|
||||
|
||||
@@ -1,16 +1,18 @@
|
||||
import type { Anthropic } from "@anthropic-ai/sdk"
|
||||
// Restore GenerateContentConfig import and add GenerateContentResponseUsageMetadata
|
||||
import { type GenerateContentConfig, type GenerateContentResponseUsageMetadata, GoogleGenAI, Part } from "@google/genai"
|
||||
import { telemetryService } from "@services/posthog/PostHogClientProvider"
|
||||
import { ApiError, type GenerateContentConfig, type GenerateContentResponseUsageMetadata, GoogleGenAI, Part } from "@google/genai"
|
||||
import { GeminiModelId, geminiDefaultModelId, geminiModels, ModelInfo } from "@shared/api"
|
||||
import { telemetryService } from "@/services/telemetry"
|
||||
import { ApiHandler, CommonApiHandlerOptions } from "../"
|
||||
import { withRetry } from "../retry"
|
||||
import { RetriableError, withRetry } from "../retry"
|
||||
import { convertAnthropicMessageToGemini } from "../transform/gemini-format"
|
||||
import { ApiStream } from "../transform/stream"
|
||||
|
||||
// Define a default TTL for the cache (e.g., 15 minutes in seconds)
|
||||
const _DEFAULT_CACHE_TTL_SECONDS = 900
|
||||
|
||||
const rateLimitPatterns = [/got status: 429/i, /429 Too Many Requests/i, /rate limit exceeded/i, /too many requests/i]
|
||||
|
||||
interface GeminiHandlerOptions extends CommonApiHandlerOptions {
|
||||
isVertex?: boolean
|
||||
vertexProjectId?: string
|
||||
@@ -222,24 +224,40 @@ export class GeminiHandler implements ApiHandler {
|
||||
if (error instanceof Error) {
|
||||
apiError = error.message
|
||||
|
||||
// Gemini doesn't include status codes in their errors
|
||||
// https://github.com/googleapis/js-genai/blob/61f7f27b866c74333ca6331883882489bcb708b9/src/_api_client.ts#L569
|
||||
const rateLimitPatterns = [
|
||||
/got status: 429/i,
|
||||
/429 Too Many Requests/i,
|
||||
/rate limit exceeded/i,
|
||||
/too many requests/i,
|
||||
]
|
||||
if (error instanceof ApiError) {
|
||||
if (error.status === 429) {
|
||||
// The API includes more details in the message
|
||||
// https://github.com/googleapis/js-genai/blob/v1.11.0/src/_api_client.ts#L758
|
||||
const response = this.attemptParse(error.message)
|
||||
|
||||
const isRateLimit =
|
||||
error.name === "ClientError" && rateLimitPatterns.some((pattern) => pattern.test(error.message))
|
||||
if (response && response.error) {
|
||||
const responseBody = this.attemptParse(response.error.message)
|
||||
|
||||
if (isRateLimit) {
|
||||
const rateLimitError = Object.assign(new Error(error.message), {
|
||||
...error,
|
||||
status: 429,
|
||||
})
|
||||
throw rateLimitError
|
||||
if (responseBody.error) {
|
||||
const detail = responseBody.error.details?.find(
|
||||
(d: any) => d["@type"] === "type.googleapis.com/google.rpc.RetryInfo",
|
||||
)
|
||||
|
||||
const detailedError = new RetriableError(
|
||||
apiError,
|
||||
this.parseRetryDelay(detail?.retryDelay) || undefined,
|
||||
{
|
||||
cause: error,
|
||||
},
|
||||
)
|
||||
throw detailedError
|
||||
}
|
||||
}
|
||||
|
||||
throw new RetriableError(apiError, undefined, { cause: error })
|
||||
}
|
||||
|
||||
// Fallback in case Gemini throws a rate limit error without a 429 status code
|
||||
// https://github.com/cline/cline/pull/5205#discussion_r2311761559
|
||||
const isRateLimit = rateLimitPatterns.some((pattern) => pattern.test(error.message))
|
||||
if (isRateLimit) {
|
||||
throw new RetriableError(apiError, undefined, { cause: error })
|
||||
}
|
||||
}
|
||||
} else {
|
||||
apiError = String(error)
|
||||
@@ -420,4 +438,35 @@ export class GeminiHandler implements ApiHandler {
|
||||
|
||||
return Math.ceil(totalChars / 4)
|
||||
}
|
||||
|
||||
private parseRetryDelay(retryAfter?: string): number {
|
||||
if (!retryAfter) {
|
||||
return 0
|
||||
}
|
||||
|
||||
const unit = retryAfter.at(-1)
|
||||
const value = parseInt(retryAfter, 10)
|
||||
|
||||
if (Number.isNaN(value)) {
|
||||
return 0
|
||||
}
|
||||
|
||||
if (unit === "s") {
|
||||
return value
|
||||
} else if (unit === "m") {
|
||||
return value * 60 // Convert minutes to seconds
|
||||
} else if (unit === "h") {
|
||||
return value * 60 * 60 // Convert hours to seconds
|
||||
}
|
||||
|
||||
return value
|
||||
}
|
||||
|
||||
private attemptParse(str: string) {
|
||||
try {
|
||||
return JSON.parse(str)
|
||||
} catch (_) {
|
||||
return null
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
import { Anthropic } from "@anthropic-ai/sdk"
|
||||
import { HuaweiCloudMaasModelId, huaweiCloudMaasDefaultModelId, huaweiCloudMaasModels, ModelInfo } from "@shared/api"
|
||||
import OpenAI from "openai"
|
||||
import { ApiHandler } from ".."
|
||||
import { ApiHandler, CommonApiHandlerOptions } from ".."
|
||||
import { withRetry } from "../retry"
|
||||
import { convertToOpenAiMessages } from "../transform/openai-format"
|
||||
import { ApiStream } from "../transform/stream"
|
||||
|
||||
interface HuaweiCloudMaaSHandlerOptions {
|
||||
interface HuaweiCloudMaaSHandlerOptions extends CommonApiHandlerOptions {
|
||||
huaweiCloudMaasApiKey?: string
|
||||
huaweiCloudMaasModelId?: string
|
||||
huaweiCloudMaasModelInfo?: ModelInfo
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
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"
|
||||
@@ -16,7 +17,7 @@ interface LiteLlmHandlerOptions extends CommonApiHandlerOptions {
|
||||
ulid?: string
|
||||
}
|
||||
|
||||
interface LiteLlmModelInfoResponse {
|
||||
export interface LiteLlmModelInfoResponse {
|
||||
data: Array<{
|
||||
model_name: string
|
||||
litellm_params: {
|
||||
@@ -28,6 +29,7 @@ interface LiteLlmModelInfoResponse {
|
||||
output_cost_per_token: number
|
||||
cache_creation_input_token_cost?: number
|
||||
cache_read_input_token_cost?: number
|
||||
supports_prompt_caching?: boolean
|
||||
[key: string]: any
|
||||
}
|
||||
}>
|
||||
@@ -61,7 +63,17 @@ export class LiteLlmHandler implements ApiHandler {
|
||||
return this.client
|
||||
}
|
||||
|
||||
private async fetchModelInfo(): Promise<LiteLlmModelInfoResponse | undefined> {
|
||||
private async modelInfo(publicModelName: string): Promise<LiteLlmModelInfoResponse["data"][number] | undefined> {
|
||||
const modelInfo = await this.fetchModelsInfo()
|
||||
|
||||
if (!modelInfo?.data) {
|
||||
return undefined
|
||||
}
|
||||
|
||||
return modelInfo.data.find((model) => model.model_name === publicModelName)
|
||||
}
|
||||
|
||||
private async fetchModelsInfo(): Promise<LiteLlmModelInfoResponse | undefined> {
|
||||
// Check if cache is still valid
|
||||
const now = Date.now()
|
||||
if (this.modelInfoCache && now - this.modelInfoCacheTimestamp < this.modelInfoCacheTTL) {
|
||||
@@ -121,19 +133,14 @@ export class LiteLlmHandler implements ApiHandler {
|
||||
cacheReadCostPerToken?: number
|
||||
}> {
|
||||
try {
|
||||
const modelInfo = await this.fetchModelInfo()
|
||||
const matchingModel = await this.modelInfo(publicModelName)
|
||||
|
||||
if (modelInfo?.data) {
|
||||
// Find the model by public name
|
||||
const matchingModel = modelInfo.data.find((model) => model.model_name === publicModelName)
|
||||
|
||||
if (matchingModel?.model_info) {
|
||||
return {
|
||||
inputCostPerToken: matchingModel.model_info.input_cost_per_token || 0,
|
||||
outputCostPerToken: matchingModel.model_info.output_cost_per_token || 0,
|
||||
cacheCreationCostPerToken: matchingModel.model_info.cache_creation_input_token_cost,
|
||||
cacheReadCostPerToken: matchingModel.model_info.cache_read_input_token_cost,
|
||||
}
|
||||
if (matchingModel) {
|
||||
return {
|
||||
inputCostPerToken: matchingModel.model_info.input_cost_per_token || 0,
|
||||
outputCostPerToken: matchingModel.model_info.output_cost_per_token || 0,
|
||||
cacheCreationCostPerToken: matchingModel.model_info.cache_creation_input_token_cost,
|
||||
cacheReadCostPerToken: matchingModel.model_info.cache_read_input_token_cost,
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
@@ -177,7 +184,7 @@ export class LiteLlmHandler implements ApiHandler {
|
||||
async *createMessage(systemPrompt: string, messages: Anthropic.Messages.MessageParam[]): ApiStream {
|
||||
const client = this.ensureClient()
|
||||
const formattedMessages = convertToOpenAiMessages(messages)
|
||||
const systemMessage: OpenAI.Chat.ChatCompletionSystemMessageParam = {
|
||||
const systemMessage: OpenAI.Chat.ChatCompletionSystemMessageParam | Anthropic.Messages.TextBlockParam = {
|
||||
role: "system",
|
||||
content: systemPrompt,
|
||||
}
|
||||
@@ -191,17 +198,26 @@ export class LiteLlmHandler implements ApiHandler {
|
||||
|
||||
let temperature: number | undefined = this.options.liteLlmModelInfo?.temperature ?? 0
|
||||
|
||||
if (isOminiModel && reasoningOn) {
|
||||
temperature = undefined // Thinking mode doesn't support temperature
|
||||
if ((isOminiModel || isAnthropicModelId(modelId)) && reasoningOn) {
|
||||
temperature = undefined // OAI omni and Anthropic extended thinking mode doesn't support temperature
|
||||
}
|
||||
|
||||
// Define cache control object if prompt caching is enabled
|
||||
const cacheControl = this.options.liteLlmUsePromptCache ? { cache_control: { type: "ephemeral" } } : undefined
|
||||
const modelInfo = await this.modelInfo(modelId)
|
||||
const cacheControl =
|
||||
this.options.liteLlmUsePromptCache && Boolean(modelInfo?.model_info.supports_prompt_caching)
|
||||
? { cache_control: { type: "ephemeral" } }
|
||||
: undefined
|
||||
|
||||
// Add cache_control to system message if enabled
|
||||
const enhancedSystemMessage = {
|
||||
...systemMessage,
|
||||
...(cacheControl && cacheControl),
|
||||
if (cacheControl) {
|
||||
// Add cache_control to system message if enabled
|
||||
// https://docs.litellm.ai/docs/providers/anthropic#caching---large-context-caching
|
||||
systemMessage.content = [
|
||||
{
|
||||
text: systemPrompt,
|
||||
type: "text",
|
||||
...cacheControl,
|
||||
},
|
||||
] as Anthropic.Messages.TextBlockParam[]
|
||||
}
|
||||
|
||||
// Find the last two user messages to apply caching
|
||||
@@ -213,19 +229,49 @@ export class LiteLlmHandler implements ApiHandler {
|
||||
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,
|
||||
// https://docs.litellm.ai/docs/providers/anthropic#caching---large-context-caching
|
||||
const enhancedMessages: OpenAI.Chat.ChatCompletionMessageParam[] = formattedMessages.map(
|
||||
(message, index): OpenAI.Chat.ChatCompletionMessageParam => {
|
||||
if ((index === lastUserMsgIndex || index === secondLastUserMsgIndex) && cacheControl) {
|
||||
// Handle both string and array content types
|
||||
if (typeof message.content === "string") {
|
||||
return {
|
||||
...message,
|
||||
content: [
|
||||
{
|
||||
type: "text",
|
||||
text: message.content,
|
||||
...cacheControl,
|
||||
},
|
||||
] as any,
|
||||
}
|
||||
} else if (Array.isArray(message.content)) {
|
||||
// Apply cache control to the last content item in the array
|
||||
return {
|
||||
...message,
|
||||
content: message.content.map((item, contentIndex) =>
|
||||
contentIndex === (message.content?.length || 0) - 1
|
||||
? {
|
||||
...item,
|
||||
...cacheControl,
|
||||
}
|
||||
: item,
|
||||
) as any,
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
...message,
|
||||
...cacheControl,
|
||||
}
|
||||
}
|
||||
}
|
||||
return message
|
||||
})
|
||||
return message
|
||||
},
|
||||
)
|
||||
|
||||
const stream = await client.chat.completions.create({
|
||||
model: this.options.liteLlmModelId || liteLlmDefaultModelId,
|
||||
messages: [enhancedSystemMessage, ...enhancedMessages],
|
||||
messages: [systemMessage, ...enhancedMessages],
|
||||
temperature,
|
||||
stream: true,
|
||||
stream_options: { include_usage: true },
|
||||
@@ -244,16 +290,16 @@ export class LiteLlmHandler implements ApiHandler {
|
||||
}
|
||||
}
|
||||
|
||||
// Handle reasoning events (thinking)
|
||||
// Thinking is not in the standard types but may be in the response
|
||||
// Handle reasoning events
|
||||
// This is not in the standard types but may be in the response
|
||||
interface ThinkingDelta {
|
||||
thinking?: string
|
||||
reasoning_content?: string
|
||||
}
|
||||
|
||||
if ((delta as ThinkingDelta)?.thinking) {
|
||||
if ((delta as ThinkingDelta)?.reasoning_content) {
|
||||
yield {
|
||||
type: "reasoning",
|
||||
reasoning: (delta as ThinkingDelta).thinking || "",
|
||||
reasoning: (delta as ThinkingDelta).reasoning_content || "",
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@ import { ModelInfo, QwenCodeModelId, qwenCodeDefaultModelId, qwenCodeModels } fr
|
||||
import OpenAI from "openai"
|
||||
import * as os from "os"
|
||||
import * as path from "path"
|
||||
import { ApiHandler } from "../"
|
||||
import { ApiHandler, CommonApiHandlerOptions } from "../"
|
||||
import { withRetry } from "../retry"
|
||||
import { convertToOpenAiMessages } from "../transform/openai-format"
|
||||
import { ApiStream } from "../transform/stream"
|
||||
@@ -24,7 +24,7 @@ interface QwenOAuthCredentials {
|
||||
resource_url?: string
|
||||
}
|
||||
|
||||
interface QwenCodeHandlerOptions {
|
||||
interface QwenCodeHandlerOptions extends CommonApiHandlerOptions {
|
||||
qwenCodeOauthPath?: string
|
||||
apiModelId?: string
|
||||
}
|
||||
|
||||
@@ -4,6 +4,7 @@ import {
|
||||
ConversationRole as BedrockConversationRole,
|
||||
type Message as BedrockMessage,
|
||||
} from "@aws-sdk/client-bedrock-runtime"
|
||||
import { ChatMessages, LlmModuleConfig, OrchestrationClient, TemplatingModuleConfig } from "@sap-ai-sdk/orchestration"
|
||||
import { ModelInfo, SapAiCoreModelId, sapAiCoreDefaultModelId, sapAiCoreModels } from "@shared/api"
|
||||
import axios from "axios"
|
||||
import OpenAI from "openai"
|
||||
@@ -18,7 +19,9 @@ interface SapAiCoreHandlerOptions extends CommonApiHandlerOptions {
|
||||
sapAiResourceGroup?: string
|
||||
sapAiCoreBaseUrl?: string
|
||||
apiModelId?: string
|
||||
sapAiCoreUseOrchestrationMode?: boolean
|
||||
thinkingBudgetTokens?: number
|
||||
deploymentId?: string
|
||||
reasoningEffort?: string
|
||||
}
|
||||
|
||||
@@ -26,6 +29,7 @@ interface Deployment {
|
||||
id: string
|
||||
name: string
|
||||
}
|
||||
|
||||
interface Token {
|
||||
access_token: string
|
||||
expires_in: number
|
||||
@@ -350,19 +354,33 @@ export class SapAiCoreHandler implements ApiHandler {
|
||||
private options: SapAiCoreHandlerOptions
|
||||
private token?: Token
|
||||
private deployments?: Deployment[]
|
||||
private isAiCoreEnvSetup: boolean = false
|
||||
|
||||
constructor(options: SapAiCoreHandlerOptions) {
|
||||
this.options = options
|
||||
}
|
||||
|
||||
private validateCredentials(): void {
|
||||
if (
|
||||
!this.options.sapAiCoreClientId ||
|
||||
!this.options.sapAiCoreClientSecret ||
|
||||
!this.options.sapAiCoreTokenUrl ||
|
||||
!this.options.sapAiCoreBaseUrl
|
||||
) {
|
||||
throw new Error("Missing required SAP AI Core credentials. Please check your configuration.")
|
||||
}
|
||||
}
|
||||
|
||||
private async authenticate(): Promise<Token> {
|
||||
this.validateCredentials()
|
||||
|
||||
const payload = {
|
||||
grant_type: "client_credentials",
|
||||
client_id: this.options.sapAiCoreClientId || "",
|
||||
client_secret: this.options.sapAiCoreClientSecret || "",
|
||||
client_id: this.options.sapAiCoreClientId,
|
||||
client_secret: this.options.sapAiCoreClientSecret,
|
||||
}
|
||||
|
||||
const tokenUrl = (this.options.sapAiCoreTokenUrl || "").replace(/\/+$/, "") + "/oauth/token"
|
||||
const tokenUrl = this.options.sapAiCoreTokenUrl!.replace(/\/+$/, "") + "/oauth/token"
|
||||
const response = await axios.post(tokenUrl, payload, {
|
||||
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
||||
})
|
||||
@@ -378,11 +396,8 @@ 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}`,
|
||||
@@ -440,6 +455,87 @@ export class SapAiCoreHandler implements ApiHandler {
|
||||
}
|
||||
|
||||
async *createMessage(systemPrompt: string, messages: Anthropic.Messages.MessageParam[]): ApiStream {
|
||||
if (this.options.sapAiCoreUseOrchestrationMode ?? true) {
|
||||
yield* this.createMessageWithOrchestration(systemPrompt, messages)
|
||||
} else {
|
||||
yield* this.createMessageWithDeployments(systemPrompt, messages)
|
||||
}
|
||||
}
|
||||
|
||||
// TODO: support credentials changes after initial setup
|
||||
private ensureAiCoreEnvSetup(): void {
|
||||
// Only set up once to avoid redundant operations
|
||||
if (this.isAiCoreEnvSetup) {
|
||||
return
|
||||
}
|
||||
|
||||
// Validate required credentials
|
||||
this.validateCredentials()
|
||||
|
||||
const aiCoreServiceCredentials = {
|
||||
clientid: this.options.sapAiCoreClientId!,
|
||||
clientsecret: this.options.sapAiCoreClientSecret!,
|
||||
url: this.options.sapAiCoreTokenUrl!,
|
||||
serviceurls: {
|
||||
AI_API_URL: this.options.sapAiCoreBaseUrl!,
|
||||
},
|
||||
}
|
||||
process.env["AICORE_SERVICE_KEY"] = JSON.stringify(aiCoreServiceCredentials)
|
||||
|
||||
// Mark as set up to avoid redundant calls
|
||||
this.isAiCoreEnvSetup = true
|
||||
}
|
||||
|
||||
private async *createMessageWithOrchestration(systemPrompt: string, messages: Anthropic.Messages.MessageParam[]): ApiStream {
|
||||
try {
|
||||
// Ensure AI Core environment variable is set up (only runs once)
|
||||
this.ensureAiCoreEnvSetup()
|
||||
const model = this.getModel()
|
||||
|
||||
// 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 = {
|
||||
template: [
|
||||
{
|
||||
role: "system",
|
||||
content: systemPrompt,
|
||||
},
|
||||
],
|
||||
}
|
||||
const orchestrationClient = new OrchestrationClient(
|
||||
{ llm, templating },
|
||||
{ resourceGroup: this.options.sapAiResourceGroup || "default" },
|
||||
)
|
||||
|
||||
const sapMessages = this.convertMessageParamToSAPMessages(messages)
|
||||
|
||||
const response = await orchestrationClient.stream({
|
||||
messages: sapMessages,
|
||||
})
|
||||
|
||||
for await (const chunk of response.stream.toContentStream()) {
|
||||
yield { type: "text", text: chunk }
|
||||
}
|
||||
|
||||
const tokenUsage = response.getTokenUsage()
|
||||
if (tokenUsage) {
|
||||
yield {
|
||||
type: "usage",
|
||||
inputTokens: tokenUsage.prompt_tokens || 0,
|
||||
outputTokens: tokenUsage.completion_tokens || 0,
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Error in SAP orchestration mode:", error)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
private async *createMessageWithDeployments(systemPrompt: string, messages: Anthropic.Messages.MessageParam[]): ApiStream {
|
||||
const token = await this.getToken()
|
||||
const headers = {
|
||||
Authorization: `Bearer ${token}`,
|
||||
@@ -449,7 +545,13 @@ export class SapAiCoreHandler implements ApiHandler {
|
||||
}
|
||||
|
||||
const model = this.getModel()
|
||||
const deploymentId = await this.getDeploymentForModel(model.id)
|
||||
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 anthropicModels = [
|
||||
"anthropic--claude-4-sonnet",
|
||||
@@ -934,4 +1036,8 @@ export class SapAiCoreHandler implements ApiHandler {
|
||||
}
|
||||
return { id: sapAiCoreDefaultModelId, info: sapAiCoreModels[sapAiCoreDefaultModelId] }
|
||||
}
|
||||
private convertMessageParamToSAPMessages(messages: Anthropic.Messages.MessageParam[]): ChatMessages {
|
||||
// Use the existing OpenAI converter since the logic is identical
|
||||
return convertToOpenAiMessages(messages) as ChatMessages
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
import { Anthropic } from "@anthropic-ai/sdk"
|
||||
import { ModelInfo, vercelAiGatewayDefaultModelId, vercelAiGatewayDefaultModelInfo } from "@shared/api"
|
||||
import OpenAI from "openai"
|
||||
import { ApiHandler } from "../index"
|
||||
import { ApiHandler, CommonApiHandlerOptions } from "../index"
|
||||
import { withRetry } from "../retry"
|
||||
import { ApiStream } from "../transform/stream"
|
||||
import { createVercelAIGatewayStream } from "../transform/vercel-ai-gateway-stream"
|
||||
|
||||
interface VercelAIGatewayHandlerOptions {
|
||||
interface VercelAIGatewayHandlerOptions extends CommonApiHandlerOptions {
|
||||
vercelAiGatewayApiKey?: string
|
||||
vercelAiGatewayModelId?: string
|
||||
vercelAiGatewayModelInfo?: ModelInfo
|
||||
|
||||
@@ -10,12 +10,12 @@ import {
|
||||
} from "@shared/api"
|
||||
import OpenAI from "openai"
|
||||
import { version as extensionVersion } from "../../../../package.json"
|
||||
import { ApiHandler } from ".."
|
||||
import { ApiHandler, CommonApiHandlerOptions } from ".."
|
||||
import { withRetry } from "../retry"
|
||||
import { convertToOpenAiMessages } from "../transform/openai-format"
|
||||
import { ApiStream } from "../transform/stream"
|
||||
|
||||
interface ZAiHandlerOptions {
|
||||
interface ZAiHandlerOptions extends CommonApiHandlerOptions {
|
||||
zaiApiLine?: string
|
||||
zaiApiKey?: string
|
||||
apiModelId?: string
|
||||
|
||||
+15
-2
@@ -12,6 +12,18 @@ const DEFAULT_OPTIONS: Required<RetryOptions> = {
|
||||
retryAllErrors: false,
|
||||
}
|
||||
|
||||
export class RetriableError extends Error {
|
||||
status: number = 429
|
||||
retryAfter?: number
|
||||
|
||||
constructor(message: string, retryAfter?: number, options?: ErrorOptions) {
|
||||
super(message, options)
|
||||
this.name = "RetriableError"
|
||||
|
||||
this.retryAfter = retryAfter
|
||||
}
|
||||
}
|
||||
|
||||
export function withRetry(options: RetryOptions = {}) {
|
||||
const { maxRetries, baseDelay, maxDelay, retryAllErrors } = { ...DEFAULT_OPTIONS, ...options }
|
||||
|
||||
@@ -24,7 +36,7 @@ export function withRetry(options: RetryOptions = {}) {
|
||||
yield* originalMethod.apply(this, args)
|
||||
return
|
||||
} catch (error: any) {
|
||||
const isRateLimit = error?.status === 429
|
||||
const isRateLimit = error?.status === 429 || error instanceof RetriableError
|
||||
const isLastAttempt = attempt === maxRetries - 1
|
||||
|
||||
if ((!isRateLimit && !retryAllErrors) || isLastAttempt) {
|
||||
@@ -36,7 +48,8 @@ export function withRetry(options: RetryOptions = {}) {
|
||||
const retryAfter =
|
||||
error.headers?.["retry-after"] ||
|
||||
error.headers?.["x-ratelimit-reset"] ||
|
||||
error.headers?.["ratelimit-reset"]
|
||||
error.headers?.["ratelimit-reset"] ||
|
||||
error.retryAfter
|
||||
|
||||
let delay: number
|
||||
if (retryAfter) {
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import { Anthropic } from "@anthropic-ai/sdk"
|
||||
import { CLAUDE_SONNET_4_1M_SUFFIX, ModelInfo, openRouterClaudeSonnet41mModelId } from "@shared/api"
|
||||
import OpenAI from "openai"
|
||||
import { isGPT5ModelFamily } from "../../prompts/system-prompt/utils"
|
||||
import { convertToOpenAiMessages } from "./openai-format"
|
||||
import { convertToR1Format } from "./r1-format"
|
||||
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { ClineDefaultTool } from "@shared/tools"
|
||||
export type AssistantMessageContent = TextContent | ToolUse
|
||||
|
||||
export { parseAssistantMessageV2 } from "./parse-assistant-message"
|
||||
@@ -8,32 +9,6 @@ export interface TextContent {
|
||||
partial: boolean
|
||||
}
|
||||
|
||||
export const toolUseNames = [
|
||||
"execute_command",
|
||||
"read_file",
|
||||
"write_to_file",
|
||||
"replace_in_file",
|
||||
"search_files",
|
||||
"list_files",
|
||||
"list_code_definition_names",
|
||||
"browser_action",
|
||||
"use_mcp_tool",
|
||||
"access_mcp_resource",
|
||||
"ask_followup_question",
|
||||
"plan_mode_respond",
|
||||
"load_mcp_documentation",
|
||||
"attempt_completion",
|
||||
"new_task",
|
||||
"condense",
|
||||
"summarize_task",
|
||||
"report_bug",
|
||||
"new_rule",
|
||||
"web_fetch",
|
||||
] as const
|
||||
|
||||
// Converts array of tool call names into a union type ("execute_command" | "read_file" | ...)
|
||||
export type ToolUseName = (typeof toolUseNames)[number]
|
||||
|
||||
export const toolParamNames = [
|
||||
"command",
|
||||
"requires_approval",
|
||||
@@ -69,7 +44,7 @@ export type ToolParamName = (typeof toolParamNames)[number]
|
||||
|
||||
export interface ToolUse {
|
||||
type: "tool_use"
|
||||
name: ToolUseName
|
||||
name: ClineDefaultTool // id of the tool being used
|
||||
// params is a partial record, allowing only some or none of the possible parameters to be used
|
||||
params: Partial<Record<ToolParamName, string>>
|
||||
partial: boolean
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { AssistantMessageContent, TextContent, ToolParamName, ToolUse, ToolUseName, toolParamNames, toolUseNames } from "." // Assuming types are defined in index.ts or a similar file
|
||||
import { ClineDefaultTool, toolUseNames } from "@shared/tools"
|
||||
import { AssistantMessageContent, TextContent, ToolParamName, ToolUse, toolParamNames } from "." // Assuming types are defined in index.ts or a similar file
|
||||
|
||||
// parseAssistantmessageV1 removed in https://github.com/cline/cline/pull/5425
|
||||
|
||||
@@ -33,7 +34,7 @@ export function parseAssistantMessageV2(assistantMessage: string): AssistantMess
|
||||
let currentParamName: ToolParamName | undefined
|
||||
|
||||
// Precompute tags for faster lookups
|
||||
const toolUseOpenTags = new Map<string, ToolUseName>()
|
||||
const toolUseOpenTags = new Map<string, ClineDefaultTool>()
|
||||
const toolParamOpenTags = new Map<string, ToolParamName>()
|
||||
for (const name of toolUseNames) {
|
||||
toolUseOpenTags.set(`<${name}>`, name)
|
||||
|
||||
@@ -1,10 +1,9 @@
|
||||
import { getTaskMetadata, saveTaskMetadata } from "@core/storage/disk"
|
||||
import { getTaskMetadata, readTaskHistoryFromState, saveTaskMetadata } from "@core/storage/disk"
|
||||
import type { ClineMessage } from "@shared/ExtensionMessage"
|
||||
import chokidar, { FSWatcher } from "chokidar"
|
||||
import * as path from "path"
|
||||
import * as vscode from "vscode"
|
||||
import { Controller } from "@/core/controller"
|
||||
import { HistoryItem } from "@/shared/HistoryItem"
|
||||
import { getCwd } from "@/utils/path"
|
||||
import type { FileMetadataEntry } from "./ContextTrackerTypes"
|
||||
|
||||
@@ -286,8 +285,7 @@ export class FileContextTracker {
|
||||
static async cleanupOrphanedWarnings(context: vscode.ExtensionContext): Promise<void> {
|
||||
const startTime = Date.now()
|
||||
try {
|
||||
// eslint-disable-next-line eslint-rules/no-direct-vscode-state-api
|
||||
const taskHistory = (context.globalState.get("taskHistory") as HistoryItem[]) || []
|
||||
const taskHistory = await readTaskHistoryFromState(context)
|
||||
const existingTaskIds = new Set(taskHistory.map((task) => task.id))
|
||||
const allStateKeys = context.workspaceState.keys()
|
||||
const pendingWarningKeys = allStateKeys.filter((key) => key.startsWith("pendingFileContextWarning_"))
|
||||
@@ -312,7 +310,7 @@ export class FileContextTracker {
|
||||
`FileContextTracker: Processed ${existingTaskIds.size} tasks, found ${pendingWarningKeys.length} pending warnings, ${orphanedPendingContextTasks.length} orphaned, deleted ${orphanedPendingContextTasks.length}, took ${duration}ms`,
|
||||
)
|
||||
} catch (error) {
|
||||
console.error("Error cleaning up orphaned file context warnings:", error)
|
||||
console.error("[FileContextTracker] Error cleaning up orphaned file context warnings:", error)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,62 +0,0 @@
|
||||
import { UpdateBrowserSettingsRequest } from "@shared/proto/cline/browser"
|
||||
import { Boolean } from "@shared/proto/cline/common"
|
||||
import { DEFAULT_BROWSER_SETTINGS, BrowserSettings as SharedBrowserSettings } from "../../../shared/BrowserSettings"
|
||||
import { Controller } from "../index"
|
||||
|
||||
/**
|
||||
* Update browser settings
|
||||
* @param controller The controller instance
|
||||
* @param request The browser settings request message
|
||||
* @returns Success response
|
||||
*/
|
||||
export async function updateBrowserSettings(controller: Controller, request: UpdateBrowserSettingsRequest): Promise<Boolean> {
|
||||
try {
|
||||
// Get current browser settings to preserve fields not in the request
|
||||
const currentSettings = controller.stateManager.getGlobalStateKey("browserSettings")
|
||||
const mergedWithDefaults = { ...DEFAULT_BROWSER_SETTINGS, ...currentSettings }
|
||||
|
||||
// Convert from protobuf format to shared format, merging with existing settings
|
||||
const newBrowserSettings: SharedBrowserSettings = {
|
||||
...mergedWithDefaults, // Start with existing settings (and defaults)
|
||||
viewport: {
|
||||
// Apply updates from request
|
||||
width: request.viewport?.width || mergedWithDefaults.viewport.width,
|
||||
height: request.viewport?.height || mergedWithDefaults.viewport.height,
|
||||
},
|
||||
// Explicitly handle optional boolean and string fields from the request
|
||||
remoteBrowserEnabled:
|
||||
request.remoteBrowserEnabled === undefined
|
||||
? mergedWithDefaults.remoteBrowserEnabled
|
||||
: request.remoteBrowserEnabled,
|
||||
remoteBrowserHost:
|
||||
request.remoteBrowserHost === undefined ? mergedWithDefaults.remoteBrowserHost : request.remoteBrowserHost,
|
||||
chromeExecutablePath:
|
||||
// If chromeExecutablePath is explicitly in the request (even as ""), use it.
|
||||
// Otherwise, fall back to mergedWithDefaults.
|
||||
"chromeExecutablePath" in request ? request.chromeExecutablePath : mergedWithDefaults.chromeExecutablePath,
|
||||
disableToolUse: request.disableToolUse === undefined ? mergedWithDefaults.disableToolUse : request.disableToolUse,
|
||||
customArgs: "customArgs" in request ? request.customArgs : mergedWithDefaults.customArgs,
|
||||
}
|
||||
|
||||
// Update global state with new settings
|
||||
controller.stateManager.setGlobalState("browserSettings", newBrowserSettings)
|
||||
|
||||
// Update task browser settings if task exists
|
||||
if (controller.task) {
|
||||
controller.task.browserSettings = newBrowserSettings
|
||||
controller.task.browserSession.browserSettings = newBrowserSettings
|
||||
}
|
||||
|
||||
// Post updated state to webview
|
||||
await controller.postStateToWebview()
|
||||
|
||||
return Boolean.create({
|
||||
value: true,
|
||||
})
|
||||
} catch (error) {
|
||||
console.error("Error updating browser settings:", error)
|
||||
return Boolean.create({
|
||||
value: false,
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -3,7 +3,7 @@ import { Controller } from ".."
|
||||
|
||||
export async function checkpointDiff(controller: Controller, request: Int64Request): Promise<Empty> {
|
||||
if (request.value) {
|
||||
await controller.task?.presentMultifileDiff(request.value, false)
|
||||
await controller.task?.checkpointManager?.presentMultifileDiff?.(request.value, false)
|
||||
}
|
||||
return Empty
|
||||
return Empty.create()
|
||||
}
|
||||
|
||||
@@ -23,7 +23,11 @@ export async function checkpointRestore(controller: Controller, request: Checkpo
|
||||
})
|
||||
|
||||
// NOTE: cancelTask awaits abortTask, which awaits diffViewProvider.revertChanges, which reverts any edited files, allowing us to reset to a checkpoint rather than running into a state where the revertChanges function is called alongside or after the checkpoint reset
|
||||
await controller.task?.restoreCheckpoint(request.number, request.restoreType as ClineCheckpointRestore, request.offset)
|
||||
await controller.task?.checkpointManager?.restoreCheckpoint(
|
||||
request.number,
|
||||
request.restoreType as ClineCheckpointRestore,
|
||||
request.offset,
|
||||
)
|
||||
}
|
||||
return Empty.create({})
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { getFileMentionFromPath } from "@/core/mentions"
|
||||
import { WebviewProvider } from "@/core/webview"
|
||||
import { singleFileDiagnosticsToProblemsString } from "@/integrations/diagnostics"
|
||||
import { telemetryService } from "@/services/posthog/PostHogClientProvider"
|
||||
import { telemetryService } from "@/services/telemetry"
|
||||
import { CommandContext, Empty } from "@/shared/proto/index.cline"
|
||||
import { Controller } from "../index"
|
||||
import { sendAddToInputEventToClient } from "../ui/subscribeToAddToInput"
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { getFileMentionFromPath } from "@/core/mentions"
|
||||
import { HostProvider } from "@/hosts/host-provider"
|
||||
import { telemetryService } from "@/services/posthog/PostHogClientProvider"
|
||||
import { telemetryService } from "@/services/telemetry"
|
||||
import { CommandContext, Empty } from "@/shared/proto/index.cline"
|
||||
import { ShowMessageType } from "@/shared/proto/index.host"
|
||||
import { Controller } from "../index"
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { getFileMentionFromPath } from "@/core/mentions"
|
||||
import { singleFileDiagnosticsToProblemsString } from "@/integrations/diagnostics"
|
||||
import { telemetryService } from "@/services/posthog/PostHogClientProvider"
|
||||
import { telemetryService } from "@/services/telemetry"
|
||||
import { CommandContext, Empty } from "@/shared/proto/index.cline"
|
||||
import { Controller } from "../index"
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { getFileMentionFromPath } from "@/core/mentions"
|
||||
import { HostProvider } from "@/hosts/host-provider"
|
||||
import { telemetryService } from "@/services/posthog/PostHogClientProvider"
|
||||
import { telemetryService } from "@/services/telemetry"
|
||||
import { CommandContext, Empty } from "@/shared/proto/index.cline"
|
||||
import { ShowMessageType } from "@/shared/proto/index.host"
|
||||
import { Controller } from "../index"
|
||||
|
||||
@@ -1,35 +0,0 @@
|
||||
import { telemetryService } from "@services/posthog/PostHogClientProvider"
|
||||
import { RecordingResult } from "@shared/proto/cline/dictation"
|
||||
import { audioRecordingService } from "@/services/dictation/AudioRecordingService"
|
||||
import { Controller } from ".."
|
||||
|
||||
/**
|
||||
* Cancels audio recording without saving or transcribing the audio
|
||||
* @param controller The controller instance
|
||||
* @returns RecordingResult indicating success or failure
|
||||
*/
|
||||
export const cancelRecording = async (controller: Controller): Promise<RecordingResult> => {
|
||||
const taskId = controller.task?.taskId
|
||||
const recordingStatus = audioRecordingService.getRecordingStatus()
|
||||
const recordingDuration = recordingStatus.durationSeconds * 1000 // Convert to milliseconds
|
||||
|
||||
try {
|
||||
const result = await audioRecordingService.cancelRecording()
|
||||
|
||||
telemetryService.captureVoiceRecordingStopped(taskId, recordingDuration, false, process.platform)
|
||||
|
||||
return RecordingResult.create({
|
||||
success: result.success,
|
||||
error: result.error || "",
|
||||
})
|
||||
} catch (error) {
|
||||
console.error("Error canceling recording:", error)
|
||||
|
||||
telemetryService.captureVoiceRecordingStopped(taskId, recordingDuration, false, process.platform)
|
||||
|
||||
return RecordingResult.create({
|
||||
success: false,
|
||||
error: error instanceof Error ? error.message : "Unknown error occurred",
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1,25 +0,0 @@
|
||||
import { RecordingStatus } from "@shared/proto/cline/dictation"
|
||||
import { audioRecordingService } from "@/services/dictation/AudioRecordingService"
|
||||
|
||||
/**
|
||||
* Gets the current recording status
|
||||
* @returns RecordingStatus with current status
|
||||
*/
|
||||
export const getRecordingStatus = async (): Promise<RecordingStatus> => {
|
||||
try {
|
||||
const status = audioRecordingService.getRecordingStatus()
|
||||
|
||||
return RecordingStatus.create({
|
||||
isRecording: status.isRecording,
|
||||
durationSeconds: status.durationSeconds,
|
||||
error: status.error || "",
|
||||
})
|
||||
} catch (error) {
|
||||
console.error("Error getting recording status:", error)
|
||||
return RecordingStatus.create({
|
||||
isRecording: false,
|
||||
durationSeconds: 0,
|
||||
error: error instanceof Error ? error.message : "Unknown error occurred",
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1,52 +0,0 @@
|
||||
import { RecordingResult } from "@shared/proto/cline/dictation"
|
||||
import { HostProvider } from "@/hosts/host-provider"
|
||||
import { audioRecordingService } from "@/services/dictation/AudioRecordingService"
|
||||
import { telemetryService } from "@/services/posthog/PostHogClientProvider"
|
||||
import { ShowMessageType } from "@/shared/proto/host/window"
|
||||
import { Controller } from ".."
|
||||
|
||||
/**
|
||||
* Starts audio recording using the Extension Host
|
||||
* @param controller The controller instance
|
||||
* @returns RecordingResult with success status
|
||||
*/
|
||||
export const startRecording = async (controller: Controller): Promise<RecordingResult> => {
|
||||
const taskId = controller.task?.taskId
|
||||
|
||||
try {
|
||||
const userInfo = controller.authService.getInfo()
|
||||
if (!userInfo?.user?.uid) {
|
||||
throw new Error("Please sign in to your Cline Account to use Dictation.")
|
||||
}
|
||||
|
||||
const result = await audioRecordingService.startRecording()
|
||||
|
||||
if (result.success) {
|
||||
telemetryService.captureVoiceRecordingStarted(taskId, process.platform)
|
||||
}
|
||||
|
||||
return RecordingResult.create({
|
||||
success: result.success,
|
||||
error: result.error || "",
|
||||
})
|
||||
} catch (error) {
|
||||
console.error("Error starting recording:", error)
|
||||
const errorMessage = error instanceof Error ? error.message : "Unknown error occurred"
|
||||
|
||||
const signInAction = "Sign in to Cline"
|
||||
const action = await HostProvider.window.showMessage({
|
||||
type: ShowMessageType.ERROR,
|
||||
message: `Voice recording error: ${errorMessage}`,
|
||||
options: { items: [signInAction] },
|
||||
})
|
||||
|
||||
if (action.selectedOption === signInAction) {
|
||||
await controller.authService.createAuthRequest()
|
||||
}
|
||||
|
||||
return RecordingResult.create({
|
||||
success: false,
|
||||
error: errorMessage,
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1,37 +0,0 @@
|
||||
import { telemetryService } from "@services/posthog/PostHogClientProvider"
|
||||
import { RecordedAudio } from "@shared/proto/cline/dictation"
|
||||
import { audioRecordingService } from "@/services/dictation/AudioRecordingService"
|
||||
import { Controller } from ".."
|
||||
|
||||
/**
|
||||
* Stops audio recording and returns the recorded audio
|
||||
* @param controller The controller instance
|
||||
* @returns RecordedAudio with audio data
|
||||
*/
|
||||
export const stopRecording = async (controller: Controller): Promise<RecordedAudio> => {
|
||||
const taskId = controller.task?.taskId
|
||||
const recordingStatus = audioRecordingService.getRecordingStatus()
|
||||
const recordingDuration = recordingStatus.durationSeconds * 1000 // Convert to milliseconds
|
||||
|
||||
try {
|
||||
const result = await audioRecordingService.stopRecording()
|
||||
|
||||
telemetryService.captureVoiceRecordingStopped(taskId, recordingDuration, result.success, process.platform)
|
||||
|
||||
return RecordedAudio.create({
|
||||
success: result.success,
|
||||
audioBase64: result.audioBase64 || "",
|
||||
error: result.error || "",
|
||||
})
|
||||
} catch (error) {
|
||||
console.error("Error stopping recording:", error)
|
||||
|
||||
telemetryService.captureVoiceRecordingStopped(taskId, recordingDuration, false, process.platform)
|
||||
|
||||
return RecordedAudio.create({
|
||||
success: false,
|
||||
audioBase64: "",
|
||||
error: error instanceof Error ? error.message : "Unknown error occurred",
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1,77 +0,0 @@
|
||||
import { telemetryService } from "@services/posthog/PostHogClientProvider"
|
||||
import { TranscribeAudioRequest, Transcription } from "@shared/proto/cline/dictation"
|
||||
import { HostProvider } from "@/hosts/host-provider"
|
||||
import { voiceTranscriptionService } from "@/services/dictation/VoiceTranscriptionService"
|
||||
import { ShowMessageType } from "@/shared/proto/host/window"
|
||||
import { Controller } from ".."
|
||||
|
||||
/**
|
||||
* Transcribes audio using Cline transcription service
|
||||
* @param controller The controller instance
|
||||
* @param request TranscribeAudioRequest containing base64 audio data
|
||||
* @returns Transcription with transcribed text or error
|
||||
*/
|
||||
export const transcribeAudio = async (controller: Controller, request: TranscribeAudioRequest): Promise<Transcription> => {
|
||||
const taskId = controller.task?.taskId
|
||||
const startTime = Date.now()
|
||||
|
||||
// Capture telemetry for transcription start
|
||||
telemetryService.captureVoiceTranscriptionStarted(taskId, request.language || "en")
|
||||
|
||||
try {
|
||||
// Transcribe the audio
|
||||
const result = await voiceTranscriptionService.transcribeAudio(request.audioBase64, request.language || "en")
|
||||
const durationMs = Date.now() - startTime
|
||||
|
||||
if (result.error) {
|
||||
let errorType = "api_error"
|
||||
if (result.error.includes("Authentication failed")) {
|
||||
errorType = "invalid_jwt_token"
|
||||
} else if (result.error.includes("Insufficient credits")) {
|
||||
errorType = "insufficient_credits"
|
||||
} else if (result.error.includes("Invalid audio format")) {
|
||||
errorType = "invalid_audio_format"
|
||||
} else if (result.error.includes("Cannot connect")) {
|
||||
errorType = "connection_error"
|
||||
} else if (result.error.includes("Network error")) {
|
||||
errorType = "network_error"
|
||||
}
|
||||
|
||||
telemetryService.captureVoiceTranscriptionError(taskId, errorType, result.error, durationMs)
|
||||
|
||||
let errorMessage = ""
|
||||
if (result.error.includes("Authentication failed")) {
|
||||
errorMessage = "Authentication failed. Please log in again."
|
||||
} else if (result.error.includes("Insufficient credits")) {
|
||||
errorMessage = "Insufficient credits for transcription service."
|
||||
} else if (result.error.includes("Cannot connect")) {
|
||||
errorMessage = "Cannot connect to transcription service."
|
||||
} else {
|
||||
errorMessage = `Voice transcription failed: ${result.error}`
|
||||
}
|
||||
|
||||
HostProvider.window.showMessage({
|
||||
type: ShowMessageType.ERROR,
|
||||
message: errorMessage,
|
||||
})
|
||||
} else if (result.text) {
|
||||
telemetryService.captureVoiceTranscriptionCompleted(taskId, result.text.length, durationMs, request.language || "en")
|
||||
}
|
||||
|
||||
return Transcription.create({
|
||||
text: result.text || "",
|
||||
error: result.error || "",
|
||||
})
|
||||
} catch (error) {
|
||||
console.error("Error transcribing audio:", error)
|
||||
const durationMs = Date.now() - startTime
|
||||
const errorMessage = error instanceof Error ? error.message : "Unknown error occurred"
|
||||
|
||||
telemetryService.captureVoiceTranscriptionError(taskId, "unexpected_error", errorMessage, durationMs)
|
||||
|
||||
return Transcription.create({
|
||||
text: "",
|
||||
error: errorMessage,
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
import { refreshClineRulesToggles } from "@core/context/instructions/user-instructions/cline-rules"
|
||||
import { createRuleFile as createRuleFileImpl } from "@core/context/instructions/user-instructions/rule-helpers"
|
||||
import { getWorkspaceBasename } from "@core/workspace"
|
||||
import { RuleFile, RuleFileRequest } from "@shared/proto/cline/file"
|
||||
import * as path from "path"
|
||||
import { refreshWorkflowToggles } from "@/core/context/instructions/user-instructions/workflows"
|
||||
import { HostProvider } from "@/hosts/host-provider"
|
||||
import { ShowMessageType } from "@/shared/proto/host/window"
|
||||
@@ -68,7 +68,7 @@ export async function createRuleFile(controller: Controller, request: RuleFileRe
|
||||
|
||||
return RuleFile.create({
|
||||
filePath: filePath,
|
||||
displayName: path.basename(filePath),
|
||||
displayName: getWorkspaceBasename(filePath, "Controller.createRuleFile"),
|
||||
alreadyExists: fileExists,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { deleteRuleFile as deleteRuleFileImpl } from "@core/context/instructions/user-instructions/rule-helpers"
|
||||
import { getWorkspaceBasename } from "@core/workspace"
|
||||
import { RuleFile, RuleFileRequest } from "@shared/proto/cline/file"
|
||||
import * as path from "path"
|
||||
import { HostProvider } from "@/hosts/host-provider"
|
||||
import { ShowMessageType } from "@/shared/proto/host/window"
|
||||
import { Controller } from ".."
|
||||
@@ -40,7 +40,7 @@ export async function deleteRuleFile(controller: Controller, request: RuleFileRe
|
||||
//await refreshWorkflowToggles(controller.context, cwd)
|
||||
await controller.postStateToWebview()
|
||||
|
||||
const fileName = path.basename(request.rulePath)
|
||||
const fileName = getWorkspaceBasename(request.rulePath, "Controller.deleteRuleFile")
|
||||
|
||||
const fileTypeName = request.type === "workflow" ? "workflow" : "rule"
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { workspaceResolver } from "@core/workspace"
|
||||
import { BooleanResponse, StringRequest } from "@shared/proto/cline/common"
|
||||
import { getWorkspacePath } from "@utils/path"
|
||||
import * as fs from "fs"
|
||||
import * as path from "path"
|
||||
import { Controller } from ".."
|
||||
|
||||
/**
|
||||
@@ -25,7 +25,12 @@ export async function ifFileExistsRelativePath(_controller: Controller, request:
|
||||
}
|
||||
|
||||
// Resolve the relative path to absolute path
|
||||
const absolutePath = path.resolve(workspacePath, request.value)
|
||||
const resolvedPath = workspaceResolver.resolveWorkspacePath(
|
||||
workspacePath,
|
||||
request.value,
|
||||
"Controller.ifFileExistsRelativePath",
|
||||
)
|
||||
const absolutePath = typeof resolvedPath === "string" ? resolvedPath : resolvedPath.absolutePath
|
||||
// Check if the file exists
|
||||
try {
|
||||
return BooleanResponse.create({ value: fs.statSync(absolutePath).isFile() })
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { workspaceResolver } from "@core/workspace"
|
||||
import { openFile as openFileIntegration } from "@integrations/misc/open-file"
|
||||
import { Empty, StringRequest } from "@shared/proto/cline/common"
|
||||
import { getWorkspacePath } from "@utils/path"
|
||||
import * as path from "path"
|
||||
import { Controller } from ".."
|
||||
|
||||
/**
|
||||
@@ -20,7 +20,12 @@ export async function openFileRelativePath(_controller: Controller, request: Str
|
||||
|
||||
if (request.value) {
|
||||
// Resolve the relative path to absolute path
|
||||
const absolutePath = path.resolve(workspacePath, request.value)
|
||||
const resolvedPath = workspaceResolver.resolveWorkspacePath(
|
||||
workspacePath,
|
||||
request.value,
|
||||
"Controller.openFileRelativePath",
|
||||
)
|
||||
const absolutePath = typeof resolvedPath === "string" ? resolvedPath : resolvedPath.absolutePath
|
||||
|
||||
// Open the file using the existing integration
|
||||
openFileIntegration(absolutePath)
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { openFile as openFileIntegration } from "@integrations/misc/open-file"
|
||||
import { telemetryService } from "../../../services/posthog/PostHogClientProvider"
|
||||
import { telemetryService } from "../../../services/telemetry"
|
||||
import { Empty, StringRequest } from "../../../shared/proto/cline/common"
|
||||
import { ensureFocusChainFile, extractFocusChainListFromText } from "../../task/focus-chain/file-utils"
|
||||
import { Controller } from ".."
|
||||
|
||||
@@ -1,8 +1,7 @@
|
||||
import { searchWorkspaceFiles } from "@services/search/file-search"
|
||||
import { FileSearchRequest, FileSearchResults, FileSearchType } from "@shared/proto/cline/file"
|
||||
import { SearchWorkspaceItemsRequest_SearchItemType } from "@shared/proto/host/workspace"
|
||||
import { convertSearchResultsToProtoFileInfos } from "@shared/proto-conversions/file/search-result-conversion"
|
||||
import { getWorkspacePath } from "@utils/path"
|
||||
import { HostProvider } from "@/hosts/host-provider"
|
||||
import { Controller } from ".."
|
||||
|
||||
/**
|
||||
@@ -17,47 +16,36 @@ export async function searchFiles(_controller: Controller, request: FileSearchRe
|
||||
if (!workspacePath) {
|
||||
// Handle case where workspace path is not available
|
||||
console.error("Error in searchFiles: No workspace path available")
|
||||
return FileSearchResults.create({
|
||||
results: [],
|
||||
mentionsRequestId: request.mentionsRequestId,
|
||||
})
|
||||
return { results: [], mentionsRequestId: request.mentionsRequestId }
|
||||
}
|
||||
|
||||
try {
|
||||
// Map enum to host SearchItemType (0 = FILE, 1 = FOLDER)
|
||||
const selectedTypeValue: SearchWorkspaceItemsRequest_SearchItemType | undefined =
|
||||
request.selectedType === FileSearchType.FILE
|
||||
? SearchWorkspaceItemsRequest_SearchItemType.FILE
|
||||
: request.selectedType === FileSearchType.FOLDER
|
||||
? SearchWorkspaceItemsRequest_SearchItemType.FOLDER
|
||||
: undefined
|
||||
// Map enum to string for the search service
|
||||
let selectedTypeString: "file" | "folder" | undefined
|
||||
if (request.selectedType === FileSearchType.FILE) {
|
||||
selectedTypeString = "file"
|
||||
} else if (request.selectedType === FileSearchType.FOLDER) {
|
||||
selectedTypeString = "folder"
|
||||
}
|
||||
|
||||
// Use host-provided search via hostbridge (no fallback)
|
||||
const hostResponse = await HostProvider.workspace.searchWorkspaceItems({
|
||||
query: request.query || "",
|
||||
limit: request.limit || 20,
|
||||
selectedType: selectedTypeValue,
|
||||
})
|
||||
|
||||
const mapped: { path: string; type: "file" | "folder"; label?: string }[] = (hostResponse.items || []).map(
|
||||
(item: { path?: string; type: SearchWorkspaceItemsRequest_SearchItemType; label?: string }) => ({
|
||||
path: String(item.path || ""),
|
||||
type: item.type === SearchWorkspaceItemsRequest_SearchItemType.FOLDER ? "folder" : "file",
|
||||
label: item.label || undefined,
|
||||
}),
|
||||
// Call file search service with query from request
|
||||
const searchResults = await searchWorkspaceFiles(
|
||||
request.query || "",
|
||||
workspacePath,
|
||||
request.limit || 20, // Use default limit of 20 if not specified
|
||||
selectedTypeString,
|
||||
)
|
||||
|
||||
const protoResults = convertSearchResultsToProtoFileInfos(mapped)
|
||||
// Convert search results to proto FileInfo objects using the conversion function
|
||||
const protoResults = convertSearchResultsToProtoFileInfos(searchResults)
|
||||
|
||||
return FileSearchResults.create({
|
||||
results: protoResults,
|
||||
mentionsRequestId: request.mentionsRequestId,
|
||||
})
|
||||
// Return successful results
|
||||
return { results: protoResults, mentionsRequestId: request.mentionsRequestId }
|
||||
} catch (error) {
|
||||
console.error("Error in host searchWorkspaceItems:", error instanceof Error ? error.message : String(error))
|
||||
return FileSearchResults.create({
|
||||
results: [],
|
||||
mentionsRequestId: request.mentionsRequestId,
|
||||
})
|
||||
// Log the error but don't include it in the response, following the pattern in searchCommits
|
||||
console.error("Error in searchFiles:", error)
|
||||
|
||||
// Return empty results without error message
|
||||
return { results: [], mentionsRequestId: request.mentionsRequestId }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import path from "node:path"
|
||||
import { telemetryService } from "@services/posthog/PostHogClientProvider"
|
||||
import { getWorkspaceBasename } from "@core/workspace"
|
||||
import type { ToggleClineRuleRequest } from "@shared/proto/cline/file"
|
||||
import { ToggleClineRules } from "@shared/proto/cline/file"
|
||||
import { telemetryService } from "@/services/telemetry"
|
||||
import type { Controller } from "../index"
|
||||
|
||||
/**
|
||||
@@ -36,14 +36,7 @@ export async function toggleClineRule(controller: Controller, request: ToggleCli
|
||||
// Track rule toggle telemetry with current task context
|
||||
if (controller.task?.ulid) {
|
||||
// Extract just the filename for privacy (no full paths)
|
||||
const ruleFileName = path.basename(rulePath)
|
||||
telemetryService.captureClineRuleToggled(controller.task.ulid, ruleFileName, enabled, isGlobal)
|
||||
}
|
||||
|
||||
// Track rule toggle telemetry with current task context
|
||||
if (controller.task?.ulid) {
|
||||
// Extract just the filename for privacy (no full paths)
|
||||
const ruleFileName = path.basename(rulePath)
|
||||
const ruleFileName = getWorkspaceBasename(rulePath, "Controller.toggleClineRule")
|
||||
telemetryService.captureClineRuleToggled(controller.task.ulid, ruleFileName, enabled, isGlobal)
|
||||
}
|
||||
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
import { ClineRulesToggles as AppClineRulesToggles } from "@shared/cline-rules"
|
||||
import type { ToggleWindsurfRuleRequest } from "@shared/proto/cline/file"
|
||||
import { ClineRulesToggles } from "@shared/proto/cline/file"
|
||||
import type { Controller } from "../index"
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
import { Controller } from "@core/controller/index"
|
||||
import { serviceHandlers } from "@generated/hosts/vscode/protobus-services"
|
||||
import { GrpcRecorderBuilder } from "@/core/controller/grpc-recorder/grpc-recorder.builder"
|
||||
import { GrpcRequestRegistry } from "@/core/controller/grpc-request-registry"
|
||||
import { ExtensionMessage } from "@/shared/ExtensionMessage"
|
||||
import { GrpcCancel, GrpcRequest } from "@/shared/WebviewMessage"
|
||||
import { GrpcRequestRegistry } from "./grpc-request-registry"
|
||||
import { Controller } from "./index"
|
||||
|
||||
/**
|
||||
* Type definition for a streaming response handler
|
||||
@@ -15,6 +16,36 @@ export type StreamingResponseHandler<TResponse> = (
|
||||
|
||||
export type PostMessageToWebview = (message: ExtensionMessage) => Thenable<boolean | undefined>
|
||||
|
||||
/**
|
||||
* Creates a middleware wrapper for recording gRPC requests and responses
|
||||
*/
|
||||
function withRecordingMiddleware(postMessage: PostMessageToWebview, controller: Controller): PostMessageToWebview {
|
||||
return async (response: ExtensionMessage) => {
|
||||
if (response?.grpc_response) {
|
||||
try {
|
||||
GrpcRecorderBuilder.getRecorder(controller).recordResponse(
|
||||
response.grpc_response.request_id,
|
||||
response.grpc_response,
|
||||
)
|
||||
} catch (e) {
|
||||
console.warn("Failed to record gRPC response:", e)
|
||||
}
|
||||
}
|
||||
return postMessage(response)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Records gRPC request with error handling
|
||||
*/
|
||||
function recordRequest(request: GrpcRequest, controller: Controller): void {
|
||||
try {
|
||||
GrpcRecorderBuilder.getRecorder(controller).recordRequest(request)
|
||||
} catch (e) {
|
||||
console.warn("Failed to record gRPC request:", e)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Handles a gRPC request from the webview.
|
||||
*/
|
||||
@@ -23,10 +54,15 @@ export async function handleGrpcRequest(
|
||||
postMessageToWebview: PostMessageToWebview,
|
||||
request: GrpcRequest,
|
||||
): Promise<void> {
|
||||
recordRequest(request, controller)
|
||||
|
||||
// Create recording middleware wrapper
|
||||
const postMessageWithRecording = withRecordingMiddleware(postMessageToWebview, controller)
|
||||
|
||||
if (request.is_streaming) {
|
||||
await handleStreamingRequest(controller, postMessageToWebview, request)
|
||||
await handleStreamingRequest(controller, postMessageWithRecording, request)
|
||||
} else {
|
||||
await handleUnaryRequest(controller, postMessageToWebview, request)
|
||||
await handleUnaryRequest(controller, postMessageWithRecording, request)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
import { describe, it } from "mocha"
|
||||
import "should"
|
||||
import { GrpcRecorderNoops } from "@/core/controller/grpc-recorder/grpc-recorder"
|
||||
import { GrpcRecorderBuilder } from "@/core/controller/grpc-recorder/grpc-recorder.builder"
|
||||
import { LogFileHandler } from "@/core/controller/grpc-recorder/log-file-handler"
|
||||
|
||||
describe("GrpcRecorderBuilder", () => {
|
||||
describe("when not enabling", () => {
|
||||
it("should return GrpcRecorderNoops when enableIf is false", () => {
|
||||
const builder = new GrpcRecorderBuilder()
|
||||
const recorder = builder.enableIf(false).build()
|
||||
|
||||
recorder.should.be.instanceOf(GrpcRecorderNoops)
|
||||
})
|
||||
|
||||
it("should return GrpcRecorderNoops when enableIf is false even with log file handler", () => {
|
||||
const builder = new GrpcRecorderBuilder()
|
||||
const logFileHandler = new LogFileHandler()
|
||||
const recorder = builder.withLogFileHandler(logFileHandler).enableIf(false).build()
|
||||
|
||||
recorder.should.be.instanceOf(GrpcRecorderNoops)
|
||||
})
|
||||
})
|
||||
|
||||
describe("GrpcRecorderNoops functionality", () => {
|
||||
it("should have no-op methods that don't throw errors", () => {
|
||||
const recorder = new GrpcRecorderNoops()
|
||||
|
||||
recorder.recordRequest({
|
||||
request_id: "test-id",
|
||||
service: "TestService",
|
||||
method: "testMethod",
|
||||
message: {},
|
||||
is_streaming: false,
|
||||
})
|
||||
|
||||
recorder.recordResponse("test-id", {
|
||||
request_id: "test-id",
|
||||
message: {},
|
||||
})
|
||||
|
||||
recorder.recordError("test-id", "test error")
|
||||
|
||||
const sessionLog = recorder.getSessionLog()
|
||||
sessionLog.should.have.property("startTime").which.is.a.String()
|
||||
sessionLog.should.have.property("entries").which.is.an.Array()
|
||||
sessionLog.entries.should.have.length(0)
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,102 @@
|
||||
import { GrpcPostRecordHook, GrpcRequestFilter } from "@core/controller/grpc-recorder/types"
|
||||
import { Controller } from "@/core/controller"
|
||||
import { GrpcRecorder, GrpcRecorderNoops, IRecorder } from "@/core/controller/grpc-recorder/grpc-recorder"
|
||||
import { LogFileHandler, LogFileHandlerNoops } from "@/core/controller/grpc-recorder/log-file-handler"
|
||||
import { testHooks } from "@/core/controller/grpc-recorder/test-hooks"
|
||||
|
||||
/**
|
||||
* A builder class for constructing a gRPC recorder instance.
|
||||
*
|
||||
* This class follows the Builder pattern, allowing consumers
|
||||
* to configure logging behavior and control whether recording
|
||||
* is enabled or disabled before creating a final `IRecorder`.
|
||||
*/
|
||||
export class GrpcRecorderBuilder {
|
||||
private fileHandler: LogFileHandler | null = null
|
||||
private enabled: boolean = true
|
||||
private filters: GrpcRequestFilter[] = []
|
||||
private hooks: GrpcPostRecordHook[] = []
|
||||
|
||||
public withLogFileHandler(handler: LogFileHandler): this {
|
||||
this.fileHandler = handler
|
||||
return this
|
||||
}
|
||||
|
||||
public enableIf(condition: boolean): this {
|
||||
this.enabled = condition
|
||||
return this
|
||||
}
|
||||
|
||||
public withFilters(...filters: GrpcRequestFilter[]): this {
|
||||
this.filters.push(...filters)
|
||||
return this
|
||||
}
|
||||
|
||||
public withPostRecordHooks(...hooks: GrpcPostRecordHook[]): this {
|
||||
this.hooks.push(...hooks)
|
||||
return this
|
||||
}
|
||||
|
||||
// Initialize the recorder as a singleton
|
||||
private static recorder: IRecorder
|
||||
|
||||
/**
|
||||
* Gets or creates the GrpcRecorder instance
|
||||
*/
|
||||
static getRecorder(controller: Controller): IRecorder {
|
||||
if (!GrpcRecorderBuilder.recorder) {
|
||||
GrpcRecorderBuilder.recorder = GrpcRecorder.builder()
|
||||
.enableIf(process.env.GRPC_RECORDER_ENABLED === "true" && process.env.CLINE_ENVIRONMENT === "local")
|
||||
.withLogFileHandler(new LogFileHandler())
|
||||
.build(controller)
|
||||
}
|
||||
return GrpcRecorderBuilder.recorder
|
||||
}
|
||||
|
||||
public build(controller?: Controller): IRecorder {
|
||||
if (!this.enabled) {
|
||||
return new GrpcRecorderNoops()
|
||||
}
|
||||
|
||||
let filters: GrpcRequestFilter[] = filtersFromEnv()
|
||||
if (this.filters.length > 0) {
|
||||
filters = filters.concat(this.filters)
|
||||
}
|
||||
|
||||
let hooks: GrpcPostRecordHook[] = hooksFromEnv(controller)
|
||||
if (this.hooks.length > 0) {
|
||||
hooks = hooks.concat(this.hooks)
|
||||
}
|
||||
|
||||
const handler = this.fileHandler ?? new LogFileHandlerNoops()
|
||||
return new GrpcRecorder(handler, filters, hooks)
|
||||
}
|
||||
}
|
||||
|
||||
function filtersFromEnv(): GrpcRequestFilter[] {
|
||||
const filters: GrpcRequestFilter[] = []
|
||||
|
||||
if (process.env.GRPC_RECORDER_TESTS_FILTERS_ENABLED === "true") {
|
||||
filters.push(...testFilters())
|
||||
}
|
||||
|
||||
return filters
|
||||
}
|
||||
|
||||
function testFilters(): GrpcRequestFilter[] {
|
||||
/*
|
||||
* Ignores streaming messages and unwanted services messages
|
||||
* that record more than expected.
|
||||
*/
|
||||
return [(req) => req.is_streaming, (req) => ["cline.UiService", "cline.McpService", "cline.WebService"].includes(req.service)]
|
||||
}
|
||||
|
||||
function hooksFromEnv(controller?: Controller): GrpcPostRecordHook[] {
|
||||
const hooks: GrpcPostRecordHook[] = []
|
||||
|
||||
if (controller && process.env.GRPC_RECORDER_TESTS_FILTERS_ENABLED === "true") {
|
||||
hooks.push(...testHooks(controller))
|
||||
}
|
||||
|
||||
return hooks
|
||||
}
|
||||
@@ -0,0 +1,214 @@
|
||||
import { GrpcRecorder, IRecorder } from "@core/controller/grpc-recorder/grpc-recorder"
|
||||
import { expect } from "chai"
|
||||
import { ExtensionMessage } from "@/shared/ExtensionMessage"
|
||||
import { GrpcRequest } from "@/shared/WebviewMessage"
|
||||
|
||||
describe("grpc-recorder", () => {
|
||||
let recorder: IRecorder
|
||||
|
||||
before(async () => {
|
||||
recorder = GrpcRecorder.builder()
|
||||
.withFilters((req: GrpcRequest) => req.service === "the-unwanted-service")
|
||||
.enableIf(true)
|
||||
.build()
|
||||
})
|
||||
|
||||
describe("GrpcRecorder", () => {
|
||||
it("matches multiple request, response and stats", async () => {
|
||||
interface UseCase {
|
||||
request: GrpcRequest
|
||||
response: ExtensionMessage["grpc_response"]
|
||||
expectedStatus: string
|
||||
}
|
||||
const requestResponseUseCases: UseCase[] = [
|
||||
{
|
||||
request: {
|
||||
service: "the-service",
|
||||
method: "the-method",
|
||||
message: "the-message",
|
||||
request_id: "request-id-1",
|
||||
is_streaming: false,
|
||||
},
|
||||
response: {
|
||||
request_id: "request-id-1",
|
||||
message: "the-message-response",
|
||||
error: "",
|
||||
},
|
||||
expectedStatus: "completed",
|
||||
},
|
||||
{
|
||||
request: {
|
||||
service: "streaming-service",
|
||||
method: "stream-method",
|
||||
message: { data: "streaming-data", count: 42 },
|
||||
request_id: "request-id-2",
|
||||
is_streaming: true,
|
||||
},
|
||||
response: {
|
||||
request_id: "request-id-2",
|
||||
message: { streamData: "chunk-1" },
|
||||
error: "",
|
||||
is_streaming: true,
|
||||
sequence_number: 1,
|
||||
},
|
||||
expectedStatus: "completed",
|
||||
},
|
||||
{
|
||||
request: {
|
||||
service: "another-service",
|
||||
method: "another-method",
|
||||
message: { complex: { nested: "object", array: [1, 2, 3] } },
|
||||
request_id: "request-id-3",
|
||||
is_streaming: false,
|
||||
},
|
||||
response: {
|
||||
request_id: "request-id-3",
|
||||
message: "",
|
||||
error: "Something went wrong",
|
||||
},
|
||||
expectedStatus: "error",
|
||||
},
|
||||
]
|
||||
|
||||
const initialExpectedStatus = "pending"
|
||||
|
||||
requestResponseUseCases.forEach((us: UseCase, index: number) => {
|
||||
recorder.recordRequest(us.request)
|
||||
|
||||
let sessionLog = recorder.getSessionLog()
|
||||
expect(sessionLog.entries).length(index + 1, `unexpected request_id: ${us.request.request_id}`)
|
||||
|
||||
expect(sessionLog.entries[index]).to.include({
|
||||
service: us.request.service,
|
||||
method: us.request.method,
|
||||
isStreaming: us.request.is_streaming,
|
||||
requestId: us.request.request_id,
|
||||
status: initialExpectedStatus,
|
||||
})
|
||||
|
||||
if (us.response) {
|
||||
recorder.recordResponse(us.request.request_id, us.response)
|
||||
}
|
||||
sessionLog = recorder.getSessionLog()
|
||||
|
||||
expect(sessionLog.entries[index].status).equal(us.expectedStatus)
|
||||
expect(sessionLog.entries[index].response).to.deep.include({
|
||||
error: us.response?.error,
|
||||
})
|
||||
})
|
||||
|
||||
const sessionLog = recorder.getSessionLog()
|
||||
expect(sessionLog.stats).to.include({
|
||||
totalRequests: 3,
|
||||
pendingRequests: 0,
|
||||
completedRequests: 2,
|
||||
errorRequests: 1,
|
||||
})
|
||||
|
||||
recorder.recordRequest({
|
||||
service: "the-unwanted-service",
|
||||
method: "the-method",
|
||||
message: "the-message",
|
||||
request_id: "request-id-1",
|
||||
is_streaming: false,
|
||||
})
|
||||
|
||||
expect(sessionLog.entries).length(3)
|
||||
})
|
||||
|
||||
it("using default filtering should filter out unwanted requests", async () => {
|
||||
const customRecorder = GrpcRecorder.builder()
|
||||
.withFilters(
|
||||
(req) => req.is_streaming,
|
||||
(req) => ["cline.UiService", "cline.McpService", "cline.WebService"].includes(req.service),
|
||||
)
|
||||
.enableIf(true)
|
||||
.build()
|
||||
const unwantedServices = ["cline.UiService", "cline.McpService", "cline.WebService"]
|
||||
unwantedServices.forEach((us) => {
|
||||
customRecorder.recordRequest({
|
||||
service: us,
|
||||
method: "the-method",
|
||||
message: "the-message",
|
||||
request_id: "request-id-1",
|
||||
is_streaming: false,
|
||||
})
|
||||
})
|
||||
let sessionLog = customRecorder.getSessionLog()
|
||||
expect(sessionLog.entries).length(0)
|
||||
customRecorder.recordRequest({
|
||||
service: "streaming-request",
|
||||
method: "the-method",
|
||||
message: "the-message",
|
||||
request_id: "request-id-1",
|
||||
is_streaming: true,
|
||||
})
|
||||
sessionLog = customRecorder.getSessionLog()
|
||||
expect(sessionLog.entries).length(0)
|
||||
})
|
||||
|
||||
it("cleanupSyntheticEntries removes synthetic entries from session log", async () => {
|
||||
const testRecorder = GrpcRecorder.builder().enableIf(true).build()
|
||||
|
||||
// Add regular request
|
||||
testRecorder.recordRequest({
|
||||
service: "regular-service",
|
||||
method: "regular-method",
|
||||
message: "regular-message",
|
||||
request_id: "regular-id",
|
||||
is_streaming: false,
|
||||
})
|
||||
|
||||
// Add synthetic request
|
||||
testRecorder.recordRequest(
|
||||
{
|
||||
service: "synthetic-service",
|
||||
method: "synthetic-method",
|
||||
message: "synthetic-message",
|
||||
request_id: "synthetic-id",
|
||||
is_streaming: false,
|
||||
},
|
||||
true, // synthetic = true
|
||||
)
|
||||
|
||||
let sessionLog = testRecorder.getSessionLog()
|
||||
expect(sessionLog.entries).length(2)
|
||||
|
||||
testRecorder.cleanupSyntheticEntries()
|
||||
|
||||
sessionLog = testRecorder.getSessionLog()
|
||||
expect(sessionLog.entries).length(1)
|
||||
expect(sessionLog.entries[0].requestId).equal("regular-id")
|
||||
})
|
||||
|
||||
it("recordResponse executes post-record hooks", async () => {
|
||||
let hookExecuted = false
|
||||
let hookEntry: any = null
|
||||
|
||||
const mockHook = async (entry: any) => {
|
||||
hookExecuted = true
|
||||
hookEntry = entry
|
||||
}
|
||||
|
||||
const testRecorder = GrpcRecorder.builder().withPostRecordHooks(mockHook).enableIf(true).build()
|
||||
|
||||
testRecorder.recordRequest({
|
||||
service: "test-service",
|
||||
method: "test-method",
|
||||
message: "test-message",
|
||||
request_id: "test-id",
|
||||
is_streaming: false,
|
||||
})
|
||||
|
||||
testRecorder.recordResponse("test-id", {
|
||||
request_id: "test-id",
|
||||
message: "response-message",
|
||||
error: "",
|
||||
})
|
||||
|
||||
expect(hookExecuted).to.be.true
|
||||
expect(hookEntry).to.not.be.null
|
||||
expect(hookEntry.requestId).equal("test-id")
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,225 @@
|
||||
import { GrpcResponse } from "@shared/ExtensionMessage"
|
||||
import { GrpcRequest } from "@shared/WebviewMessage"
|
||||
import { GrpcRecorderBuilder } from "@/core/controller/grpc-recorder/grpc-recorder.builder"
|
||||
import { ILogFileHandler } from "@/core/controller/grpc-recorder/log-file-handler"
|
||||
import {
|
||||
GrpcLogEntry,
|
||||
GrpcPostRecordHook,
|
||||
GrpcRequestFilter,
|
||||
GrpcSessionLog,
|
||||
SessionStats,
|
||||
} from "@/core/controller/grpc-recorder/types"
|
||||
|
||||
export class GrpcRecorderNoops implements IRecorder {
|
||||
recordRequest(_request: GrpcRequest): void {}
|
||||
recordResponse(_requestId: string, _response: GrpcResponse): void {}
|
||||
recordError(_requestId: string, _error: string): void {}
|
||||
getSessionLog(): GrpcSessionLog {
|
||||
return {
|
||||
startTime: "",
|
||||
entries: [],
|
||||
}
|
||||
}
|
||||
cleanupSyntheticEntries(): void {}
|
||||
}
|
||||
|
||||
export interface IRecorder {
|
||||
recordRequest(request: GrpcRequest, synthetic?: boolean): void
|
||||
recordResponse(requestId: string, response: GrpcResponse): void
|
||||
recordError(requestId: string, error: string): void
|
||||
getSessionLog(): GrpcSessionLog
|
||||
cleanupSyntheticEntries(): void
|
||||
}
|
||||
|
||||
/**
|
||||
* Default implementation of a gRPC recorder.
|
||||
*
|
||||
* Responsibilities:
|
||||
* - Records requests, responses, and errors.
|
||||
* - Tracks request/response lifecycle, including duration and status.
|
||||
* - Maintains a session log of all recorded entries.
|
||||
* - Persists logs asynchronously through a file handler.
|
||||
*/
|
||||
export class GrpcRecorder implements IRecorder {
|
||||
private sessionLog: GrpcSessionLog
|
||||
private pendingRequests: Map<string, { entry: GrpcLogEntry; startTime: number }> = new Map()
|
||||
|
||||
constructor(
|
||||
private fileHandler: ILogFileHandler,
|
||||
private requestFilters: GrpcRequestFilter[] = [],
|
||||
private postRecordHooks: GrpcPostRecordHook[] = [],
|
||||
) {
|
||||
this.sessionLog = {
|
||||
startTime: new Date().toISOString(),
|
||||
entries: [],
|
||||
}
|
||||
|
||||
this.fileHandler.initialize(this.sessionLog).catch((error) => {
|
||||
console.error("Failed to initialize gRPC log file:", error)
|
||||
})
|
||||
}
|
||||
|
||||
public static builder(): GrpcRecorderBuilder {
|
||||
return new GrpcRecorderBuilder()
|
||||
}
|
||||
|
||||
/**
|
||||
* Records a gRPC request.
|
||||
*
|
||||
* - Stores the request as a "pending" log entry.
|
||||
* - Tracks the request start time for later duration calculation.
|
||||
* - Persists the log asynchronously.
|
||||
*
|
||||
* @param request - The incoming gRPC request.
|
||||
*/
|
||||
public recordRequest(request: GrpcRequest, synthetic: boolean = false): void {
|
||||
if (this.shouldFilter(request)) {
|
||||
return
|
||||
}
|
||||
|
||||
const entry: GrpcLogEntry = {
|
||||
requestId: request.request_id,
|
||||
service: request.service,
|
||||
method: request.method,
|
||||
isStreaming: request.is_streaming || false,
|
||||
request: {
|
||||
message: request.message,
|
||||
},
|
||||
status: "pending",
|
||||
meta: { synthetic },
|
||||
}
|
||||
|
||||
this.pendingRequests.set(request.request_id, {
|
||||
entry,
|
||||
startTime: Date.now(),
|
||||
})
|
||||
|
||||
this.sessionLog.entries.push(entry)
|
||||
this.flushLogAsync()
|
||||
}
|
||||
|
||||
public getSessionLog(): GrpcSessionLog {
|
||||
return this.sessionLog
|
||||
}
|
||||
|
||||
/**
|
||||
* Records a gRPC response for a given request.
|
||||
*
|
||||
* - Looks up the pending request entry.
|
||||
* - Updates the entry with response data, status, and duration.
|
||||
* - Removes the request from pending if it's not streaming.
|
||||
* - Recomputes session stats.
|
||||
* - Persists the log asynchronously.
|
||||
*
|
||||
* @param requestId - The ID of the request being responded to.
|
||||
* @param response - The corresponding gRPC response.
|
||||
*/
|
||||
public recordResponse(requestId: string, response: GrpcResponse): void {
|
||||
const pendingRequest = this.pendingRequests.get(requestId)
|
||||
|
||||
if (!pendingRequest) {
|
||||
console.warn(`No pending request found for response with ID: ${requestId}`)
|
||||
return
|
||||
}
|
||||
|
||||
const { entry, startTime } = pendingRequest
|
||||
|
||||
entry.response = {
|
||||
message: response?.message ? response.message : undefined,
|
||||
error: response?.error,
|
||||
isStreaming: response?.is_streaming,
|
||||
sequenceNumber: response?.sequence_number,
|
||||
}
|
||||
|
||||
entry.duration = Date.now() - startTime
|
||||
entry.status = response?.error ? "error" : "completed"
|
||||
|
||||
if (!response?.is_streaming) {
|
||||
this.pendingRequests.delete(requestId)
|
||||
}
|
||||
|
||||
this.sessionLog.stats = this.getStats()
|
||||
|
||||
this.flushLogAsync()
|
||||
|
||||
this.runHooks(entry).catch((e) => console.error("Post-record hook failed:", e))
|
||||
}
|
||||
|
||||
private async runHooks(entry: GrpcLogEntry): Promise<void> {
|
||||
if (entry.meta?.synthetic) return
|
||||
for (const hook of this.postRecordHooks) {
|
||||
await hook(entry)
|
||||
}
|
||||
}
|
||||
|
||||
public cleanupSyntheticEntries(): void {
|
||||
// Remove synthetic entries from session log
|
||||
this.sessionLog.entries = this.sessionLog.entries.filter((entry) => !entry.meta?.synthetic)
|
||||
|
||||
// clean up from pending requests if needed
|
||||
for (const [requestId, pendingRequest] of this.pendingRequests.entries()) {
|
||||
if (pendingRequest.entry.meta?.synthetic) {
|
||||
this.pendingRequests.delete(requestId)
|
||||
}
|
||||
}
|
||||
|
||||
this.sessionLog.stats = this.getStats()
|
||||
this.flushLogAsync()
|
||||
}
|
||||
|
||||
/**
|
||||
* Records an error for a given request.
|
||||
*
|
||||
* - Marks the request as failed.
|
||||
* - Records the error message and request duration.
|
||||
* - Removes it from the pending requests.
|
||||
* - Persists the log asynchronously.
|
||||
*
|
||||
* @param requestId - The ID of the request that errored.
|
||||
* @param error - Error message.
|
||||
*/
|
||||
public recordError(requestId: string, error: string): void {
|
||||
const pendingRequest = this.pendingRequests.get(requestId)
|
||||
if (!pendingRequest) {
|
||||
console.warn(`No pending request found for error with ID: ${requestId}`)
|
||||
return
|
||||
}
|
||||
|
||||
const { entry, startTime } = pendingRequest
|
||||
|
||||
entry.response = {
|
||||
error: error,
|
||||
}
|
||||
entry.duration = Date.now() - startTime
|
||||
entry.status = "error"
|
||||
|
||||
this.pendingRequests.delete(requestId)
|
||||
this.flushLogAsync()
|
||||
}
|
||||
|
||||
private flushLogAsync(): void {
|
||||
setImmediate(() => {
|
||||
this.fileHandler.write(this.sessionLog).catch((error) => {
|
||||
console.error("Failed to flush gRPC log:", error)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
public getStats(): SessionStats {
|
||||
const totalRequests = this.sessionLog.entries.length
|
||||
const pendingRequests = this.sessionLog.entries.filter((e) => e.status === "pending").length
|
||||
const completedRequests = this.sessionLog.entries.filter((e) => e.status === "completed").length
|
||||
const errorRequests = this.sessionLog.entries.filter((e) => e.status === "error").length
|
||||
|
||||
return {
|
||||
totalRequests,
|
||||
pendingRequests,
|
||||
completedRequests,
|
||||
errorRequests,
|
||||
}
|
||||
}
|
||||
|
||||
private shouldFilter(request: GrpcRequest): boolean {
|
||||
return this.requestFilters.some((filter) => filter(request))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
import { expect } from "chai"
|
||||
import { before, describe, it } from "mocha"
|
||||
import { LogFileHandler } from "@/core/controller/grpc-recorder/log-file-handler"
|
||||
|
||||
describe("log-file-handler", () => {
|
||||
let logHandler: LogFileHandler
|
||||
|
||||
before(async () => {
|
||||
logHandler = new LogFileHandler()
|
||||
expect(logHandler.getFilePath()).not.empty
|
||||
})
|
||||
|
||||
describe("LogFileHandler", () => {
|
||||
it("returns file name with timestamp when env var not set", () => {
|
||||
const result = logHandler.getFileName()
|
||||
expect(result).to.contains("grpc_recorded_session")
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,57 @@
|
||||
import { writeFile } from "@utils/fs"
|
||||
import fs from "fs/promises"
|
||||
import * as path from "path"
|
||||
import { GrpcSessionLog } from "@/core/controller/grpc-recorder/types"
|
||||
|
||||
const LOG_FILE_PREFIX = "grpc_recorded_session"
|
||||
|
||||
export class LogFileHandlerNoops implements ILogFileHandler {
|
||||
async initialize(_initialData: GrpcSessionLog): Promise<void> {}
|
||||
async write(_sessionLog: GrpcSessionLog): Promise<void> {}
|
||||
}
|
||||
|
||||
export interface ILogFileHandler {
|
||||
initialize(initialData: GrpcSessionLog): Promise<void>
|
||||
write(sessionLog: GrpcSessionLog): Promise<void>
|
||||
}
|
||||
|
||||
/**
|
||||
* Default implementation of `ILogFileHandler` that persists logs to disk.
|
||||
*
|
||||
* - Creates a log file inside the workspace `tests/specs` folder.
|
||||
* - Uses a timestamped filename by default, unless overridden by an env var.
|
||||
* - Saves logs in JSON format.
|
||||
*/
|
||||
export class LogFileHandler implements ILogFileHandler {
|
||||
private logFilePath: string
|
||||
|
||||
constructor() {
|
||||
const fileName = this.getFileName()
|
||||
const workspaceFolder = process.env.DEV_WORKSPACE_FOLDER ?? process.cwd()
|
||||
const folderPath = path.join(workspaceFolder, "tests", "specs")
|
||||
this.logFilePath = path.join(folderPath, fileName)
|
||||
}
|
||||
|
||||
public getFilePath(): string {
|
||||
return this.logFilePath
|
||||
}
|
||||
|
||||
public getFileName(): string {
|
||||
const envFileName = path.basename(process.env.GRPC_RECORDER_FILE_NAME || "").replace(/[^a-zA-Z0-9-_]/g, "_")
|
||||
if (envFileName && envFileName.trim().length > 0) {
|
||||
return `${LOG_FILE_PREFIX}_${envFileName}.json`
|
||||
}
|
||||
|
||||
const timestamp = new Date().toISOString().replace(/[:.]/g, "-")
|
||||
return `${LOG_FILE_PREFIX}_${timestamp}.json`
|
||||
}
|
||||
|
||||
public async initialize(initialData: GrpcSessionLog): Promise<void> {
|
||||
await fs.mkdir(path.dirname(this.logFilePath), { recursive: true })
|
||||
await writeFile(this.logFilePath, JSON.stringify(initialData, null, 2), "utf8")
|
||||
}
|
||||
|
||||
public async write(sessionLog: GrpcSessionLog): Promise<void> {
|
||||
await writeFile(this.logFilePath, JSON.stringify(sessionLog, null, 2), "utf8")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
import { afterEach, beforeEach, describe, it } from "mocha"
|
||||
import "should"
|
||||
import * as sinon from "sinon"
|
||||
import { Controller } from ".."
|
||||
import { IRecorder } from "./grpc-recorder"
|
||||
import { GrpcRecorderBuilder } from "./grpc-recorder.builder"
|
||||
import { testHooks } from "./test-hooks"
|
||||
import { GrpcLogEntry } from "./types"
|
||||
|
||||
describe("test-hooks", () => {
|
||||
let cleanupSyntheticEntriesStub: sinon.SinonStub
|
||||
let recordRequestStub: sinon.SinonStub
|
||||
let recordResponseStub: sinon.SinonStub
|
||||
let getRecorderStub: sinon.SinonStub
|
||||
|
||||
beforeEach(() => {
|
||||
cleanupSyntheticEntriesStub = sinon.stub()
|
||||
recordRequestStub = sinon.stub()
|
||||
recordResponseStub = sinon.stub()
|
||||
|
||||
const mockRecorder: IRecorder = {
|
||||
cleanupSyntheticEntries: cleanupSyntheticEntriesStub,
|
||||
recordRequest: recordRequestStub,
|
||||
recordResponse: recordResponseStub,
|
||||
recordError: sinon.stub(),
|
||||
getSessionLog: sinon.stub().returns({ startTime: "", entries: [] }),
|
||||
}
|
||||
|
||||
getRecorderStub = sinon.stub(GrpcRecorderBuilder, "getRecorder").returns(mockRecorder)
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
sinon.restore()
|
||||
})
|
||||
|
||||
it("should return an array of post-record hooks", () => {
|
||||
const mockController = {} as Controller
|
||||
const hooks = testHooks(mockController)
|
||||
|
||||
hooks.should.be.an.Array()
|
||||
hooks.should.have.length(1)
|
||||
hooks[0].should.be.a.Function()
|
||||
})
|
||||
|
||||
it("should execute hook and call recorder methods", async () => {
|
||||
const mockController = {
|
||||
getStateToPostToWebview: sinon.stub().returns({}),
|
||||
} as any as Controller
|
||||
|
||||
const hooks = testHooks(mockController)
|
||||
|
||||
const mockEntry: GrpcLogEntry = {
|
||||
requestId: "test-request-id",
|
||||
service: "TestService",
|
||||
method: "testMethod",
|
||||
isStreaming: false,
|
||||
request: { message: {} },
|
||||
status: "pending",
|
||||
}
|
||||
|
||||
await hooks[0](mockEntry)
|
||||
|
||||
// Validate sinon stub calls
|
||||
sinon.assert.calledWith(getRecorderStub, mockController)
|
||||
sinon.assert.calledOnce(cleanupSyntheticEntriesStub)
|
||||
sinon.assert.calledOnce(recordRequestStub)
|
||||
sinon.assert.calledOnce(recordResponseStub)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,38 @@
|
||||
import { Controller } from "@/core/controller"
|
||||
import { GrpcRecorderBuilder } from "@/core/controller/grpc-recorder/grpc-recorder.builder"
|
||||
import { GrpcPostRecordHook } from "@/core/controller/grpc-recorder/types"
|
||||
import { getLatestState } from "@/core/controller/state/getLatestState"
|
||||
|
||||
// Add 50ms delay by default to ensure we get the latest state
|
||||
const TEST_HOOK_LATEST_STATE_DELAY = 50
|
||||
|
||||
export function testHooks(controller: Controller): GrpcPostRecordHook[] {
|
||||
return [
|
||||
async (entry) => {
|
||||
GrpcRecorderBuilder.getRecorder(controller).cleanupSyntheticEntries()
|
||||
|
||||
await new Promise((resolve) => setTimeout(resolve, TEST_HOOK_LATEST_STATE_DELAY))
|
||||
|
||||
const requestId = entry.requestId
|
||||
|
||||
// Record synthetic "getLatestState" request
|
||||
GrpcRecorderBuilder.getRecorder(controller).recordRequest(
|
||||
{
|
||||
service: "cline.StateService",
|
||||
method: "getLatestState",
|
||||
message: {},
|
||||
request_id: requestId,
|
||||
is_streaming: false,
|
||||
},
|
||||
true,
|
||||
)
|
||||
|
||||
const state = await getLatestState(controller, {})
|
||||
|
||||
GrpcRecorderBuilder.getRecorder(controller).recordResponse(requestId, {
|
||||
request_id: requestId,
|
||||
message: state,
|
||||
})
|
||||
},
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
import { GrpcRequest } from "@/shared/WebviewMessage"
|
||||
|
||||
export type GrpcPostRecordHook = (entry: GrpcLogEntry, controller?: any) => Promise<void> | void
|
||||
|
||||
export type GrpcRequestFilter = (request: GrpcRequest) => boolean
|
||||
|
||||
export interface GrpcLogEntry {
|
||||
requestId: string
|
||||
service: string
|
||||
method: string
|
||||
isStreaming: boolean
|
||||
request: {
|
||||
message: any
|
||||
}
|
||||
response?: {
|
||||
message?: any
|
||||
error?: string
|
||||
isStreaming?: boolean
|
||||
sequenceNumber?: number
|
||||
}
|
||||
duration?: number
|
||||
status: "pending" | "completed" | "error"
|
||||
meta?: { synthetic?: boolean }
|
||||
}
|
||||
|
||||
export interface SessionStats {
|
||||
totalRequests: number
|
||||
pendingRequests: number
|
||||
completedRequests: number
|
||||
errorRequests: number
|
||||
}
|
||||
|
||||
export interface GrpcSessionLog {
|
||||
startTime: string
|
||||
stats?: SessionStats
|
||||
entries: GrpcLogEntry[]
|
||||
}
|
||||
@@ -1,5 +1,8 @@
|
||||
import { Anthropic } from "@anthropic-ai/sdk"
|
||||
import { buildApiHandler } from "@core/api"
|
||||
import { detectWorkspaceRoots } from "@core/workspace/detection"
|
||||
import { setupWorkspaceManager } from "@core/workspace/setup"
|
||||
import { WorkspaceRootManager } from "@core/workspace/WorkspaceRootManager"
|
||||
import { cleanupLegacyCheckpoints } from "@integrations/checkpoints/CheckpointMigration"
|
||||
import { downloadTask } from "@integrations/misc/export-markdown"
|
||||
import { ClineAccountService } from "@services/account/ClineAccountService"
|
||||
@@ -21,10 +24,12 @@ import * as vscode from "vscode"
|
||||
import { clineEnvConfig } from "@/config"
|
||||
import { HostProvider } from "@/hosts/host-provider"
|
||||
import { AuthService } from "@/services/auth/AuthService"
|
||||
import { PostHogClientProvider, telemetryService } from "@/services/posthog/PostHogClientProvider"
|
||||
import { getDistinctId } from "@/services/logging/distinctId"
|
||||
import { telemetryService } from "@/services/telemetry"
|
||||
import { ShowMessageType } from "@/shared/proto/host/window"
|
||||
import { getLatestAnnouncementId } from "@/utils/announcements"
|
||||
import { getCwd, getDesktopDir } from "@/utils/path"
|
||||
import { PromptRegistry } from "../prompts/system-prompt"
|
||||
import { ensureMcpServersDirectoryExists, ensureSettingsDirectoryExists, GlobalFileNames } from "../storage/disk"
|
||||
import { PersistenceErrorEvent, StateManager } from "../storage/StateManager"
|
||||
import { Task } from "../task"
|
||||
@@ -39,7 +44,6 @@ https://github.com/KumarVariable/vscode-extension-sidebar-html/blob/master/src/c
|
||||
|
||||
export class Controller {
|
||||
readonly id: string
|
||||
private disposables: vscode.Disposable[] = []
|
||||
task?: Task
|
||||
|
||||
mcpHub: McpHub
|
||||
@@ -47,12 +51,15 @@ export class Controller {
|
||||
authService: AuthService
|
||||
readonly stateManager: StateManager
|
||||
|
||||
// NEW: Add workspace manager (optional initially)
|
||||
private workspaceManager?: WorkspaceRootManager
|
||||
|
||||
constructor(
|
||||
readonly context: vscode.ExtensionContext,
|
||||
id: string,
|
||||
) {
|
||||
this.id = id
|
||||
|
||||
PromptRegistry.getInstance() // Ensure prompts and tools are registered
|
||||
HostProvider.get().logToChannel("ClineProvider instantiated")
|
||||
this.accountService = ClineAccountService.getInstance()
|
||||
this.stateManager = new StateManager(context)
|
||||
@@ -65,12 +72,19 @@ export class Controller {
|
||||
this.authService.restoreRefreshTokenAndRetrieveAuthInfo()
|
||||
})
|
||||
.catch((error) => {
|
||||
console.error("CRITICAL: Failed to initialize StateManager - extension may not function properly:", error)
|
||||
console.error(
|
||||
"[Controller] CRITICAL: Failed to initialize StateManager - extension may not function properly:",
|
||||
error,
|
||||
)
|
||||
HostProvider.window.showMessage({
|
||||
type: ShowMessageType.ERROR,
|
||||
message: "Failed to initialize Cline's application state. Please restart the extension.",
|
||||
})
|
||||
})
|
||||
|
||||
// Set up persistence error recovery
|
||||
this.stateManager.onPersistenceError = async ({ error }: PersistenceErrorEvent) => {
|
||||
console.error("Cache persistence failed, recovering:", error)
|
||||
console.error("[Controller] Cache persistence failed, recovering:", error)
|
||||
try {
|
||||
await this.stateManager.reInitialize()
|
||||
await this.postStateToWebview()
|
||||
@@ -79,7 +93,7 @@ export class Controller {
|
||||
message: "Saving settings to storage failed.",
|
||||
})
|
||||
} catch (recoveryError) {
|
||||
console.error("Cache recovery failed:", recoveryError)
|
||||
console.error("[Controller] Cache recovery failed:", recoveryError)
|
||||
HostProvider.window.showMessage({
|
||||
type: ShowMessageType.ERROR,
|
||||
message: "Failed to save settings. Please restart the extension.",
|
||||
@@ -87,6 +101,10 @@ export class Controller {
|
||||
}
|
||||
}
|
||||
|
||||
this.stateManager.onSyncExternalChange = async () => {
|
||||
await this.postStateToWebview()
|
||||
}
|
||||
|
||||
this.mcpHub = new McpHub(
|
||||
() => ensureMcpServersDirectoryExists(),
|
||||
() => ensureSettingsDirectoryExists(this.context),
|
||||
@@ -111,12 +129,6 @@ export class Controller {
|
||||
*/
|
||||
async dispose() {
|
||||
await this.clearTask()
|
||||
while (this.disposables.length) {
|
||||
const x = this.disposables.pop()
|
||||
if (x) {
|
||||
x.dispose()
|
||||
}
|
||||
}
|
||||
this.mcpHub.dispose()
|
||||
|
||||
console.error("Controller disposed")
|
||||
@@ -191,12 +203,29 @@ export class Controller {
|
||||
}
|
||||
this.stateManager.setGlobalState("autoApprovalSettings", updatedAutoApprovalSettings)
|
||||
}
|
||||
// Apply remote feature flag gate to focus chain settings
|
||||
// Apply remote feature flag gate to focus chain settings. Respect if user has disabled it.
|
||||
let focusChainEnabled: boolean
|
||||
if (focusChainSettings?.enabled === false) {
|
||||
focusChainEnabled = false
|
||||
} else if (focusChainFeatureFlagEnabled === false) {
|
||||
focusChainEnabled = false
|
||||
} else {
|
||||
focusChainEnabled = Boolean(focusChainSettings?.enabled)
|
||||
}
|
||||
|
||||
const effectiveFocusChainSettings = {
|
||||
...(focusChainSettings || { enabled: true, remindClineInterval: 6 }),
|
||||
enabled: Boolean(focusChainSettings?.enabled) && Boolean(focusChainFeatureFlagEnabled),
|
||||
enabled: focusChainEnabled,
|
||||
}
|
||||
|
||||
// Initialize and persist the workspace manager (multi-root or single-root) with telemetry + fallback
|
||||
this.workspaceManager = await setupWorkspaceManager({
|
||||
stateManager: this.stateManager,
|
||||
detectRoots: detectWorkspaceRoots,
|
||||
})
|
||||
|
||||
const cwd = this.workspaceManager?.getPrimaryRoot()?.path || (await getCwd(getDesktopDir()))
|
||||
|
||||
this.task = new Task(
|
||||
this,
|
||||
this.mcpHub,
|
||||
@@ -212,14 +241,15 @@ export class Controller {
|
||||
openaiReasoningEffort,
|
||||
mode,
|
||||
strictPlanModeEnabled ?? true,
|
||||
useAutoCondense ?? true,
|
||||
useAutoCondense ?? false,
|
||||
shellIntegrationTimeout,
|
||||
terminalReuseEnabled ?? true,
|
||||
terminalOutputLineLimit ?? 500,
|
||||
defaultTerminalProfile ?? "default",
|
||||
enableCheckpointsSetting ?? true,
|
||||
await getCwd(getDesktopDir()),
|
||||
cwd,
|
||||
this.stateManager,
|
||||
this.workspaceManager,
|
||||
task,
|
||||
images,
|
||||
files,
|
||||
@@ -594,7 +624,6 @@ export class Controller {
|
||||
const taskHistory = this.stateManager.getGlobalStateKey("taskHistory")
|
||||
const autoApprovalSettings = this.stateManager.getGlobalStateKey("autoApprovalSettings")
|
||||
const browserSettings = this.stateManager.getGlobalStateKey("browserSettings")
|
||||
const dictationSettings = this.stateManager.getGlobalStateKey("dictationSettings")
|
||||
const focusChainSettings = this.stateManager.getGlobalStateKey("focusChainSettings")
|
||||
const focusChainFeatureFlagEnabled = this.stateManager.getGlobalStateKey("focusChainFeatureFlagEnabled")
|
||||
const preferredLanguage = this.stateManager.getGlobalStateKey("preferredLanguage")
|
||||
@@ -626,8 +655,8 @@ export class Controller {
|
||||
const workflowToggles = this.stateManager.getWorkspaceStateKey("workflowToggles")
|
||||
|
||||
const currentTaskItem = this.task?.taskId ? (taskHistory || []).find((item) => item.id === this.task?.taskId) : undefined
|
||||
const checkpointTrackerErrorMessage = this.task?.taskState.checkpointTrackerErrorMessage
|
||||
const clineMessages = this.task?.messageStateHandler.getClineMessages() || []
|
||||
const checkpointManagerErrorMessage = this.task?.taskState.checkpointManagerErrorMessage
|
||||
|
||||
const processedTaskHistory = (taskHistory || [])
|
||||
.filter((item) => item.ts && item.task)
|
||||
@@ -637,24 +666,24 @@ export class Controller {
|
||||
const latestAnnouncementId = getLatestAnnouncementId(this.context)
|
||||
const shouldShowAnnouncement = lastShownAnnouncementId !== latestAnnouncementId
|
||||
const platform = process.platform as Platform
|
||||
const distinctId = PostHogClientProvider.getInstance().distinctId
|
||||
const distinctId = getDistinctId()
|
||||
const version = this.context.extension?.packageJSON?.version ?? ""
|
||||
const uriScheme = vscode.env.uriScheme
|
||||
const extensionInfo = {
|
||||
name: this.context.extension?.packageJSON?.name,
|
||||
publisher: this.context.extension?.packageJSON?.publisher,
|
||||
}
|
||||
|
||||
return {
|
||||
version,
|
||||
apiConfiguration,
|
||||
uriScheme,
|
||||
currentTaskItem,
|
||||
checkpointTrackerErrorMessage,
|
||||
clineMessages,
|
||||
currentFocusChainChecklist: this.task?.taskState.currentFocusChainChecklist || null,
|
||||
taskHistory: processedTaskHistory,
|
||||
shouldShowAnnouncement,
|
||||
platform,
|
||||
checkpointManagerErrorMessage,
|
||||
autoApprovalSettings,
|
||||
browserSettings,
|
||||
dictationSettings,
|
||||
focusChainSettings,
|
||||
focusChainFeatureFlagEnabled,
|
||||
preferredLanguage,
|
||||
@@ -683,6 +712,14 @@ export class Controller {
|
||||
mcpResponsesCollapsed,
|
||||
terminalOutputLineLimit,
|
||||
customPrompt,
|
||||
taskHistory: processedTaskHistory,
|
||||
platform,
|
||||
shouldShowAnnouncement,
|
||||
extensionInfo,
|
||||
// NEW: Add workspace information
|
||||
workspaceRoots: this.workspaceManager?.getRoots() ?? [],
|
||||
primaryRootIndex: this.workspaceManager?.getPrimaryIndex() ?? 0,
|
||||
isMultiRootWorkspace: (this.workspaceManager?.getRoots().length ?? 0) > 1,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import axios from "axios"
|
||||
import { StringArray } from "@/shared/proto/cline/common"
|
||||
import { SapAiCoreModelsRequest } from "@/shared/proto/cline/models"
|
||||
import { SapAiCoreModelDeployment, SapAiCoreModelsRequest, SapAiCoreModelsResponse } from "@/shared/proto/cline/models"
|
||||
import { Controller } from ".."
|
||||
|
||||
interface Token {
|
||||
@@ -12,6 +11,11 @@ interface Token {
|
||||
expires_at: number
|
||||
}
|
||||
|
||||
interface Deployment {
|
||||
id: string
|
||||
name: string
|
||||
}
|
||||
|
||||
/**
|
||||
* Authenticates with SAP AI Core and returns an access token
|
||||
* @param clientId SAP AI Core client ID
|
||||
@@ -36,15 +40,19 @@ async function getToken(clientId: string, clientSecret: string, tokenUrl: string
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetches model names from SAP AI Core deployments
|
||||
* Fetches deployments and orchestration availability from SAP AI Core deployments
|
||||
* @param accessToken Access token for authentication
|
||||
* @param baseUrl SAP AI Core base URL
|
||||
* @param resourceGroup SAP AI Core resource group
|
||||
* @returns Promise<string[]> Array of model names from running deployments
|
||||
* @returns Promise<{deployments: Deployment[], orchestrationAvailable: boolean}> Deployments and orchestration availability
|
||||
*/
|
||||
async function fetchAiCoreModelNames(accessToken: string, baseUrl: string, resourceGroup: string): Promise<string[]> {
|
||||
async function fetchAiCoreDeploymentsAndOrchestration(
|
||||
accessToken: string,
|
||||
baseUrl: string,
|
||||
resourceGroup: string,
|
||||
): Promise<{ deployments: Deployment[]; orchestrationAvailable: boolean }> {
|
||||
if (!accessToken) {
|
||||
return ["ai-core-not-configured"]
|
||||
return { deployments: [], orchestrationAvailable: false }
|
||||
}
|
||||
|
||||
const headers = {
|
||||
@@ -58,18 +66,29 @@ async function fetchAiCoreModelNames(accessToken: string, baseUrl: string, resou
|
||||
|
||||
try {
|
||||
const response = await axios.get(url, { headers })
|
||||
const deployments = response.data.resources
|
||||
const allDeployments = response.data.resources
|
||||
|
||||
return deployments
|
||||
.filter((deployment: any) => deployment.targetStatus === "RUNNING")
|
||||
// Filter running deployments
|
||||
const runningDeployments = allDeployments.filter((deployment: any) => deployment.targetStatus === "RUNNING")
|
||||
|
||||
// Check for orchestration deployment
|
||||
const orchestrationAvailable = runningDeployments.some((deployment: any) => deployment.scenarioId === "orchestration")
|
||||
|
||||
// Extract deployments with model names and IDs
|
||||
const deployments = runningDeployments
|
||||
.map((deployment: any) => {
|
||||
const model = deployment.details?.resources?.backend_details?.model
|
||||
if (!model?.name || !model?.version) {
|
||||
return null // Skip this row
|
||||
}
|
||||
return `${model.name}:${model.version}`
|
||||
return {
|
||||
id: deployment.id,
|
||||
name: `${model.name}:${model.version}`,
|
||||
}
|
||||
})
|
||||
.filter((modelName: string | null) => modelName !== null)
|
||||
.filter((deployment: any) => deployment !== null)
|
||||
|
||||
return { deployments, orchestrationAvailable }
|
||||
} catch (error) {
|
||||
console.error("Error fetching deployments:", error)
|
||||
throw new Error("Failed to fetch deployments")
|
||||
@@ -77,29 +96,53 @@ async function fetchAiCoreModelNames(accessToken: string, baseUrl: string, resou
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetches available models from SAP AI Core deployments
|
||||
* Fetches available models from SAP AI Core deployments and orchestration availability
|
||||
* @param controller The controller instance
|
||||
* @param request The request containing SAP AI Core configuration
|
||||
* @returns StringArray of model names
|
||||
* @returns SapAiCoreModelsResponse with deployments and orchestration availability
|
||||
*/
|
||||
export async function getSapAiCoreModels(controller: Controller, request: SapAiCoreModelsRequest): Promise<StringArray> {
|
||||
export async function getSapAiCoreModels(
|
||||
controller: Controller,
|
||||
request: SapAiCoreModelsRequest,
|
||||
): Promise<SapAiCoreModelsResponse> {
|
||||
try {
|
||||
// Check if required configuration is provided
|
||||
if (!request.clientId || !request.clientSecret || !request.baseUrl) {
|
||||
// Return empty array if configuration is incomplete
|
||||
return StringArray.create({ values: [] })
|
||||
// Return empty response if configuration is incomplete
|
||||
return SapAiCoreModelsResponse.create({
|
||||
deployments: [],
|
||||
orchestrationAvailable: false,
|
||||
})
|
||||
}
|
||||
|
||||
// Direct authentication and model name fetching
|
||||
// Direct authentication and deployment/orchestration fetching
|
||||
const token = await getToken(request.clientId, request.clientSecret, request.tokenUrl)
|
||||
const modelNames = await fetchAiCoreModelNames(token.access_token, request.baseUrl, request.resourceGroup)
|
||||
const { deployments, orchestrationAvailable } = await fetchAiCoreDeploymentsAndOrchestration(
|
||||
token.access_token,
|
||||
request.baseUrl,
|
||||
request.resourceGroup,
|
||||
)
|
||||
|
||||
// Extract base model names (without version) and sort
|
||||
const baseModelNames = modelNames.map((modelName) => modelName.split(":")[0].toLowerCase()).sort()
|
||||
// Create model-deployment pairs
|
||||
const modelDeployments = deployments
|
||||
.map((deployment) => {
|
||||
const modelName = deployment.name.split(":")[0].toLowerCase()
|
||||
return SapAiCoreModelDeployment.create({
|
||||
modelName: modelName,
|
||||
deploymentId: deployment.id,
|
||||
})
|
||||
})
|
||||
.sort((a, b) => a.modelName.localeCompare(b.modelName))
|
||||
|
||||
return StringArray.create({ values: baseModelNames })
|
||||
return SapAiCoreModelsResponse.create({
|
||||
deployments: modelDeployments,
|
||||
orchestrationAvailable,
|
||||
})
|
||||
} catch (error) {
|
||||
console.error("Error fetching SAP AI Core models:", error)
|
||||
return StringArray.create({ values: [] })
|
||||
return SapAiCoreModelsResponse.create({
|
||||
deployments: [],
|
||||
orchestrationAvailable: false,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,7 +5,7 @@ import { fileExistsAtPath } from "@utils/fs"
|
||||
import axios from "axios"
|
||||
import fs from "fs/promises"
|
||||
import path from "path"
|
||||
import { telemetryService } from "@/services/posthog/PostHogClientProvider"
|
||||
import { telemetryService } from "@/services/telemetry"
|
||||
import { groqModels } from "../../../shared/api"
|
||||
import { Controller } from ".."
|
||||
|
||||
|
||||
@@ -110,6 +110,12 @@ export async function refreshOpenRouterModels(
|
||||
|
||||
switch (rawModel.id) {
|
||||
case "anthropic/claude-sonnet-4":
|
||||
// NOTE: we artificially restrict the context window to 200k to keep costs low for users, and have a :1m model variant created below for users that want to use the full 1m.
|
||||
modelInfo.contextWindow = 200_000
|
||||
modelInfo.supportsPromptCache = true
|
||||
modelInfo.cacheWritesPrice = 3.75
|
||||
modelInfo.cacheReadsPrice = 0.3
|
||||
break
|
||||
case "anthropic/claude-3-7-sonnet":
|
||||
case "anthropic/claude-3-7-sonnet:beta":
|
||||
case "anthropic/claude-3.7-sonnet":
|
||||
@@ -183,6 +189,10 @@ export async function refreshOpenRouterModels(
|
||||
modelInfo.maxTokens = 8_192 // 128000 breaks context window truncation
|
||||
modelInfo.contextWindow = 272_000 // openrouter reports 400k but the input limit is actually 400k-128k
|
||||
break
|
||||
case "x-ai/grok-code-fast-1":
|
||||
modelInfo.supportsPromptCache = true
|
||||
modelInfo.cacheReadsPrice = 0.02
|
||||
break
|
||||
default:
|
||||
if (rawModel.id.startsWith("openai/")) {
|
||||
modelInfo.cacheReadsPrice = parsePrice(rawModel.pricing?.input_cache_read)
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { telemetryService } from "@services/posthog/PostHogClientProvider"
|
||||
import { Empty, StringRequest } from "@shared/proto/cline/common"
|
||||
import { telemetryService } from "@/services/telemetry"
|
||||
import { Controller } from ".."
|
||||
|
||||
/**
|
||||
|
||||
@@ -1,55 +0,0 @@
|
||||
import { HostProvider } from "@/hosts/host-provider"
|
||||
import { TerminalInfo } from "@/integrations/terminal/TerminalRegistry"
|
||||
import * as proto from "@/shared/proto"
|
||||
import { ShowMessageType } from "@/shared/proto/host/window"
|
||||
import { Controller } from "../index"
|
||||
|
||||
export async function updateDefaultTerminalProfile(
|
||||
controller: Controller,
|
||||
request: proto.cline.StringRequest,
|
||||
): Promise<proto.cline.TerminalProfileUpdateResponse> {
|
||||
const profileId = request.value
|
||||
|
||||
// Update the terminal profile in the state
|
||||
controller.stateManager.setGlobalState("defaultTerminalProfile", profileId)
|
||||
|
||||
let closedCount = 0
|
||||
let busyTerminals: TerminalInfo[] = []
|
||||
|
||||
// Update the terminal manager of the current task if it exists
|
||||
if (controller.task) {
|
||||
// Call the updated setDefaultTerminalProfile method that returns closed terminal info
|
||||
const result = controller.task.terminalManager.setDefaultTerminalProfile(profileId)
|
||||
closedCount = result.closedCount
|
||||
busyTerminals = result.busyTerminals
|
||||
|
||||
// Show information message if terminals were closed
|
||||
if (closedCount > 0) {
|
||||
const message = `Closed ${closedCount} ${closedCount === 1 ? "terminal" : "terminals"} with different profile.`
|
||||
HostProvider.window.showMessage({
|
||||
type: ShowMessageType.INFORMATION,
|
||||
message,
|
||||
})
|
||||
}
|
||||
|
||||
// Show warning if there are busy terminals that couldn't be closed
|
||||
if (busyTerminals.length > 0) {
|
||||
const message =
|
||||
`${busyTerminals.length} busy ${busyTerminals.length === 1 ? "terminal has" : "terminals have"} a different profile. ` +
|
||||
`Close ${busyTerminals.length === 1 ? "it" : "them"} to use the new profile for all commands.`
|
||||
HostProvider.window.showMessage({
|
||||
type: ShowMessageType.WARNING,
|
||||
message,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Broadcast state update to all webviews
|
||||
await controller.postStateToWebview()
|
||||
|
||||
return proto.cline.TerminalProfileUpdateResponse.create({
|
||||
closedCount,
|
||||
busyTerminalsCount: busyTerminals.length,
|
||||
hasBusyTerminals: busyTerminals.length > 0,
|
||||
})
|
||||
}
|
||||
@@ -1,5 +1,4 @@
|
||||
import { buildApiHandler } from "@core/api"
|
||||
import { telemetryService } from "@services/posthog/PostHogClientProvider"
|
||||
import { Empty } from "@shared/proto/cline/common"
|
||||
import {
|
||||
PlanActMode,
|
||||
@@ -8,9 +7,14 @@ import {
|
||||
UpdateSettingsRequest,
|
||||
} from "@shared/proto/cline/state"
|
||||
import { convertProtoApiConfigurationToApiConfiguration } from "@shared/proto-conversions/state/settings-conversion"
|
||||
import { OpenaiReasoningEffort } from "@shared/storage/types"
|
||||
import { TelemetrySetting } from "@shared/TelemetrySetting"
|
||||
import { HostProvider } from "@/hosts/host-provider"
|
||||
import { TerminalInfo } from "@/integrations/terminal/TerminalRegistry"
|
||||
import { McpDisplayMode } from "@/shared/McpDisplayMode"
|
||||
import { OpenaiReasoningEffort } from "@/shared/storage/types"
|
||||
import { TelemetrySetting } from "@/shared/TelemetrySetting"
|
||||
import { ShowMessageType } from "@/shared/proto/host/window"
|
||||
import { telemetryService } from "../../../services/telemetry"
|
||||
import { BrowserSettings as SharedBrowserSettings } from "../../../shared/BrowserSettings"
|
||||
import { Controller } from ".."
|
||||
|
||||
/**
|
||||
@@ -98,6 +102,9 @@ export async function updateSettings(controller: Controller, request: UpdateSett
|
||||
case ProtoOpenaiReasoningEffort.HIGH:
|
||||
reasoningEffort = "high"
|
||||
break
|
||||
case ProtoOpenaiReasoningEffort.MINIMAL:
|
||||
reasoningEffort = "minimal"
|
||||
break
|
||||
default:
|
||||
throw new Error(`Invalid OpenAI reasoning effort value: ${request.openaiReasoningEffort}`)
|
||||
}
|
||||
@@ -139,10 +146,6 @@ export async function updateSettings(controller: Controller, request: UpdateSett
|
||||
controller.stateManager.setGlobalState("strictPlanModeEnabled", request.strictPlanModeEnabled)
|
||||
}
|
||||
|
||||
if (request.dictationSettings !== undefined) {
|
||||
controller.stateManager.setGlobalState("dictationSettings", request.dictationSettings)
|
||||
}
|
||||
|
||||
// Update auto-condense setting
|
||||
if (request.useAutoCondense !== undefined) {
|
||||
if (controller.task) {
|
||||
@@ -180,6 +183,91 @@ export async function updateSettings(controller: Controller, request: UpdateSett
|
||||
controller.stateManager.setGlobalState("customPrompt", value)
|
||||
}
|
||||
|
||||
// Update browser settings
|
||||
if (request.browserSettings !== undefined) {
|
||||
// Get current browser settings to preserve fields not in the request
|
||||
const currentSettings = controller.stateManager.getGlobalStateKey("browserSettings")
|
||||
|
||||
// Convert from protobuf format to shared format, merging with existing settings
|
||||
const newBrowserSettings: SharedBrowserSettings = {
|
||||
...currentSettings, // Start with existing settings (and defaults)
|
||||
viewport: {
|
||||
// Apply updates from request
|
||||
width: request.browserSettings.viewport?.width || currentSettings.viewport.width,
|
||||
height: request.browserSettings.viewport?.height || currentSettings.viewport.height,
|
||||
},
|
||||
// Explicitly handle optional boolean and string fields from the request
|
||||
remoteBrowserEnabled:
|
||||
request.browserSettings.remoteBrowserEnabled === undefined
|
||||
? currentSettings.remoteBrowserEnabled
|
||||
: request.browserSettings.remoteBrowserEnabled,
|
||||
remoteBrowserHost:
|
||||
request.browserSettings.remoteBrowserHost === undefined
|
||||
? currentSettings.remoteBrowserHost
|
||||
: request.browserSettings.remoteBrowserHost,
|
||||
chromeExecutablePath:
|
||||
// If chromeExecutablePath is explicitly in the request (even as ""), use it.
|
||||
// Otherwise, fall back to mergedWithDefaults.
|
||||
"chromeExecutablePath" in request.browserSettings
|
||||
? request.browserSettings.chromeExecutablePath
|
||||
: currentSettings.chromeExecutablePath,
|
||||
disableToolUse:
|
||||
request.browserSettings.disableToolUse === undefined
|
||||
? currentSettings.disableToolUse
|
||||
: request.browserSettings.disableToolUse,
|
||||
customArgs:
|
||||
"customArgs" in request.browserSettings ? request.browserSettings.customArgs : currentSettings.customArgs,
|
||||
}
|
||||
|
||||
// Update global state with new settings
|
||||
controller.stateManager.setGlobalState("browserSettings", newBrowserSettings)
|
||||
|
||||
// Update task browser settings if task exists
|
||||
if (controller.task) {
|
||||
controller.task.browserSettings = newBrowserSettings
|
||||
controller.task.browserSession.browserSettings = newBrowserSettings
|
||||
}
|
||||
}
|
||||
|
||||
// Update default terminal profile
|
||||
if (request.defaultTerminalProfile !== undefined) {
|
||||
const profileId = request.defaultTerminalProfile
|
||||
|
||||
// Update the terminal profile in the state
|
||||
controller.stateManager.setGlobalState("defaultTerminalProfile", profileId)
|
||||
|
||||
let closedCount = 0
|
||||
let busyTerminals: TerminalInfo[] = []
|
||||
|
||||
// Update the terminal manager of the current task if it exists
|
||||
if (controller.task) {
|
||||
// Call the updated setDefaultTerminalProfile method that returns closed terminal info
|
||||
const result = controller.task.terminalManager.setDefaultTerminalProfile(profileId)
|
||||
closedCount = result.closedCount
|
||||
busyTerminals = result.busyTerminals
|
||||
|
||||
// Show information message if terminals were closed
|
||||
if (closedCount > 0) {
|
||||
const message = `Closed ${closedCount} ${closedCount === 1 ? "terminal" : "terminals"} with different profile.`
|
||||
HostProvider.window.showMessage({
|
||||
type: ShowMessageType.INFORMATION,
|
||||
message,
|
||||
})
|
||||
}
|
||||
|
||||
// Show warning if there are busy terminals that couldn't be closed
|
||||
if (busyTerminals.length > 0) {
|
||||
const message =
|
||||
`${busyTerminals.length} busy ${busyTerminals.length === 1 ? "terminal has" : "terminals have"} a different profile. ` +
|
||||
`Close ${busyTerminals.length === 1 ? "it" : "them"} to use the new profile for all commands.`
|
||||
HostProvider.window.showMessage({
|
||||
type: ShowMessageType.WARNING,
|
||||
message,
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Post updated state to webview
|
||||
await controller.postStateToWebview()
|
||||
|
||||
|
||||
@@ -138,7 +138,11 @@ async function cleanupTaskFiles(controller: Controller, preserveTaskIds: string[
|
||||
// Delete only non-preserved task directories
|
||||
for (const dir of taskDirs) {
|
||||
if (!preserveTaskIds.includes(dir)) {
|
||||
await fs.rm(path.join(taskDirPath, dir), { recursive: true, force: true })
|
||||
// Task dir path is not workspace specific
|
||||
await fs.rm(path.join(taskDirPath, dir), {
|
||||
recursive: true,
|
||||
force: true,
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -47,8 +47,6 @@ export async function deleteTasksWithIds(controller: Controller, request: String
|
||||
* @param id The task ID to delete
|
||||
*/
|
||||
async function deleteTaskWithId(controller: Controller, id: string): Promise<void> {
|
||||
console.info("deleteTaskWithId: ", id)
|
||||
|
||||
try {
|
||||
// Clear current task if it matches the ID being deleted
|
||||
if (id === controller.task?.taskId) {
|
||||
|
||||
@@ -10,7 +10,8 @@ import { Controller } from ".."
|
||||
export async function taskCompletionViewChanges(controller: Controller, request: Int64Request): Promise<Empty> {
|
||||
try {
|
||||
if (request.value && controller.task) {
|
||||
await controller.task.presentMultifileDiff(request.value, true)
|
||||
// presentMultifileDiff is optional on ICheckpointManager, so capture then optionally invoke
|
||||
await controller.task.checkpointManager?.presentMultifileDiff?.(request.value, true)
|
||||
}
|
||||
return Empty.create()
|
||||
} catch (error) {
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { telemetryService } from "@services/posthog/PostHogClientProvider"
|
||||
import { Empty, StringRequest } from "@shared/proto/cline/common"
|
||||
import { telemetryService } from "@/services/telemetry"
|
||||
import { Controller } from ".."
|
||||
|
||||
/**
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user