Compare commits

...

152 Commits

Author SHA1 Message Date
abeatrix f2dc9c8482 fix: extension auth flow
- Remove provider parameter from handleAuthCallback methods across auth services and controller.
- Accepts Firebase JWT token that can be refreshed instead of oauth token from provider
2025-08-02 17:54:58 -07:00
Bee 0ddef94d1f feat: use auth callback handling with custom AuthHandler (#5223)
* feat: use auth callback handling with custom AuthHandler

- Add AuthHandler class to manage OAuth flow with local HTTP server
- Move callback logic from extension.ts to SharingUriHandler, making that shared between the original and new authentication ways
- Enabling Custom HTTP for "core only" environments
- Async starting and stopping HTTP server
2025-08-02 15:10:16 -07:00
Bee b9ae83b1cd fix: standalone navbar style with chat layout refactor (#5308)
* fix: standalone navbar style with chat layout refactor

* Update webview-ui/src/components/chat/chat-view/components/layout/MessagesArea.tsx

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>

---------

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
2025-08-02 14:17:38 -07:00
Sarah Fortune e4eaf34827 test: Fix and re-enable unit tests (#5298)
* test: Fix and re-enable unit tests

Re-enable unit tests in CI workflow that were previously disabled

The cline-api test requires VSCode SDK which cannot be easily mocked in unit tests,
so it has been moved to integration tests where the full VSCode environment is available.

The @google/genai module is ES6-only which causes issues when running integration tests
compiled to CommonJS. A mock implementation has been added and the module resolution
is intercepted in test-setup.js to use the mock instead.

The bedrock unit tests for getModelId() functionality are removed as they were failing
and fixing them is out of scope for this PR.

- Move cline-api.test.ts from exports to test directory as it depends on VSCode SDK
- Add gemini-mock.test.ts to mock @google/genai ES6 module for CommonJS compatibility
- Add module interception in test-setup.js to redirect @google/genai to mock
- Remove failing bedrock unit tests introduced in PR #4209 (out of scope)

* Update src/api/providers/__tests__/bedrock.test.ts

Co-authored-by: ellipsis-dev[bot] <65095814+ellipsis-dev[bot]@users.noreply.github.com>

* Formatting

---------

Co-authored-by: ellipsis-dev[bot] <65095814+ellipsis-dev[bot]@users.noreply.github.com>
2025-08-02 01:47:27 +01:00
github-actions[bot] 6d3ed43c74 v3.20.5 Release Notes (#5297)
* changeset version bump

* Updating CHANGELOG.md format

* Update CHANGELOG.md for version 3.20.5

---------

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
Co-authored-by: github-actions <github-actions@github.com>
Co-authored-by: pashpashpash <nik@cline.bot>
2025-08-01 16:50:04 -07:00
celestial-vault cbb67b48f2 fix secrets persistence (#5296) 2025-08-01 16:41:14 -07:00
Sarah Fortune a5f6a97be8 Fix eslint unit tests (#5295) 2025-08-01 23:16:18 +01:00
github-actions[bot] f309b062e7 v3.20.4 Release Notes
v3.20.4 Release Notes
2025-08-01 13:20:27 -07:00
canvrno 768df130ab Fix for delete task popup (#5260)
Co-authored-by: Kevin Bond <kevin@Kevins-MacBook-Pro.local>
2025-08-01 13:05:21 -07:00
Toshii 9980cb0938 fix grok browser_user (#5278) 2025-08-01 10:14:19 -07:00
Ara aca4f842fa Update Cerebras models (#5282)
* Update Cerebras models

* Add changeset

* Modify completion token limits

* Split qwen3 coder into free/paid

* Change -paid to base model name

* Update Cerebras models

* Update Cerebras models

* Update Cerebras models

* Update api.ts

* Update Cerebras models

---------

Co-authored-by: Kevin Taylor <kevin.taylor@cerebras.net>
2025-08-01 01:11:53 -07:00
Bee 3fc91e2afe fix: E2E test stability by reordering sidebar and notification setup (#5279)
* fix: E2E test stability by reordering sidebar and notification setup

- Extract editor menu locator to variable for better readability
- Move sidebar opening to page fixture to ensure it's available earlier
- Wait for chat input visibility before disabling notifications
- Prevents race conditions in test initialization

* fix
2025-07-31 18:03:14 -07:00
celestial-vault 5f4700ce95 Move apiconfiguration to cache layer (#5210)
* remove chatSettings object

* use cache for apiCongfiguration state

* add state persistence debounced, batch state updates, make setters synchronous

* fix types after merge conflicts

* fix global state reset

* remove clearCache; make dispose function private; remove vscode api dependency; call reInitialize in reset functions instead of dispose/initialize
2025-07-31 16:58:47 -07:00
Jim Tang dbaf5e3ee3 Update system.ts for formating the code. (#5270) 2025-07-31 16:19:01 -07:00
Toshii 576176c24f add grok4 to advanced list (#5276) 2025-07-31 14:54:45 -07:00
Akshay Raj Gollahalli c8abcbfdf9 Do not ignore pkg folder (#4483) (#4505) 2025-07-31 12:11:31 -07:00
celestial-vault 8e984f2d98 clean up getStateToPostToWebview in preparation for migration to StateManager service (#5266) 2025-07-31 11:47:06 -07:00
github-actions[bot] 81564faa4e v3.20.3 Release Notes (#5185)
* changeset version bump

* Updating CHANGELOG.md format

* releaseee

---------

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
Co-authored-by: github-actions <github-actions@github.com>
Co-authored-by: pashpashpash <nik@cline.bot>
2025-07-30 21:49:57 -07:00
pashpashpash f8b5f1fd72 adding redirectUrl to credits purchasing experience (#5158) 2025-07-30 17:43:04 -07:00
celestial-vault 2eb57384ab remove useEffect (#5261) 2025-07-30 17:11:01 -07:00
Sarah Fortune c80bae504a Add a flag to build the webview without minification, compact, etc. (#5262)
When the webview is built wuth build:test:
* don't compact the compiled code
* don't minify
* use inline source maps (the embedded JCEF browser can't load source maps from .map files).
2025-07-30 19:53:36 -04:00
Sarah Fortune 80f955be9e Add vscode.workspace.findFiles to no-direct-vscode-api eslint rule. (#5263)
Add `vscode.workspace.findFiles` to the list of the Vscode API calls that should not be re-introduced to the extension unintentionally.
2025-07-30 19:49:15 -04:00
wangyijing130 7435ffcd2f fix: use Uri.from to generate valid diff URI (#4882)
* fix: use Uri.from to generate valid diff URI

* fix the conflicts for VscodeDiffViewProvider.ts has been moved

---------

Co-authored-by: wangyj20 <wangyj20@asiainfo.com>
2025-07-30 10:42:19 -07:00
Bee a05d438612 refactor: setup e2e tests to use shared mock server (#5245)
* refactor: e2e test setup to use Playwright projects with global server

- Replace globalSetup/globalTeardown with Playwright projects configuration
- Rename setup.ts to global.setup.ts and teardown.ts to global.teardown.ts
- Convert ClineApiServerMock to use shared global server instance
- Add proper dependency management between setup, tests, and cleanup phases
- Improve server connection tracking and cleanup handling

* Rename Playwright test project names to match

* IS_DEV

* update helpers
2025-07-30 00:16:08 -07:00
Daniel Steigman b4b7512d9f Improve Cline accounts support telemetry (#5242)
* fixed linter rule and added identified telemtry stuff

* Updated the error handling

* fixed error handling
2025-07-29 17:23:50 -07:00
Toshii e08c65618e read_file can read images (png, jpg, jpeg, webp) (#4411)
* base

* throw

* chat ui

Co-authored-by: Ding Fei <fding@feysh.com>

* chat row logic for image file reads

* dim check change

---------

Co-authored-by: Ding Fei <fding@feysh.com>
2025-07-29 15:41:31 -07:00
Bee d653f1cc27 test: update Playwright test timeouts (#5241)
- Rename isGitHubAction to isCI for broader CI detection
- Adjust timeout logic to use CI or Windows conditions
- Reduce expect timeout from 40s/20s to 5s/2s for faster feedback
- Decrease streaming chunk delay from 50ms to 20ms in server mock
2025-07-29 15:27:46 -07:00
Bee c3a97c3eda e2e test: add mock service for cline API & new test for diff editor (#5196)
* Add mock api service and E2E test infrastructure

- Create AuthServiceMock for testing with mock user data and API responses
- Add AuthProvider interface to standardize authentication providers
- Implement E2E test fixtures with mock server and workspace setup
- Add comprehensive E2E tests for authentication and core functionality
- Export DEFAULT_CLINE_APP_URL config and make getEnvironmentConfig more flexible
- Update AuthService to use mock implementation during E2E tests

* format

* import

* refactor mock server

* rename data

* wait for text

* wait for edit

* increase timeout for windows

* clean up

* rename test and add orgs
2025-07-29 12:39:49 -07:00
celestial-vault 0e56272d65 remove chatSettings object (#5178)
* remove chatSettings object

* fix types after merge conflicts
2025-07-29 12:31:52 -07:00
Kevin Taylor fdc2e2655a Add Cerebras model Qwen 3 235b instruct (#5236) 2025-07-29 11:55:48 -07:00
Wintertee 6050413b8b fix: remove duplicate tool registration for claude4-experimental (#4748) 2025-07-29 10:48:41 -07:00
Bee c54f0da737 feat: adds navigation bar component and restructure app layout (#5220) 2025-07-29 13:05:01 -04:00
Sarah Fortune 6cbfb2b8b0 Remove duplication define property in esbuild.json (#5234) 2025-07-29 08:54:12 -07:00
Sarah Fortune 22788f0f12 Move the OutputChannel to the HostProvider (#5189)
* Move the OutputChannel to the HostProvider

Replace `OutputChannel.appendLine` with `HostProvider.logToChannel`.

Remove places where the cline OutputChannel was being passed around. Now it is stored in the HostProvider, so we don't need to do this.

# Conflicts:
#	src/hosts/vscode/VscodeWebviewProvider.ts

* Dont log the timestamp in logger.ts, the cline-core logger already outputs the timestamp

* Fix imports
2025-07-28 22:56:43 -07:00
DongDong Ling 708b785a97 Add Huawei Cloud MaaS Provider (#5071)
* Add Huawei Cloud MaaS Provider

* Fix case error

* Add missing modelid

* add huawei specific modelId and modelInfo

* add huawei specific model id and model info in state.proto

* more huawei maas specific change
2025-07-28 21:47:21 -07:00
Jose R. Perez 099bc44d42 docs: fix Global Rules directory location for Linux/WSL systems (#5219) 2025-07-28 23:54:03 -04:00
Toshii b9f4678dba add try-catch handling (#5227) 2025-07-28 20:21:51 -07:00
Bee f7d17384f6 refactor & fix: improve account view with better states management (#5182)
* refactor & fix: improve account view with better states management

The previous AccountView implementation suffered from several critical state management issues:

- Incorrect info on display: The active account is not ready when component is mounted because the fetching only start on mount but doesn't get reset correctly
- Excessive re-renders: All data was fetched on component mount, causing cascading state updates
- Race conditions: Multiple concurrent API calls and state dependencies created unpredictable behavior, e.g. 403 rate limits errors
- Monolithic state management: All account data, organizations, and auth state was managed in a single massive component
- Poor user experience: Users saw empty states and loading flickers when switching between organizations
- Tight coupling: User and org info logic was deeply embedded within the account view that cause Effect dependency loops

Solution: Centralized Authentication Context

- Extracted auth logic into dedicated ClineAuthContext with organizations state management
- Eliminated prop drilling by providing clineUser, organizations, and activeOrganization at the context level
- Reduced component re-renders by managing auth state separately from UI state
- Performed authentication guard at higher level and only displays user account to authenticated user. The component will get dismounted when user is not autheticated.
- Move handleSignIn and handleSignout into individual functions instead as they are regular functions with no state dependency

* 60secs

* Optimize state updates in AccountView to prevent unnecessary re-renders

Remove conditional checks before setState calls and use functional updates
with deep equality comparison to avoid redundant state changes and
dependency array bloat in useCallback hooks.

* add docs

* fix format

* fix error test

* setuser on logout
2025-07-28 15:46:23 -07:00
Sarah Fortune bb5a64afb3 Quiet spammy MCP debug logs (#5224) 2025-07-28 15:44:38 -07:00
Sarah Fortune 61224734f8 Change timeout, token budget and line limit fields in the ProtoBus from int64 to int32. (#5221) 2025-07-28 17:40:15 -04:00
Bee a28b995ab1 Fix styled-components prop warnings (#5181)
* Fix styled-components prop warnings

- Fix styled-components shouldForwardProp warnings by filtering non-DOM props
- Clean up unused imports in ChatTextArea and other components

* use mjs

* later

* remove unused imports
2025-07-28 11:19:32 -07:00
Bee a91878efc6 Fix: webview panel state change steals focus (#5193)
* Fix: webview panel state change steals focus

Fix webview visibility detection to check both visible and active states before taking focus. If a panel is visible but not active (focused), it should not steals editor focus.

Also removes unused import & add type imports

* add changeset
2025-07-28 10:59:00 -07:00
Jonathan Barazany 65c21e7b7d Bug fix: VSCode LM API token counting for Claude models (#5051)
* Improve token counting for Claude models in VSCode LM provider

- Reorder imports for better organization
- Add extractTextFromMessage helper method
- Add isClaudeModel detection method
- Use 4:1 character-to-token ratio for Claude models instead of VSCode's inaccurate counting
- Fallback to existing VSCode LM token counting for non-Claude models

* Update version to 3.18.3-r1 and refactor token calculation in VsCodeLmHandler

* 3.19.5-r1

* Add smart jobs impress changeset for VSCode LM API token counting fix

---------

Co-authored-by: Jonathan Barazany <jbarazany@microsoft.com>
2025-07-28 02:09:40 -07:00
Sarah Fortune 56e388c90f Add a check to the proto scripts to warn about using int64 types. (#5174)
* Add a check to the proto scripts to warn about using int64 types.

Javascript cannot represent the full range of int64. So, when the protos are deserialized from JSON int64's are converted to strings. The typescript code is expecting a number and not a string, and this causes errors.

This was noticed before now because in the vscode protobus and hostbridge, the proto messages are not serialized and deserialized, they are just passed around as JS objects.

However, in IntelliJ the protos are serialized when they are sent through the ProtoBus. When the response messages contains and int64, it is deserialized to a string instead of a number for safety. This is causes parts of Cline to fail in IntelliJ, e.g. the task history view won't load because `Task.getTotalTasksSize()` returns a string when it is expecting a number.

* Make checkProtos shorter

* Update scripts/build-proto.mjs

Co-authored-by: ellipsis-dev[bot] <65095814+ellipsis-dev[bot]@users.noreply.github.com>

* Update scripts/build-proto.mjs

Co-authored-by: ellipsis-dev[bot] <65095814+ellipsis-dev[bot]@users.noreply.github.com>

* Update scripts/build-proto.mjs

Co-authored-by: ellipsis-dev[bot] <65095814+ellipsis-dev[bot]@users.noreply.github.com>

* Fix typo

* Fix typo

* Fix bad merge

---------

Co-authored-by: ellipsis-dev[bot] <65095814+ellipsis-dev[bot]@users.noreply.github.com>
2025-07-27 22:02:12 -04:00
pashpashpash 586d804a01 Revert "Spruce up HistoryPreview (#4101)" (#5207)
This reverts commit cdfffb8464.
2025-07-27 16:48:49 -07:00
Saoud Rizwan 85fbbcbe3f Revise contributing guidelines and fix PR template link to feature requests board (#5195)
* Revise contributing guidelines and fix PR template link to feature requests board

* Fix wording
2025-07-26 12:43:59 -07:00
ZhangZhiheng 25c5310383 Fix url no trim (#4641)
* fix: trim input value for URL fields in BaseUrlField and DebouncedTextField components (#4051)

* chore: add changeset
2025-07-26 12:23:09 -07:00
Saoud Rizwan 19ef843d4f Revert "feat: update Gemini models - remove deprecated and add 2.5 Flash-Lite…" (#5194)
This reverts commit f6273e0661.
2025-07-26 11:53:06 -07:00
dependabot[bot] 2b3dd14271 Bump the npm_and_yarn group with 3 updates (#4186)
Bumps the npm_and_yarn group with 3 updates: [brace-expansion](https://github.com/juliangruber/brace-expansion), [tar-fs](https://github.com/mafintosh/tar-fs) and [undici](https://github.com/nodejs/undici).


Updates `brace-expansion` from 1.1.11 to 1.1.12
- [Release notes](https://github.com/juliangruber/brace-expansion/releases)
- [Commits](https://github.com/juliangruber/brace-expansion/compare/1.1.11...v1.1.12)

Updates `tar-fs` from 3.0.8 to 3.0.9
- [Commits](https://github.com/mafintosh/tar-fs/compare/v3.0.8...v3.0.9)

Updates `undici` from 6.21.1 to 6.21.3
- [Release notes](https://github.com/nodejs/undici/releases)
- [Commits](https://github.com/nodejs/undici/compare/v6.21.1...v6.21.3)

---
updated-dependencies:
- dependency-name: brace-expansion
  dependency-version: 1.1.12
  dependency-type: indirect
  dependency-group: npm_and_yarn
- dependency-name: tar-fs
  dependency-version: 3.0.9
  dependency-type: indirect
  dependency-group: npm_and_yarn
- dependency-name: undici
  dependency-version: 6.21.3
  dependency-type: indirect
  dependency-group: npm_and_yarn
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2025-07-26 08:03:48 -07:00
Karan Vaidya 721e7ae305 Add Composio to adding-mcp-servers-from-github.mdx (#4624)
* Add Composio to adding-mcp-servers-from-github.mdx

* Update adding-mcp-servers-from-github.mdx
2025-07-26 07:52:27 -07:00
Eugene Demkin f6273e0661 feat: update Gemini models - remove deprecated and add 2.5 Flash-Lite (#4681)
- Remove deprecated experimental models:
  - gemini-1.5-flash-8b-exp-0827
  - gemini-1.5-flash-exp-0827
  - gemini-1.5-pro-exp-0827
- Add gemini-2.5-flash-lite-preview-06-17 with latest pricing
2025-07-26 07:45:29 -07:00
CellenLee 68d0af2afc feat: moonshot provider ui polish (#5034) 2025-07-26 07:21:50 -07:00
Saoud Rizwan 4286f301d2 Remove feature_contribution issue type (#5184) 2025-07-26 06:18:41 -07:00
dependabot[bot] 28536084bf Bump form-data in /webview-ui in the npm_and_yarn group (#5095)
---
updated-dependencies:
- dependency-name: form-data
  dependency-version: 4.0.4
  dependency-type: indirect
  dependency-group: npm_and_yarn
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2025-07-26 06:07:58 -07:00
Utkarsh dfbac3eefd Support for Deepseek R1 0528 (#3903) (#5183) 2025-07-26 05:45:31 -07:00
Saoud Rizwan 04f0710a03 Update bug report template to make system information and logs fields optional (#5159) 2025-07-26 01:58:48 -07:00
kvyb 195e15db32 Move vscode.commands.executeCommand("vscode.open") to Hostbridge (#5173)
* feat: add openFile host bridge for vscode.open command

* fix: simplify openFile hostbridge to follow gRPC best practices:
- Remove success boolean field from OpenFileResponse proto
- Use gRPC exceptions for error handling instead of success/failure booleans
- Simplify hostbridge implementation to just move existing vscode.open code

* fix: remove create wrapper from openFile call

* fix proto merge conflict
2025-07-26 04:19:03 -04:00
Sarah Fortune 19cb70de55 Use npm moduleopen to open URLs in the external browser (instead of the host bridge) (#5013)
* Use npm `open` to open URLs in the external browser

# Conflicts:
#	src/utils/env.ts

# Conflicts:
#	src/utils/env.ts

* Change log statement

* Use the simple-open-url module to open URLs in the system browser.

Log failures of ProtoBus RPCs

* Remove vscode hostbridge handler for openExternal

* Rm unused imports

* Switch back to `open` module.

Update esbuild.js to ES6 and move to esbuild.mjs

* Update src/utils/env.ts

Co-authored-by: ellipsis-dev[bot] <65095814+ellipsis-dev[bot]@users.noreply.github.com>

* remove IS_DEV from e2e setup build

---------

Co-authored-by: ellipsis-dev[bot] <65095814+ellipsis-dev[bot]@users.noreply.github.com>
Co-authored-by: abeatrix <beatrix@cline.bot>
2025-07-26 04:06:53 -04:00
github-actions[bot] e2a2ecde44 v3.20.2 Release Notes (#5155)
* changeset version bump

* Updating CHANGELOG.md format

* Update CHANGELOG.md

---------

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
Co-authored-by: github-actions <github-actions@github.com>
Co-authored-by: Saoud Rizwan <7799382+saoudrizwan@users.noreply.github.com>
2025-07-26 00:00:19 -07:00
Saoud Rizwan 1a466c0a44 Fix cursor state after restoring files to be disabled after checked out (#5179)
* Fix cursor state after restoring files to be disabled after checked out

* Create silver-llamas-pretend.md
2025-07-25 23:51:34 -07:00
Sarah Fortune 31cbf489c4 Fix launch configuration for the cline-core (#5170) 2025-07-26 02:38:38 -04:00
Saoud Rizwan c667d34f27 Fix issue where checkpointing blocked UI (#5177)
* Fix issue where checkpointing blocked UI

* Create wet-fishes-study.md
2025-07-25 23:24:39 -07:00
Sarah Fortune a1bf1f95a3 refactor(proto): Align proto directory structure with package names to follow best practices (#5171)
* Reorganized proto directory structure to match package naming convention

Moved cline package protos from the proto directory to proto/cline/ directory
Host package protos remain in proto/host/ directory

Updated all import statements across codebase to reflect new proto paths

Removed proto linter exception for package/directory mismatch rule

Fix Vscode proto indexing errors by setting the proto path in the Vscode settings.

* Update imports to use new package

Update imports from @shared/proto/<thing> to @share/proto/cline/<thing>
2025-07-26 00:58:16 -04:00
Bee 5da75af616 Fix Qwen API options inconsistency (#5162)
* Fix Qwen API option inconsistency

Refactor Qwen API region handling with enum and improved type safety

Changes:

- Replace string literals with QwenApiRegions enum for better type safety
- Add default region initialization in QwenHandler constructor
- Extract useChinaApi() method for cleaner conditional logic
- Update UI dropdown to use enum values with proper memoization
- Improve code maintainability and reduce magic strings

* changeset added

* Apply suggestions from code review

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>

* fix type with conversion

* Refactor Qwen model defaults to use first model dynamically

Move type definitions and enums after model objects and set default
models by selecting the first key from each model object instead of
hardcoding specific model IDs.

---------

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
2025-07-25 11:15:01 -07:00
Sarah Fortune 38babe12f7 Replace vscode show message API calls with the host bridge (#5161) 2025-07-25 11:48:16 -04:00
Sarah Fortune 66fb8835a4 Add an RPC to the host bridge to scroll the diff viewer. (#5151) 2025-07-24 23:09:33 -04:00
Bee 214e157360 Fix organization state reset when switching between accounts (#5154)
* Fix organization state reset when switching between accounts

Move user authentication check into getUserOrganizations callback to properly reset state when switching between personal and organization accounts. This prevents stale organization data from persisting across account switches.

* add changeset

* Add error handling and refactor credit display components

Fix issues with balance display out of sync on org change or when API calls received 405 (rate limited) error

- Add error handling for failed API calls in getUserCredits and getOrganizationCredits
- Extract animated credit display logic into reusable StyledCreditDisplay component
- Simplify AccountView by removing inline credit animation code
- Improve organization state management and loading behavior

* Apply suggestions from code review

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>

* format

* reset on mount

---------

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
2025-07-24 19:59:42 -07:00
Igor Tceglevskii 7a9dce4f86 Moved open and visible tab retrieval to a separate hostbridge module (#5150) 2025-07-24 17:46:31 -07:00
Tomás Barreiro af7e3a4d20 Change the CLAUDE_CODE_MAX_OUTPUT_TOKENS (#5142)
* Change the CLAUDE_CODE_MAX_OUTPUT_TOKENS

* Add changeset

* Add comment and variable to explain the changes
2025-07-24 09:24:30 -07:00
schardosin 3abdc9ad0f Fixed issue affecting first-time credential entry for SAP AI Core (#5132)
* removed the reduced mask, which was making the client secret to fail in the first save

* added changeset
2025-07-23 22:19:47 -07:00
Ara 28b15d8b9b Adding gitbash terminal support and docs for solving windows terminal issues (#5110)
* Adding gitbash terminal support and docs for solving windows terminal issues

* Update docs/troubleshooting/terminal-integration-guide.mdx

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>

---------

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
2025-07-23 14:07:02 -07:00
github-actions[bot] bc6b3e54be v3.20.1 Release Notes (#5128)
* changeset version bump

* Updating CHANGELOG.md format

* Update CHANGELOG.md

---------

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
Co-authored-by: github-actions <github-actions@github.com>
Co-authored-by: Saoud Rizwan <7799382+saoudrizwan@users.noreply.github.com>
2025-07-23 11:46:55 -07:00
canvrno 9fad0aa4ae Fix file deletion bug (#5125)
* Fix for files being deleted when switching modes or closing tasks

* changeset

* Added check to see if we are waiting for API response

* More targetted fix

* Create hot-onions-promise.md

* Delete .changeset/hot-onions-promise.md

---------

Co-authored-by: Kevin Bond <kevin@Kevins-MacBook-Pro.local>
Co-authored-by: Saoud Rizwan <7799382+saoudrizwan@users.noreply.github.com>
2025-07-23 11:44:24 -07:00
Ara 23fea0e16b Stop auto focus of Cline window on Every update (#5117) 2025-07-23 04:03:28 -07:00
Bee e8aaa61494 Improve auth state management for account view (#5107)
- Fix AccountView state management when user is not authenticated or is authenticated after the webview is loaded
- Add proper loading state reset and conditional data fetching
2025-07-22 20:00:14 -07:00
github-actions[bot] d93080304c v3.20.0 Release Notes (#5096)
* changeset version bump

* Updating CHANGELOG.md format

* Update CHANGELOG.md and version for 3.20.0 release

---------

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
Co-authored-by: github-actions <github-actions@github.com>
Co-authored-by: pashpashpash <nik@cline.bot>
2025-07-22 19:52:16 -07:00
Ara 1ce5f72bc1 Updating the new release announcement note (#5101)
* Updating the new release announcement note

* Adding gitbash terminal support and docs for solving windows terminal issues
2025-07-22 19:37:44 -07:00
Saoud Rizwan fb676add2e Fix hugging face model description (#5105) 2025-07-22 19:06:51 -07:00
Ara 31cda0ce5e Adding support for new models Qwen 3 models on Qwen provider (#5106) 2025-07-22 19:00:49 -07:00
Ara e173dad69c Updating the ordering to move cerebras provider upwards in the list of providers (#5102) 2025-07-22 16:22:52 -07:00
Toshii 92f32522c5 devtral medium (#5100) 2025-07-22 16:07:00 -07:00
Bee 7817d5f261 Host bridge migration: showInputBox (#4747)
* Update showInputBox

* Simplify

* Remove undefined handler for ShowInputBoxResponse
2025-07-22 13:13:03 -07:00
Bee db6d288efa Display credit balance for all accounts (#4992)
* Display credit balance for all accounts

The credit balance display was previously only shown for personal accounts. This change removes the check for `activeOrganization === null` and displays the credit balance and "Add Credits" button for all account types, including organization accounts. A divider is added above the balance section for visual separation once the backend change is deployed.

* changeset

* Improve refresh logic

Refactors the `AccountView` component to properly display and manage credits for both user and organization accounts. It introduces the `getOrganizationCredits` API call to fetch organization-specific credits and updates the UI accordingly. The refresh logic has also been improved to ensure data consistency and prevent unnecessary API calls.

Key changes:

- Implemented `getOrganizationCredits` to fetch credits for the active organization.
- Modified the credit display to show organization credits when an organization is active.
- Updated the refresh logic to use `useCallback` and `debounce` for better performance and to prevent race conditions.
- Added a periodic refresh to update account data every 30 seconds.
- Improved error handling and loading state management.
- Removed the interval ref and replaced it with a simpler useEffect for periodic refresh.
- Added last fetch time to the UI.

* clean up

* deepEqual

* org management

* prevent race condition
2025-07-22 12:03:37 -07:00
github-actions[bot] 87ff00d87e v3.19.8 Release Notes (#5022)
* changeset version bump

* Updating CHANGELOG.md format

* Update CHANGELOG.md and package.json for v3.19.8 release

---------

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
Co-authored-by: github-actions <github-actions@github.com>
Co-authored-by: pashpashpash <nik@cline.bot>
2025-07-22 11:35:39 -07:00
Sarah Fortune e602efc7a6 Dont export the protobus handlers from the grpc-client protobus-services.ts (#5091) 2025-07-22 01:30:01 -07:00
kvyb e6462af336 automate announcement display for major.minor releases (#5081)
* automate announcement display for major.minor releases

* fix: simplify onDidShowAnnouncement
2025-07-21 23:35:27 -07:00
Sarah Fortune d2521a8abb Remove compiled files that were committed by mistake (#5082)
* Remove compiled files that were committed by mistake

* Don't JSON encode the grpc message request.

The original grpc-client-base.ts encoded the request message using
```
function encodeRequest(request: any): any {
  if (request === null || request === undefined) {
    return {}
  } else if (typeof request.toJSON === "function") {
    return request.toJSON()
  } else if (typeof request === "object") {
    return { ...request }
  } else {
    return { value: request }
  }
```
But the request object don't have a .toJSON method, so it was not actually converting them
to JSON properly.

Don't JSON encode request to keeo the same behaviour as before.

* Update gitignore
2025-07-21 23:22:25 -07:00
celestial-vault ad2923cd74 migrate save textDocument (#5088) 2025-07-21 23:12:31 -07:00
Sarah Fortune 1ecb24544f fix: Generate type-safe code for the Vscode Protobus service (#5077)
* fix: Generate type-safe code for the Vscode Protobus service

This commit establishes a fully type-safe ProtoBus system by fixing the streaming
response handler type definitions and completing the protobuf-driven architecture.

Key improvements:

• **Complete type safety**: ProtoBus is now completely type-safe with compile-time
  validation of all gRPC service definitions, request/response types, and handler
  signatures

• **Simplified message creation**: No longer need to manually call `Message.create({...})`
  - the generated code handles message instantiation automatically

• **Automated proto parsing**: Eliminated manual parsing of proto files - the build
  system now automatically generates TypeScript definitions from protobuf schemas

• **Proto files as source of truth**: Service names, method names, and message types
  are now definitively controlled by the proto files, ensuring consistency across
  the entire codebase

• **Handler type checking**: ProtoBus handlers are fully type-checked including:
  - Request and response type validation
  - Handler method name verification against proto definitions
  - Streaming vs unary handler signature enforcement

This establishes a robust, type-safe foundation for all gRPC communication between
the extension host and webview components.

* Remove commented out code in script

* Just call handlers directly
2025-07-21 18:40:28 -07:00
celestial-vault 58465d2e32 migrate showSaveDialog hostBridge (#5080)
* migrate showSaveDialog hostBridge

* rework proto type

* update proto type names
2025-07-21 18:20:52 -07:00
Toshii 35c0ced254 launch buttons (#5078) 2025-07-21 16:13:17 -07:00
Ara 63f3b40ef1 Change available Cerebras models + modify context window (#5076)
* Change context length for Cerebras Qwen 3 32b to 64k

* changeset

* changeset

* Create changeset

* Add Cerebras Qwen 3 235B a22b

* Change available Cerebras models

llama-3.3-70b
qwen-3-32b
qwen-3-235b-a22b

* Add changeset

---------

Co-authored-by: Kevin Taylor <kevin.taylor@cerebras.net>
Co-authored-by: Cline Evaluation <cline@example.com>
2025-07-21 14:03:45 -07:00
Bee 827d002ea6 Fix CLINE_ENVIRONMENT configuration not being passed to webview (#5029)
* Fix CLINE_ENVIRONMENT configuration not being passed to webview

## Problem

The CLINE_ENVIRONMENT configuration set in launch.json was not being properly passed to the webview, causing the webview to break when trying to access environment-specific configurations.

This resulted in:

Webview using incorrect API URLs (always defaulting to production)
Broken authentication flows in development/staging environments
Inconsistent behavior between the main extension and webview components

## Root Cause

The issue occurred because:

Duplicate Configuration Logic: The webview had its own separate config.ts file that was trying to read process.env.CLINE_ENVIRONMENT directly
Environment Variable Propagation: While Vite was configured to pass CLINE_ENVIRONMENT to the build process, the webview's runtime code couldn't access this environment variable properly
Configuration Mismatch: The main extension and webview were using different configuration sources, leading to inconsistent environment settings

* fix credit uri

* replace apiBaseUrl with appBaseUrl

* local option

* fallback changed to app

* change to app url

* merge fixes

---------

Co-authored-by: 0xtoshii <94262432+0xToshii@users.noreply.github.com>
2025-07-21 13:58:04 -07:00
celestial-vault c040db6d71 Fix options to buildApiHandler (#5064)
* add missing taskId to buildApiHandler

* remove console log
2025-07-21 13:56:32 -07:00
Sarah Fortune 8d5985c8fd refactor(hosts): Simplify the host provider interface for callers (#5057)
* refactor(hosts): Simplify the host provider interface for callers

- Streamline API to reduce complexity for consuming code
- Update all references across core, controller, and integration modules
- Consolidate provider patterns for easier usage
- Rename host-providers.ts to host-provider.ts

# Conflicts:
#	src/core/controller/index.ts
#	src/extension.ts
#	src/integrations/git/commit-message-generator.ts

* Add comment

* In the tests, reset the HostProvider to prevent it complaining that it is being reinitialized

* Update comment

* Fix imports
2025-07-21 12:20:50 -07:00
Bee c970b8030e Refactor: Git commit message generation as a module (#5031)
* Refactor: Git commit message generation as a module

Implement Git commit message generation as a module

Refactors the Git commit message generation functionality into a separate module for better organization and maintainability.

The changes include:

- Moving the commit message generation logic from `src/core/controller/index.ts` to a new module `src/integrations/git/commit-message-generator.ts`.
- Adding a command to abort commit message generation.
- Updating the `cline.generateGitCommitMessage` command to use the new module.
- Adding a context key to disable the generate commit message button when a commit is generating.

This refactoring improves the codebase by:

- Separating concerns: The commit message generation logic is now isolated in its own module, making it easier to understand and maintain.
- Improving testability: The new module can be tested independently of the controller.
- Promoting code reuse: The commit message generation logic can be reused in other parts of the application if needed.

* clean up

* changeset added
2025-07-21 10:43:14 -07:00
Sarah Fortune e7ce38bd85 Generate typed clients for the ProtoBus API (#5063) 2025-07-21 10:09:02 -07:00
Sarah Fortune 600a6e33ed Move duplicated code for loading the protobuf descriptor set into a shared util file. (#5059)
* Move duplicated code for laoding the protobuf descriptor set into a shared util file.

* Formatting

* Update comment
2025-07-20 17:57:22 -07:00
Sarah Fortune caf0d8aee2 Add better error handling the DiffViewProvider.saveDocument() (#5041) 2025-07-19 23:58:46 -07:00
celestial-vault ee33e84c48 Speed up E2E tests (#5045)
* cache vscode and playwright downloads

* remove extra logs

* change cache path to check for vscode

* empty commit

* use optimized e2e script
2025-07-19 21:57:36 -07:00
Sarah Fortune 280138b259 Improve HostBridge error handling and logging robustness (#5037) 2025-07-19 20:54:42 -07:00
Sarah Fortune 924f235c31 Change the script scripts/runclinecore.sh to only install and run cline-core (#5049)
-and not build the zip file.
2025-07-19 17:03:06 -07:00
Tomás Barreiro 06d5bc56bc Use --system-prompt-file to pass the system prompt to Claude Code (#5024)
* Pass the system prompt through a file when using Claude Code

* Support older versions and return better errors

* Add tests

* Add changeset

* Remove outdated docs

* Use a unique file name and clean the file

* Address comments
2025-07-19 12:41:21 -07:00
canvrno b1d82e163c Robust Checkpoints timeout, error handling (#5015)
* Diable checkpoints on tasks where the init timed out, fix settings link

* early warning message

* Added checkpointTrackerErrorMessage to HistoryItem

* Updated some comments related to checkpoints timeouts

* changeset, timer cleanup

* timer cleanup
2025-07-19 12:14:41 -07:00
celestial-vault 9f73cde5e9 fix stale state in model picker searchTerm (#5044) 2025-07-19 11:48:18 -07:00
Ara be2d416359 Updating Mintlify version (#5030)
* Updating Mintlify version

* clean up and ignore docs workspace for lint (#5032)

---------

Co-authored-by: Bee <68532117+abeatrix@users.noreply.github.com>
2025-07-18 19:29:28 -07:00
celestial-vault 42ffc30324 Separate plan act model settings (#4827)
* add provider handler options types and only pass those fields when building

* use separate fields for plan and act mode for ephemeral model settings

* post merge issues fixed: bedrock and cline api build handlers; current mode reading in controller/index.ts; adding a couple fields to welcomeView migration

* add in moonshotApiKey to settings-conversion after main merge

* fix type errors

* fix frontend types

* fix code after merge conflicts; switch groq provider to plan/act paradigm

* consolidate to Mode type

* remove promise resolve

* move huggingface provider into the new schema

* add new providers to migration function

* use normalizeApiConfiguration for settings menu provider value to avoid undefined state error
2025-07-18 14:14:31 -07:00
Sarah Fortune b0c67e9f83 Fix clean up part of the build-proto script (#5027) 2025-07-18 13:30:04 -07:00
Sarah Fortune fd366208a1 Fix the structure for the hosts package (#5020)
* Fix the structure for the hosts package.

Right now we support two host platforms: vscode using the internal host bridge service (inside the same process), and other platforms using the external host bridge (using gRPC over local sockets).

The structure of the two packages should mirror each other

```
hosts/
  vscode/
    VscodeDiffViewProvider
    VscodeWebViewProvider
    etc ...
  external/
    ExternalDiffViewProvider
    ExternalWebViewProvider
    etc ...
```

* Fix imports

* Fix imports

* Fix imports
2025-07-18 13:22:23 -07:00
Sarah Fortune 6c7bc58215 Move remaining platform specific code out of the diff view provider. (#5009)
* .

* Move the DecorationController into the hosts/vscode package.
2025-07-18 13:16:19 -07:00
Sarah Fortune f69a378ff4 Add eslint checks for more vscode API calls (#5023)
* Add eslint check for more vscode API calls

Add eslint checks to prevent vscode API calls from being reintroduced after they were switched to the host bridge.

The ones that are not enabled are not completely migrated, so they are not turned on because it would cause too many warnings, and make developers used to ignoring them.

* Update eslint-rules/no-direct-vscode-api.js

Co-authored-by: ellipsis-dev[bot] <65095814+ellipsis-dev[bot]@users.noreply.github.com>

* Update warning message text

* Move the check for if the file is being included in the linter check or not into its own function

---------

Co-authored-by: ellipsis-dev[bot] <65095814+ellipsis-dev[bot]@users.noreply.github.com>
2025-07-18 13:08:13 -07:00
Sarah Fortune 309e3bd85c Fix import in McpHub (#5021) 2025-07-18 11:59:07 -07:00
Daniel Campos Olivares eb6eb371e4 fix: Add documentation to nav menu (#5014) 2025-07-18 11:25:40 -07:00
Mohan Raj Rajamanickam 419e3e4677 fix: mcp servers are not started when disabled (#4501)
* fix: disabled servers should not be started

* refactor to dedupe

* add changeset

* Update moody-crabs-relate.md

* minor comment tweaks

* use unknown instead of any
2025-07-18 10:35:19 -07:00
Sarah Fortune e95eecd65f Just shut up already (#5011)
Don't display a notification when the MCP servers have updated.
2025-07-17 23:32:10 -07:00
Sarah Fortune e83e71cc6d Remove class that is unused, and other class that is totally commented out. (#5010) 2025-07-17 23:00:29 -07:00
Sarah Fortune a9e526e99b Move save() and getDocument() to the platform specific diff classes (#5008)
* Move logic to save the diff document and get the diff content to the platform specific diff view providers.

Add getDocumentText to the diff service.

The ExternalDiffViewProvider should be using its activeDiffEditorId (not the activeDiffEditor, which is the vscode Editor object)

* Check activeDiffEditorId

* Update src/integrations/editor/DiffViewProvider.ts

Co-authored-by: ellipsis-dev[bot] <65095814+ellipsis-dev[bot]@users.noreply.github.com>

* Use await with this.saveDocument()

* Remove test file

---------

Co-authored-by: ellipsis-dev[bot] <65095814+ellipsis-dev[bot]@users.noreply.github.com>
2025-07-17 18:06:54 -10:00
Sarah Fortune 72f16a8c30 Don't need to use Message.create({...}) with the host bridge (#4999)
* Use await when calling async function showMessage.

Use await when calling `windowClient.showMessage`, otherwise the caller doesn't wait for the request to complete and any exceptions are lost.

For the host bridge RPCs, you don't need to do `ShowMessageRequest.create({...})`, you can just pass the request directly like: `{...}. The Message.create() was needed for the ProtoBus because of the way it was implemented, it couldn't be type-checked by the compiled. It's not needed elsewhere.

* Dont use await, because it blocks until the message is dismissed

* Dont need `?.selectedOption`, the response cannot be null

* Dont use await
2025-07-17 20:15:42 -07:00
Toshii 1a3ec9f024 move environment setting to launch & publish (#5002)
* move env setting to launch & publish

* change env name

* Update webview-ui/vite.config.ts

Co-authored-by: Bee <68532117+abeatrix@users.noreply.github.com>

* update env location

---------

Co-authored-by: Bee <68532117+abeatrix@users.noreply.github.com>
2025-07-17 18:49:36 -07:00
Sarah Fortune b3fa3ad0d3 Add new RPCs to the host bridge diff service (#4997)
* Add truncate document to the hostbridge diff service.

# Conflicts:
#	src/standalone/ExternalDiffviewProvider.ts

* Fix typo

* Add host bridge rpcs for the diff service

* Add saveDocument and closeDiff to the host bridge.

* Formatting

* Use the host bridge in ExternalDiffviewProvider

* Make comments less verbose
2025-07-17 18:36:43 -07:00
github-actions[bot] 45241fcccf v3.19.7 Release Notes (#4983)
* changeset version bump

* Updating CHANGELOG.md format

* Update CHANGELOG.md for version 3.19.7

---------

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
Co-authored-by: github-actions <github-actions@github.com>
Co-authored-by: pashpashpash <nik@cline.bot>
2025-07-17 18:19:36 -07:00
pashpashpash 2a3f0e9418 Adding huggingface provider (#4952)
Co-authored-by: arafatkatze <arafat.da.khan@gmail.com>
2025-07-17 18:00:28 -07:00
Toshii 4334764903 remove warning (#5003) 2025-07-17 17:53:25 -07:00
Bee b3a10243b8 Unify error handling and display logic (#4984)
* Unify error handling and display

Several improvements to error handling and reporting within the Cline extension, focusing on providing more informative error messages to the user and improving telemetry data.

- **Error Handling:**
  - Introduces a `ClineError` class to encapsulate Cline-specific errors, providing structured data about the error (status code, request ID, etc.).
  - The `ErrorService` now creates and logs `ClineError` instances, improving error reporting to Sentry and telemetry.
  - Removes redundant error formatting logic from `src/core/task/utils.ts`, relying on the `ClineError` class for consistent error representation.
  - The Cline API handler now throws the raw error, allowing the `ClineError` class to handle the error formatting.

- **UI Improvements:**
  - Introduces new UI components (`ErrorRow`, `ErrorBlockTitle`) to display error messages in a more user-friendly format within the chat interface.
  - Displays credit limit errors with detailed information and a link to purchase credits.
  - Improves the display of rate limit errors and authentication errors.
  - Adds specific handling for PowerShell-related errors, providing a link to a troubleshooting guide.

- **Telemetry:**
  - Captures provider API errors using `ClineError` data, providing more detailed information about the error in telemetry reports.

- **Other Changes:**
  - Fixes an import path in `src/services/posthog/PostHogClientProvider.ts`.
  - Adds tests for the new UI components.
  - Adds `error` field to `ClineMessage` to transport `ClineError` instances to the webview.

These changes aim to provide a better user experience by displaying more informative error messages and improving the overall reliability of the Cline extension.

* include provider id

* includes model and provider id

* fix test

* return gracefully for empty response
2025-07-17 16:21:18 -07:00
Bee 8e95c136a6 Handle auth state changes in all extension windows (#4987)
* Handle auth state changes in all extension windows

Addresses an issue where authentication state changes (login/logout) were not being properly propagated across all extension windows.

The `onDidChange` event handler for `clineAccountId` secret now checks if the secret was added/updated (login) or removed (logout).

- If the secret exists, `restoreRefreshTokenAndRetrieveAuthInfo` is called to restore auth info (login from another window).
- If the secret is removed, `handleDeauth` is called to handle logout for all windows.

This ensures that all extension windows are kept in sync with the current authentication state.

* changeset
2025-07-17 15:40:30 -07:00
Daniel Campos Olivares 0b66faa1dd chore: Introduce SAP AI Core documentation (#4961)
* feat: Introduce SAP AI Core documentation

* fix: Markdown lint

Signed-off-by: Daniel Campos Olivares <dacamposol@gmail.com>

* fix: Typo

Signed-off-by: Daniel Campos Olivares <dacamposol@gmail.com>

---------

Signed-off-by: Daniel Campos Olivares <dacamposol@gmail.com>
2025-07-17 14:10:30 -07:00
Sarah Fortune 3d2dc1c5c4 Move platform specific code out of the DiffViewProvider and into the VscodeDiffViewProvider (#4980)
* Add a way to reset state for the platform specific diff view providers.

Add the abstract method `resetDiffView()` to the DiffViewProvider.

On Vscode it reset the active diff editor and decorations.

On External diff view providers, it reset the diff editor ID.

* Add a way to truncate the document to the platform specific diff view providers.

This is used when the last update is recieved to remove any content from the bottom of the document.

* Move `closeDiffView` to the platform specific diff view classes.

* Update comment

* Use await for async function

* Move setting the cursor position into replaceText
2025-07-17 12:35:48 -07:00
Andrei Eternal 028412579b Standalone Terminal Manager & remove other vscode-impls (now covered by host bridge) (#4993)
* Revert "experimental vscode impls & build-proto cleanup (#4493)"

This reverts commit f00c5f4ecc.

* leave terminal impls

* terminal manager switch for standalone

* Export standaloneTerminalManager to global

* clean up standalone terminal switch

---------

Co-authored-by: Andrei Edell <andrei@nugbase.com>
2025-07-17 12:11:45 -07:00
Sarah Fortune f04788c2ec Move the logic to scroll the diff editor window into the platform specific classes (#4977)
* Move the logic to scroll the diff editor window into the platform specific classes.

Move the current logic into the VscodeDiffViewProvider.

The ExternalDiffViewProvider will use the host bridge to scroll the editor tab. But for now it doesn't do anything.

* Add comment

* Remove log messages
2025-07-17 11:26:40 -07:00
Toshii 5fba39f886 move to simple config for setting env details of backend (#4978)
* backend env

* frontend env config

* rename config

* preview update

* separate mcp link

* mcp url updated

* config change to local

* webview config to local
2025-07-16 22:53:08 -07:00
Toshii 9a4e3655b3 remove import (#4981) 2025-07-16 19:40:43 -07:00
Tomás Barreiro b18ad77539 Improve Claude Code errors and create Docs (#4968)
* Create docs

* Improve the Claude Code error messages

* Replace with remote image
2025-07-16 18:22:01 -07:00
github-actions[bot] c50fce8101 v3.19.6 Release Notes (#4976)
* changeset version bump

* Updating CHANGELOG.md format

* Update CHANGELOG.md for version 3.19.6

* more modifications

---------

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
Co-authored-by: github-actions <github-actions@github.com>
Co-authored-by: pashpashpash <nik@cline.bot>
2025-07-16 17:21:22 -07:00
Sarah Fortune 47f84d7c2c Improve generated code that registers the vscode host bridge handlers. (#4972) 2025-07-16 17:14:37 -07:00
Ara 17c57162cd Refactoring terminal process logic and edge cases for simplicity (#4673)
* Refactor terminal output capture for better reliability

- Extract emitCurrentTerminalContents() as a private method for reusability
- Improve handling of commands with no/delayed output by capturing actual terminal contents instead of generic messages
- Add multiple fallback attempts (100ms, 1s, 3s) for terminals without shell integration
- Enhance timeout comments to clarify the 3-second delay purpose
- Add .tool-versions file (likely for version management)

* Refactor TerminalProcess run method into smaller functions

Split the monolithic run() method into focused helper methods for better
maintainability and readability. Extracted initialization, shell integration
execution, stream processing, and cleanup logic into separate private methods.
This improves code organization without changing functionality.

* Fixing the handling of echo commands and changing the wording of the terminal capture line

* fix: Embracing the ffmpeg for opus support
2025-07-16 16:33:01 -07:00
Toshii 0f1f3d84f7 add auto refresh to accounts page (#4901)
* add auto refresh to accounts page

* update

* 10 sec
2025-07-16 16:14:18 -07:00
Saoud Rizwan 0c5832b7a2 Fix kimi k2 provider sorting (#4975)
* Fix kimi2 provider sorting

* Create smart-flies-eat.md
2025-07-16 16:11:12 -07:00
celestial-vault 11c4c58ed3 update the current task's consecutiveAutoApprovedRequestsCount on max request change (#4955) 2025-07-16 16:07:01 -07:00
pashpashpash 27bf78ddbd swapping latest diff algo as default (#4412)
* swapping latest diff algo as default

* updating

---------

Co-authored-by: Cline Evaluation <cline@example.com>
2025-07-16 15:59:48 -07:00
pashpashpash c3161567d3 removing unneeded docs section (#4974) 2025-07-16 15:50:08 -07:00
pashpashpash 516d7bccc9 adding documentation workflow (#4598)
* adding documentation workflow

* Update .clinerules/workflows/writing-documentation.md

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>

* good example

* good example

* language

* Update writing-documentation.md

* Update writing-documentation.md

* Update writing-documentation.md

* Update writing-documentation.md

* Update writing-documentation.md

* Update writing-documentation.md

* Update writing-documentation.md

* Update writing-documentation.md

* Update writing-documentation.md

* Update writing-documentation.md

* Update writing-documentation.md

* Update writing-documentation.md

* Update writing-documentation.md

* Update writing-documentation.md

---------

Co-authored-by: Cline Evaluation <cline@example.com>
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
2025-07-16 15:37:24 -07:00
pashpashpash e91c8208a3 fix streamlit dashboard to be compatible with both old and new versions of streamlit (#4922) 2025-07-16 15:28:02 -07:00
Sarah Fortune 0fb40527c8 Add a script to run the standalone service. (#4966)
* Add a script to run the standalone service.

Remove spammy log statements.

* Add comment

* Fix some vscode stubs

* Update scripts/runstandalone.sh

Co-authored-by: ellipsis-dev[bot] <65095814+ellipsis-dev[bot]@users.noreply.github.com>

* Update scripts/runstandalone.sh

Co-authored-by: ellipsis-dev[bot] <65095814+ellipsis-dev[bot]@users.noreply.github.com>

* Update scripts/runstandalone.sh

Co-authored-by: ellipsis-dev[bot] <65095814+ellipsis-dev[bot]@users.noreply.github.com>

* Remove old script

* Add comment

* Add comment

---------

Co-authored-by: ellipsis-dev[bot] <65095814+ellipsis-dev[bot]@users.noreply.github.com>
2025-07-16 15:12:52 -07:00
Sarah Fortune 8a2e90084d Change the port numbers for the ProtoBus service and HostBridge. (#4969)
Don't use the default gRPC port number because it's more likely to already be in use.
2025-07-16 11:28:07 -07:00
Sarah Fortune 4c3384988c open-file calls vscode.workspace.openTextDocument but doesn't use the result. (#4960) 2025-07-16 03:01:25 -07:00
Daniel Steigman 8539bdce24 Upgraded telemetry to capture each message turn separately (#4954)
* refactor: Ugraded telemetry to capture each message turn seperatly

* go back to the correct posthog key oops
2025-07-15 22:49:35 -07:00
Bee cd7f3ef6a7 Disable recording webview click events (#4709)
* Disable recording webview click events

Introduces a temporary measure to disable the recording of webview click events in PostHog. This is achieved by adding a `temporaryDisabled` flag that, when true, prevents the initialization of PostHog and stops the identification of users.

This change is intended to be temporary and should be reverted in a future commit by removing the `temporaryDisabled` flag.

* Use separate PostHog config for development environment

This commit introduces a separate PostHog project for the development environment. This allows us to track events in the development environment without polluting the production data.

The `posthogConfig` now uses `posthogDevEnvConfig` when `process.env.isDev` is true, and `posthogProdConfig` otherwise.

* process.env.IS_DEV

* Update src/shared/services/config/posthog-config.ts

Co-authored-by: ellipsis-dev[bot] <65095814+ellipsis-dev[bot]@users.noreply.github.com>

* fix format

---------

Co-authored-by: Beatrix Woo <beatrix@cline.bot>
Co-authored-by: ellipsis-dev[bot] <65095814+ellipsis-dev[bot]@users.noreply.github.com>
2025-07-15 22:46:58 -07:00
github-actions[bot] 80fbcda03b v3.19.5 Release Notes (#4941)
-   Add Groq as a new API provider with support for all Groq models including Kimi-K2
-   Add user role display in organization UI for Cline account users
-   Fix message dialogs not showing option buttons properly
-   Fix authentication issues when using multiple VSCode windows
2025-07-15 21:49:06 -07:00
pashpashpash cef79e06db not showing request id when insufficient balance (#4953)
* not showing request id when insufficient balance

* whoops

* betterrr
2025-07-15 21:38:11 -07:00
Ara 5dddbef65c Adding Groq provider (#4943) 2025-07-15 19:47:56 -07:00
Bee b6f6358d4a Set up E2E tests with Playwright (#4721)
* Add Playwright E2E tests

Adding end-to-end (E2E) testing capabilities using Playwright. It also updates the `@vscode/test-electron` dependency.

The changes include:

- Adding Playwright as a dev dependency.
- Adding `e2e` and `e2e:build` scripts to `package.json` for running E2E tests.
- Adding `@playwright/test` to the list of dependencies.
- Updating `@vscode/test-electron` from `2.4.1` to `2.5.2`.
- Adding `test-results` to `.gitignore` to exclude test result files.

* wip: github workflow

Adding a new GitHub Actions workflow for running end-to-end (E2E) tests using Playwright. The workflow is triggered on push to the main branch, pull requests, and manual workflow dispatch.

The workflow defines a matrix strategy to run tests on different runners (Ubuntu and Windows) and shards. It also uploads Playwright recordings as artifacts if the tests fail.

* add @vscode/vsce as dev dep

* update workflow

* apply feedback

* fix test workflows

* add command palette helper

This commit improves the reliability and efficiency of the end-to-end tests by:

- Adding a delay to the "Let's go!" button click in the auth test to ensure the action is properly registered.
- Adding an expectation to ensure the "Get Started for Free" button is no longer visible after API key submission.
- Caching the "Use your own API key" button to avoid redundant lookups.
- Introducing a `runCommandPalette` helper function to streamline command execution within the VS Code environment.
- Disabling notifications before running the tests to prevent interference.

* state change

* set TEMP_PROFILE

* v3.18.7 Release Notes

* changeset version bump

* Updating CHANGELOG.md format

* Update CHANGELOG.md for version 3.18.7

---------

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
Co-authored-by: github-actions <github-actions@github.com>
Co-authored-by: pashpashpash <nik@cline.bot>

* Remove optimistic loading from organization dropdown (#4746)

* update build script to javascript

* fix match

* Add mode switching to chat test

* expected

---------

Co-authored-by: abeatrix <beatrix@cline.bot>
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
Co-authored-by: github-actions <github-actions@github.com>
Co-authored-by: pashpashpash <nik@cline.bot>
Co-authored-by: canvrno <46584286+canvrno@users.noreply.github.com>
2025-07-16 07:29:58 +05:30
Bee e607d02ab2 Fix: pass items to showMessage in VS Code host bridge (#4949) 2025-07-15 18:14:30 -07:00
454 changed files with 20668 additions and 32766 deletions
-5
View File
@@ -1,5 +0,0 @@
---
"claude-dev": patch
---
Display user role in organization UI
-5
View File
@@ -1,5 +0,0 @@
---
"claude-dev": patch
---
Remove state parameter from auth callback link that allows redirect to work when multiple windows are opened
+1 -1
View File
@@ -716,7 +716,7 @@ The Controller class manages MCP servers through the McpHub service:
class Controller {
mcpHub?: McpHub
constructor(context: vscode.ExtensionContext, outputChannel: vscode.OutputChannel, webviewProvider: WebviewProvider) {
constructor(context: vscode.ExtensionContext, webviewProvider: WebviewProvider) {
this.mcpHub = new McpHub(this)
}
@@ -0,0 +1,392 @@
# General writing guide
# How I want you to write
I'm gonna write something technical.
It's often less about the nitty-gritty details of the tech stuff and more about learning something new or getting a solution handed to me on a silver platter.
Look, when I read, I want something out of it. So when I write, I gotta remember that my readers want something too. This whole piece? It's about cluing in anyone who writes for me, or wants me to write for them, on how I see this whole writing product thing.
I'm gonna lay out a checklist of stuff I'd like to have. It'll make the whole writing gig a bit smoother, you know?
## Crafting Compelling Titles
I often come across titles like "How to do X with Y,Z technology." These don't excite me because X or Y are usually unfamiliar unless they're already well-known. Its rarely the dream to use X unless X is the dream.
My dream isnt to use instructor, its to do something valueble with the data it extracts
An effective title should:
- Evoke an emotional response
- Highlight someone's goal
- Offer a dream or aspiration
- Challenge or comment on a belief
- Address someone's problems
I believe it's more impactful to write about specific problems. If this approach works, you can replicate it across various scenarios rather than staying too general.
- Time management for everyone can be a 15$ ebook
- Time management for executives is a 2000$ workshop
Aim for titles that answer questions you think everyone is asking, or address thoughts people have but can't quite articulate.
Instead of "How I do something" or "How to do something," frame it from the reader's perspective with "How you can do something." This makes the title more engaging. Just make sure the difference is advisory if the content is subjective. “How I made a million dollars” might be more reasonable than “How to make a million dollars” since you are the subject and the goal might be to share your story in hopes of helping others.
This approach ultimately trains the reader to have a stronger emotional connection to your content.
- "How I do X"
- "How You Can do X"
Between these two titles, it's obvious which one resonates more emotionally.
You can take it further by adding specific conditions. For instance, you could target a particular audience or set a timeframe:
- How to set up Braintrust
- How to set up Braintrust in 5 minutes
## NO adjectiives
I want you to almost always avoid adjectives and try to use evidence instead. Instead of saying "production ready," you can write something like "scaling this to 100 servers or 1 million documents per second." Numbers like that will tell you exactly what the specificity of your product is. If you have to use adjectives rather than evidence, you are probably making something up.
There's no reason to say something like "blazingly fast" unless those things are already known phrases.
Instead, say "200 times faster" or "30% faster." A 30% improvement in recommendation system speed is insane.
There's a 200 times performance improvement because we went from one programming language to another. It's just something that's a little bit more expected and understandable.
Another test that I really like using recently is tracking whether or not the statements you make can be:
- Visualized
- Proven false
- Said only by you
If you can nail all three, the claim you make will be more likely to resonate with an audience because only you can say it.
Earlier this year, I had an example where I embedded all of Wikipedia in 17 minutes with 20 bucks, and it got half a million views. All we posted was a video of me kicking off the job, and then you can see all the log lines go through. You see the number of containers go from 1 out of 50 to 50 out of 50.
It was easy to visualize and could have been proven false by being unreproducible. Lastly, Modal is the only company that could do that in such an effortless way, which made it unique.
## Keep It Digestible
- Aim for 5-minute reads
- Write at a Grade 10 reading level
- Break up long paragraphs
- Use headers and bullet points
## Make It Scannable
- Bold key points
- Use subheadings every 3-4 paragraphs
- Include plenty of white space
- Add relevant examples
This structure works whether you're writing a tweet thread or a full blog post. The key is making complex ideas accessible.
# Guide to Writing Cline Documentation
## Some general principles for explaining features
If you're talking about a feature, it's helpful to start with a human-readable explanations that cover what the feature is in simple terms. Skip jargon and explain it like you're talking to someone who's never seen it before. This sets the foundation for everything that follows.
Combine location and usage into one flowing section. Tell users exactly where to find the feature and how to use it, but weave the instructions into natural prose with a good balance of bullet points, numbered lists, code examples (if applicable), mintlify components, and headers/subheaders. Users shouldn't have to jump between separate "where is it" and "how do I use it" sections.
Show the feature in action with real examples like actual files, workflows, or code. Users need to see concrete implementations, not just abstract descriptions. This is where understanding turns into practical knowledge.
When talking about a feature, include an inspiration section that sparks imagination. This section pushes people from understanding to action by showing them what becomes possible when they use this feature creatively. It's what separates good documentation from great documentation.
## Writing Principles That Actually Work
### Write for Action, Not Just Understanding
Documentation should motivate users to try things. Instead of just explaining how something works, focus on what users can accomplish with it. The inspiration section is crucial - it's what transforms passive readers into active users.
### Create a Natural Story Flow
It should feel like a conversation that naturally progresses from "what is this?" to "how do I use it?" to "here's a real example" to "imagine what you could do with this."
### Show Real Examples, Not Toy Demos
Provide actual workflow files, real code snippets, and concrete implementations that users can copy and adapt. Abstract examples don't help anyone - users want to see exactly what they'll be working with.
### Keep It Scannable But Not Fragmented
Write in prose that flows naturally when read completely, but structure it so users can quickly find specific information when they're troubleshooting. Avoid dense walls of text, but also avoid over-formatting with excessive bullet points and bold headers. There should be a nice visual heirarchy of balance between all elements, so you can quickly scan the page and find what you're looking for.
## Language and Tone Guidelines
Write clearly without dumbing things down. Use simple language when possible, but don't avoid technical terms that users need to know. Explain concepts in terms of what users can achieve rather than how the software works internally.
Make your writing conversational and encouraging. Phrases like "you can also try" or "when that works" feel more natural than rigid instructional language. Help users feel confident about trying new things.
Keep content concise and purposeful. Every sentence should either help users understand something or help them do something. If it doesn't serve one of those purposes, cut it.
Build in context and reasoning. Users want to understand why they're doing something, not just what to do. This builds confidence and helps them troubleshoot when things don't work exactly as expected.
## Practical Implementation
Structure each feature page consistently with the four-section approach, but let the content flow naturally within that structure. Use visual assets like videos and screenshots to complement the written content - they often communicate more effectively than paragraphs of description.
Link generously to related resources, examples, and deeper documentation. Users should never feel stuck or wonder where to go next. Maintain a repository of real examples that users can reference and adapt to their own needs.
The goal is documentation that feels more like helpful guidance from an experienced colleague than a technical manual. Users should finish reading feeling excited about what they can accomplish, not just informed about what the feature does.
## Balance Structure with Flexibility
While they discuss having consistent documentation structure, there's also mention of making content feel less rigid and more natural. The writing should follow guidelines while still feeling conversational and engaging.
## Bad examples
I personally hate this pattern of bullet point **Bold Text** colon and then more text:
<bad_example_of_writing>
#### macOS
1. **Switch to bash**: Go to Cline Settings → Terminal → Default Terminal Profile → Select "bash"
2. **Disable Oh-My-Zsh temporarily**: If using zsh, try `mv ~/.zshrc ~/.zshrc.backup` and restart VSCode
3. **Set environment**: Add to your shell config: `export TERM=xterm-256color`
#### Windows
1. **Use PowerShell 7**: Install from Microsoft Store, then select it in Cline settings
2. **Disable Windows ConPTY**: VSCode Settings → Terminal Integrated: Windows Enable Conpty → Uncheck
3. **Try Command Prompt**: Sometimes simpler is better - switch to cmd.exe
#### Linux
1. **Use bash**: Most reliable option - select in Cline settings
2. **Check permissions**: Ensure VSCode has terminal access permissions
3. **Disable custom prompts**: Comment out prompt customizations in `.bashrc`
</bad_example_of_writing>
We should instead strive to write beautiful docs that read well. We can use bullet points and numbered lists but it should read naturally and be delightful to look at hierachally when scanning through the doc. There should be a good balance between blocks of text, code snippets, paragraphs, numbered lists, and bullet points. When scanning the documentation visually, you should feel like you're adminiring a tasteful art piece.
<good_example_of_writing>
#### macOS
The most common fix is switching to bash. Navigate to Cline Settings → Terminal → Default Terminal Profile and select "bash" from the dropdown.
If you're still having issues, Oh-My-Zsh might be interfering with terminal integration. Try temporarily disabling it:
- Run `mv ~/.zshrc ~/.zshrc.backup`
- Restart VSCode
You can also add `export TERM=xterm-256color` to your shell configuration file to improve compatibility.
#### Windows
PowerShell 7 provides the most reliable experience. Install it from the Microsoft Store, then select it in your Cline settings.
Still seeing problems? Try these solutions:
- Disable Windows ConPTY: VSCode Settings → Terminal Integrated: Windows Enable Conpty → uncheck
- Switch to Command Prompt (cmd.exe) - sometimes simpler shells work better
#### Linux
Bash is your most dependable option. Select it in Cline settings if you haven't already.
Check these common issues:
- Ensure VSCode has terminal access permissions
- Temporarily comment out custom prompt configurations in your `.bashrc`
</good_example_of_writing>
This is much more natural to read. Writing this way creates a conversational flow, and bullet points are used idiomatically.
# Using Mintlify Components Idiomatically
Mintlify's custom components can transform basic documentation into engaging, scannable content that users actually want to read. Here's how to use them effectively.
## Visual Content with Frames
Videos and images should be wrapped in `<Frame>` components rather than using raw HTML or markdown. This creates consistent styling and proper responsive behavior.
For videos, embed them directly rather than linking externally. Users are much more likely to watch a 30-second demonstration than click through to another platform:
```jsx
<Frame>
<iframe
style={{ width: "100%", aspectRatio: "16/9" }}
src="https://www.youtube.com/embed/your-video-id"
title="Feature demonstration"
frameBorder="0"
allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share"
allowFullScreen
/>
</Frame>
```
Screenshots work similarly - the frame provides visual polish and consistency:
```jsx
<Frame>
<img src="/path/to/screenshot.png" alt="Descriptive alt text" />
</Frame>
```
## Cards for Navigation and Overview
Cards excel at creating scannable overviews that link to detailed documentation. They're perfect for feature listings, getting started guides, or any section where users need to choose their path.
Use the two-column layout for related features:
```jsx
<Columns cols={2}>
<Card title="Feature Name" icon="relevant-icon" href="/link/to/docs">
Brief description that explains what this feature does and why someone would use it.
</Card>
<Card title="Related Feature" icon="another-icon" href="/another/link">
Another concise explanation that helps users understand the value proposition.
</Card>
</Columns>
```
The key is writing card descriptions that are informative enough to help users decide whether to click through, but concise enough to scan quickly. Each card should answer "what does this do?" and "why would I need this?"
## Tips and Notes for Context
Use `<Tip>` components for helpful information that enhances the main content without cluttering it:
```jsx
<Tip>
Pro tip: You can combine multiple @ mentions in a single message to give Cline
comprehensive context about your issue.
</Tip>
```
`<Note>` components work well for important caveats or technical limitations:
```jsx
<Note>
Due to VS Code limitations, some features require specific settings to work properly.
</Note>
```
`<Info>` is also cool:
<Info>
**Quick Fix**: If you're experiencing terminal issues, try switching to a simpler shell like `bash` in the Cline settings.
This resolves 90% of terminal integration problems.
</Info>
**Never** fall into that awful **Bold Text** - description pattern that we specifically identified as bad writing. The content should flow naturally as connected thoughts rather than feeling like a templated AI response with forced formatting.
## When to Use Bullet Points and Numbered Lists Strategically
Bullet points serve functional purposes - use them for:
**Sequential actions or troubleshooting steps** where users need to follow a specific order:
1. Install the extension
2. Restart VSCode
3. Check the settings panel
**Lists of related options** where users need to choose one approach:
- Try PowerShell 7 for the most reliable experience
- Switch to Command Prompt if you're still having issues
- Use WSL Bash for Linux compatibility
**Quick reference items** that users might need to scan quickly when problem-solving.
**Improving Visual Hierarchy** when there's a wall of text - that's a good time to introduce bullet points or numbered lists.
Each bulleted item or numbered list should be a discrete action or piece of information that benefits from being visually separated. This is a key weapon you can employ when going for that artwork experience I mentioned earlier.
<good_example_of_bullet_points>
## Finding and Configuring Terminal Settings
You can access Cline's terminal settings by clicking the settings icon in the Cline sidebar, then navigating to the Terminal section. These settings control how Cline interacts with your system's terminal.
- The **Default Terminal Profile** setting determines which shell Cline uses for executing commands. If you're experiencing issues, this is usually the first thing to change. I personally keep this set to `bash` on all my systems because it's the most reliable option, even though I use `zsh` for my regular terminal work.
- **Shell Integration Timeout** controls how long Cline waits for the terminal to become ready. The default is 4 seconds, but if you have a heavy shell configuration (lots of plugins, slow startup scripts), you might need to increase this to 10 or even 15 seconds. I've found that WSL environments and SSH connections often need longer timeouts.
- The **Enable Aggressive Terminal Reuse** setting determines whether Cline tries to reuse existing terminals even when they're not in the correct directory. When this causes problems (commands running in the wrong directory, virtual environment issues), disabling it creates more terminal instances but ensures each command runs in a clean state.
- **Terminal Output Line Limit** sets how many lines of output Cline will read from commands. The default of 500 lines works for most cases, but you might need to adjust it. For verbose build outputs, increase it. For commands with progress bars that spam thousands of lines, decrease it to around 100 to avoid consuming too many tokens.
</good_example_of_bullet_points>
## Write Like a Human, Not an AI
Keep it short and direct. If you can say something in fewer words, do it. Long explanations often confuse more than they help.
Use normal sentence lengths. Mix short and long sentences naturally, like you would when talking to someone. Avoid those meandering compound sentences that go on forever.
Cut the corporate speak. Instead of "utilize," say "use." Instead of "in order to," just say "to." Write like you're explaining something to a colleague, not drafting a press release.
Don't over-explain obvious things. If users are reading documentation, they probably understand basic concepts. Respect their intelligence.
## Never use em dashes or emojis
That's pretty much it. Never use them. Only AI writes with em dashes or emojis.
# Anthropomorphizing Cline
When referring to Cline, always call him a "him" not an "it".
Bad example:
- When Cline cant execute commands or read their output, you lose access to one of its most powerful capabilities.
Good Example:
- When Cline cant execute commands or read their output, you lose access to one of his most powerful capabilities.
# Using "I" when sharing your workflow
Adding a personal touch goes a long way. There are great examples in the docs currently where I use "I" to share how I personally use cline, from dev to dev. It's a great technique.
# Crosslinking relevant documentation pages
Make sure you crosslink when you're done writing the docs. If there are relevant docs, just link to them.
# Brevity is the soul of wit
Don't ramble if you don't need to. Use bullet points and numbered lists. Keep things easy to read.
<bad_example>
When Cline can't execute commands or read their output, you lose access to one of his most powerful capabilities. Terminal integration problems are frustrating, but they're usually fixable with a few simple changes.
## The Most Common Problem: Shell Integration Issues
If you're seeing "Shell integration unavailable" or Cline isn't getting command output, the issue is almost always your shell configuration. Complex shell setups with custom prompts, plugins, and fancy configurations can interfere with VSCode's terminal integration.
**Switch to bash first.** This fixes the problem 90% of the time. Navigate to Cline Settings → Terminal → Default Terminal Profile and select "bash" from the dropdown. Restart VSCode after making this change.
Still having issues? Try increasing the shell integration timeout. Go to Cline Settings → Terminal → Shell Integration Timeout and change it from 4 seconds to 10 seconds. Heavy shell configurations need more time to initialize properly.
If commands are running in the wrong directories or you're seeing weird behavior, disable aggressive terminal reuse. In Cline Settings → Terminal, uncheck "Enable aggressive terminal reuse." This creates more terminal instances but ensures each command runs in a clean environment.
</bad_exaxmple>
The first part is total filler, useless to any serious developer. You can tell it's written by a non technical person that doesn't value clean, straightforward information.
<good_example>
## Shell Integration Issues
If you're seeing "Shell integration unavailable" or Cline can't read command output, your shell configuration is interfering with VSCode's terminal integration.
**Switch to bash first.** Go to Cline Settings → Terminal → Default Terminal Profile and select "bash." This fixes 90% of problems.
Still broken? Try these:
- Increase shell integration timeout to 10 seconds in Cline Settings → Terminal
- Disable "aggressive terminal reuse" if commands run in wrong directories
- Restart VSCode after making changes
</good_example>
The good version cuts straight to the problem and solution. No hand-holding, no emotional language about frustration, just the facts: what's wrong, how to fix it, what to try next. Respects that developers want information, not sympathy.RetryClaude can make mistakes. Please double-check responses.
ALWAYS consider your audience. And your audience is devs who don't want their time wasted. Give them the info. I cannot stress this enough. Use bullet points and numbered lists. Prose is good, but every word should actually mean something to the dev reading it.
# Lastly, before you start writing docs
1. Internalize these guidelines. I mean it.
2. Read `docs/docs.json` and get an understanding of the structure of the docs. This will come in handly at the end when you're doing a final pass so you can cross link to docs where relevant.
3. Read some good examples that I personally wrote and am proud of:
- docs/features/slash-commands/workflows.mdx
- docs/features/slash-commands/new-task.mdx
- docs/features/at-mentions/overview.mdx
- docs/features/drag-and-drop.mdx
4. If the user specifies any other instructions make sure you follow them.
-2
View File
@@ -20,8 +20,6 @@
"no-throw-literal": "warn",
"semi": "off",
"react-hooks/exhaustive-deps": "off",
"eslint-rules/no-protobuf-object-literals": "error",
"eslint-rules/no-grpc-client-object-literals": "error",
"eslint-rules/no-direct-vscode-api": "warn",
"no-restricted-syntax": [
"error",
+12 -18
View File
@@ -5,7 +5,7 @@ body:
- type: markdown
attributes:
value: |
**Important:** All bug reports must be reproducible using Claude 3.5 Sonnet. Cline uses complex prompts so less capable models may not work as expected.
**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:
@@ -24,7 +24,7 @@ body:
2.
3.
validations:
required: true
required: false
- type: textarea
id: logs
attributes:
@@ -39,20 +39,19 @@ body:
placeholder: "e.g., cline:anthropic/claude-3.7-sonnet, gemini:gemini-2.5-pro-exp-03-25"
validations:
required: true
- type: input
id: operating-system
attributes:
label: Operating System
description: What operating system are you using?
placeholder: "e.g., Windows 11, macOS Sonoma, Ubuntu 22.04"
validations:
required: true
- type: textarea
id: system-info
attributes:
label: System Info
description: What system information is relevant to the issue?
placeholder: "e.g., CPU: Intel Core i7-11700K, GPU: NVIDIA GeForce RTX 3070, RAM: 32GB DDR4"
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
@@ -63,8 +62,3 @@ body:
placeholder: "e.g., 1.2.3"
validations:
required: true
- type: textarea
id: additional-context
attributes:
label: Additional context
description: Add any other context about the problem here, such as screenshots or related issues.
@@ -1,116 +0,0 @@
name: 💡 Feature Proposal & Contribution
description: Propose a new feature or improvement, and optionally offer to implement feature as a contributor
labels: ["proposal"]
body:
- type: markdown
attributes:
value: |
**Feature Proposal & Contribution for Cline**
Thank you for proposing a feature or improvement for Cline! This template helps us understand the problem, evaluate the solution, and coordinate implementation.
**For detailed proposals:** Please provide comprehensive information to enable fast prioritization and discussion.
**For contribution offers:** You can indicate your willingness to implement the feature yourself.
Before submitting:
- Search existing [Issues](https://github.com/cline/cline/issues) and [Discussions](https://github.com/cline/cline/discussions) to avoid duplicates
- Read the [Contributing Guide](https://github.com/cline/cline/blob/main/CONTRIBUTING.md) if you plan to contribute
- Don't start implementation until the proposal is reviewed and approved
- type: textarea
id: problem-description
attributes:
label: What problem does this solve?
description: |
Describe the problem clearly from a user's point of view. Focus on why this matters, who it affects, and when it occurs.
✅ Good examples:
- "LLM provider returns 400 error when nearing the context window instead of truncating"
- "Submit button is invisible in dark mode"
- "Users can't easily share their Cline configurations with team members"
❌ Avoid vague descriptions:
- "Performance is bad"
- "UI needs work"
Your description should include:
- Who is affected?
- When does it happen?
- What's the current vs expected behavior?
- What is the impact?
placeholder: Be specific about the problem, who it affects, and the impact.
validations:
required: true
- type: textarea
id: proposed-solution
attributes:
label: What's the proposed solution?
description: |
Describe how the problem should be solved. Be specific about UX, system behavior, and any flows that would change.
✅ Good examples:
- "Add error handling immediately after attempting to create the llm stream and retry after manually truncating"
- "Update button styling to ensure contrast in all themes"
- "Add export/import functionality in settings with JSON format"
❌ Avoid vague solutions:
- "Improve performance"
- "Fix the bug"
Your solution should include:
- What exactly will change?
- How will users interact with it?
- What's the expected outcome?
placeholder: Describe the proposed changes and how they solve the problem.
validations:
required: false
- type: dropdown
id: contribution-intent
attributes:
label: Are you interested in implementing this?
description: Let us know if you'd like to contribute to this feature
options:
- "No, just proposing the idea"
- "Yes, I'd like to implement this myself"
- "Yes, I'd like to collaborate with others"
- "Maybe, depending on complexity and guidance"
validations:
required: false
- type: textarea
id: implementation-approach
attributes:
label: Implementation approach (if contributing)
description: |
**Only fill this out if you selected "Yes" above.**
How do you plan to implement this? Include:
- High-level technical approach
- Files/components that would be affected
- Any new dependencies required
- Potential challenges or considerations you've identified
This helps us provide better guidance and ensures alignment before you start coding.
placeholder: "My implementation approach would be..."
- type: checkboxes
id: checklist
attributes:
label: Proposal checklist
options:
- label: I've checked for existing issues or related proposals
required: true
- label: I understand this needs review before implementation can start
required: true
- type: checkboxes
id: contribution-checklist
attributes:
label: Contribution checklist (if contributing)
description: Only check these if you plan to contribute
options:
- label: I've read the [Contributing Guide](https://github.com/cline/cline/blob/main/CONTRIBUTING.md)
- label: I'm willing to make changes based on feedback
- label: I understand the code review process and requirements
+4 -5
View File
@@ -2,15 +2,14 @@
Thank you for contributing to Cline!
⚠️ Important: Before submitting this PR, please ensure you have:
- Opened an issue and discussed your proposed changes with the community / contributors
- Received approval from a core Cline contributor prior to proceeding with the implementation
- Link the associated issue in the "Related Issue" section
- For feature requests: Created a discussion in our Feature Requests discussions board https://github.com/cline/cline/discussions/categories/feature-requests and received approval from core maintainers before implementation
- For all changes: Link the associated issue/discussion in the "Related Issue" section below
Limited exceptions:
Small bug fixes, typo corrections, minor wording improvements, or simple type fixes that don't change functionality may be submitted directly.
Small bug fixes, typo corrections, minor wording improvements, or simple type fixes that don't change functionality may be submitted directly without prior discussion.
Why this requirement?
We deeply appreciate all community contributions - they are the core reason we're able to operate successfully and keep innovating! We welcome community input and want to make it as easy as possible for people to submit quality work. This process helps our core maintainers review new ideas faster and saves contributor time by ensuring you have the go-ahead before spending time on implementation.
We deeply appreciate all community contributions - they are essential to Cline's success! To ensure the best use of everyone's time and maintain project direction, we use our Feature Requests discussions board to gauge community interest and validate feature ideas before implementation begins. This helps us focus development efforts on features that will benefit the most users.
-->
### Related Issue
+108
View File
@@ -0,0 +1,108 @@
name: E2E Tests
on:
push:
branches:
- main
pull_request:
types: [opened, reopened, synchronize, ready_for_review]
workflow_dispatch:
concurrency:
group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }}
cancel-in-progress: true
jobs:
matrix_prep:
runs-on: ubuntu-latest
outputs:
matrix: ${{ steps.set-matrix.outputs.matrix }}
steps:
- id: set-matrix
run: |
echo 'matrix=[{"runner":"ubuntu"},{"runner":"windows"},{"runner":"macos"}]' >> $GITHUB_OUTPUT
e2e:
needs: matrix_prep
strategy:
fail-fast: false
matrix:
include: ${{ fromJson(needs.matrix_prep.outputs.matrix) }}
runs-on: ${{ matrix.runner }}-latest
timeout-minutes: 20
permissions:
id-token: write
contents: read
steps:
- uses: actions/checkout@v4
- name: Setup Node.js environment
uses: actions/setup-node@v4
with:
node-version: 22
# Cache root dependencies - only reuse if package-lock.json exactly matches
- name: Cache root dependencies
uses: actions/cache@v4
id: root-cache
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') }}
# Cache VS Code installation
- name: Cache VS Code
uses: actions/cache@v4
id: vscode-cache
with:
path: .vscode-test
key: vscode-${{ runner.os }}-stable-${{ hashFiles('.vscode-test.mjs', 'package.json') }}
restore-keys: |
vscode-${{ runner.os }}-stable-
# Cache Playwright browsers
- name: Cache Playwright browsers
uses: actions/cache@v4
id: playwright-cache
with:
path: |
~/.cache/ms-playwright
~/Library/Caches/ms-playwright
~/AppData/Local/ms-playwright
key: playwright-browsers-${{ runner.os }}-${{ hashFiles('package-lock.json') }}
restore-keys: |
playwright-browsers-${{ runner.os }}-
- name: Install root dependencies
if: steps.root-cache.outputs.cache-hit != 'true'
run: npm ci
- name: Install webview-ui dependencies
if: steps.webview-cache.outputs.cache-hit != 'true'
run: cd webview-ui && npm ci
- name: Install xvfb on Linux
if: matrix.runner == 'ubuntu'
run: sudo apt-get update && sudo apt-get install -y xvfb
# Run optimized E2E tests (eliminates redundant builds)
- name: Run E2E tests - Linux
if: matrix.runner == 'ubuntu'
run: xvfb-run -a npm run test:e2e:optimal
- name: Run E2E tests - Non-Linux
if: matrix.runner != 'ubuntu'
run: npm run test:e2e:optimal
- uses: actions/upload-artifact@v4
if: ${{ failure() }}
with:
name: playwright-recordings-${{ matrix.runner }}
path: |
test-results/playwright/
+1
View File
@@ -94,6 +94,7 @@ jobs:
env:
VSCE_PAT: ${{ secrets.VSCE_PAT }}
OVSX_PAT: ${{ secrets.OVSX_PAT }}
CLINE_ENVIRONMENT: production
run: |
# Required to generate the .vsix
vsce package --out "cline-${{ steps.get_version.outputs.version }}.vsix"
+6 -3
View File
@@ -68,6 +68,10 @@ jobs:
if: steps.webview-cache.outputs.cache-hit != 'true'
run: cd webview-ui && npm ci
- name: Install xvfb on Linux
if: runner.os == 'Linux'
run: sudo apt-get update && sudo apt-get install -y xvfb
- name: Install local modules on windows
if: runner.os == 'Windows' && steps.root-cache.outputs.cache-hit == 'true'
run: |
@@ -92,9 +96,8 @@ jobs:
- name: Build Tests and Extension
run: npm run pretest
# Unit Tests disabled due to module system conflicts between backend and webview-ui
# - name: Unit Tests
# run: npm run test:unit
- name: Unit Tests
run: npm run test:unit
# Run extension tests with coverage
- name: Extension Tests with Coverage
+8 -11
View File
@@ -15,6 +15,9 @@ pnpm-lock.yaml
.venv
.actrc
webview-ui/src/**/*.js
webview-ui/src/**/*.js.map
# Ignore coverage directories and files
coverage
# But don't ignore the coverage scripts in .github/scripts/
@@ -22,16 +25,10 @@ coverage
*evals.env
# Generated files
## Generated files ##
src/generated/
# Core
src/core/controller/*/methods.ts
src/core/controller/*/index.ts
src/core/controller/grpc-service-config.ts
# Shared
src/shared/proto/*.ts
src/shared/proto/host/*.ts
# Webview
src/shared/proto/
webview-ui/src/services/grpc-client.ts
# Host bridge
src/hosts/vscode/client/host-grpc-client.ts
# E2E Tests
test-results
+3 -1
View File
@@ -5,4 +5,6 @@ webview-ui/build/
package-lock.json
src/core/prompts/system.ts
src/core/prompts/model_prompts/claude4.ts
evals/
evals/
docs/
out/
+1 -1
View File
@@ -2,7 +2,7 @@ import { defineConfig } from "@vscode/test-cli"
import path from "path"
export default defineConfig({
files: "{out/**/*.test.js,src/**/*.test.js}",
files: "{out/**/*.test.js,src/**/*.test.js,!src/test/e2e/**/*.test.js,!out/src/test/e2e/**/*.test.js}",
mocha: {
ui: "bdd",
timeout: 20000, // Maximum time (in ms) that a test can run before failing
+34 -8
View File
@@ -6,7 +6,7 @@
"version": "0.2.0",
"configurations": [
{
"name": "Run Extension",
"name": "Run Extension (production)",
"type": "extensionHost",
"request": "launch",
"args": ["--extensionDevelopmentPath=${workspaceFolder}", "--disable-workspace-trust", "${workspaceFolder}"],
@@ -14,7 +14,34 @@
"preLaunchTask": "${defaultBuildTask}",
"env": {
"IS_DEV": "true",
"DEV_WORKSPACE_FOLDER": "${workspaceFolder}"
"DEV_WORKSPACE_FOLDER": "${workspaceFolder}",
"CLINE_ENVIRONMENT": "production"
}
},
{
"name": "Run Extension (staging)",
"type": "extensionHost",
"request": "launch",
"args": ["--extensionDevelopmentPath=${workspaceFolder}", "--disable-workspace-trust", "${workspaceFolder}"],
"outFiles": ["${workspaceFolder}/dist/**/*.js"],
"preLaunchTask": "${defaultBuildTask}",
"env": {
"IS_DEV": "true",
"DEV_WORKSPACE_FOLDER": "${workspaceFolder}",
"CLINE_ENVIRONMENT": "staging"
}
},
{
"name": "Run Extension (local)",
"type": "extensionHost",
"request": "launch",
"args": ["--extensionDevelopmentPath=${workspaceFolder}", "--disable-workspace-trust", "${workspaceFolder}"],
"outFiles": ["${workspaceFolder}/dist/**/*.js"],
"preLaunchTask": "${defaultBuildTask}",
"env": {
"IS_DEV": "true",
"DEV_WORKSPACE_FOLDER": "${workspaceFolder}",
"CLINE_ENVIRONMENT": "local"
}
},
{
@@ -37,13 +64,14 @@
"env": {
"IS_DEV": "true",
"TEMP_PROFILE": "true",
"DEV_WORKSPACE_FOLDER": "${workspaceFolder}"
"DEV_WORKSPACE_FOLDER": "${workspaceFolder}",
"CLINE_ENVIRONMENT": "production"
}
},
{
"type": "node",
"request": "launch",
"name": "Run Standalone Service",
"name": "Run cline-core service",
"skipFiles": ["<node_internals>/**"],
"sourceMaps": true,
"resolveSourceMapLocations": ["${workspaceFolder}/**", "!**/node_modules/**"],
@@ -54,11 +82,9 @@
// Turns on grpc debug log.
//"GRPC_TRACE": "all",
//"GRPC_VERBOSITY": "DEBUG",
"NODE_PATH": "${workspaceFolder}/dist-standalone/node_modules",
"HOST_BRIDGE_ADDRESS": "localhost:50052"
"NODE_PATH": "${workspaceFolder}/dist-standalone/node_modules"
},
"program": "standalone.js"
"program": "cline-core.js"
}
]
}
+5 -1
View File
@@ -9,5 +9,9 @@
"dist": true // set this to false to include "dist" folder in search results
},
// Turn off tsc task auto detection since we have the necessary tasks as npm scripts
"typescript.tsc.autoDetect": "off"
"typescript.tsc.autoDetect": "off",
// Protobuf settings
"protoc": {
"options": ["--proto_path=proto"]
}
}
+21 -4
View File
@@ -1,15 +1,16 @@
# Default
.vscode/**
.vscode-test/**
out/**
dist-standalone/**
node_modules/**
out/
dist-standalone/
node_modules/
src/**
standalone/**
.gitignore
.yarnrc
esbuild.js
**/tsconfig.json
vsc-extension-quickstart.md
tsconfig*.json
**/.eslintrc.json
**/*.map
**/*.ts
@@ -23,6 +24,17 @@ eslint-rules/**
.nvmrc
.gitattributes
.prettierignore
.husky/
.github/
eslint-rules/
old_docs/
evals/
.changie.yaml
.codespellrc
.mocharc.json
buf.yaml
.changeset/
.clinerules/
# Ignore all webview-ui files except the build directory (https://github.com/microsoft/vscode-webview-ui-toolkit-samples/blob/main/frameworks/hello-world-react-cra/.vscodeignore)
webview-ui/src/**
@@ -47,3 +59,8 @@ old_docs/**
# Include icons
!assets/icons/**
# Ignore E2E build files
e2e-build.js
e2e.vsix
test-results/
+609 -542
View File
File diff suppressed because it is too large Load Diff
+5 -8
View File
@@ -14,14 +14,11 @@ Bug reports help make Cline better for everyone! Before creating a new issue, pl
## Before Contributing
All contributions must begin with a GitHub Issue, unless the change is for small bug fixes, typo corrections, minor wording improvements, or simple type fixes that don't change functionality.
- **Check existing issues**: Search [GitHub Issues](https://github.com/cline/cline/issues).
- **Create an issue**: Use appropriate templates:
- **Contributions:** Use the "Contribution Request" template to propose what you'd like to work on.
- **Bugs:** "Bug Report" template for reporting issues.
- **Features:** "Detailed Feature Proposal" template for suggesting new features.
- **Wait for approval**: A core Cline contributor must approve your contribution request before you start implementation.
- **Claim issues**: Once approved, the issue will be assigned to you.
**For features and contributions**:
- First check the [Feature Requests discussions board](https://github.com/cline/cline/discussions/categories/feature-requests) for similar ideas
- If your idea is new, create a new feature request
- Wait for approval from core maintainers before starting implementation
- Once approved, feel free to begin working on a PR with the help of our community!
**PRs without approved issues may be closed.**
+1 -1
View File
@@ -51,7 +51,7 @@ Thanks to [Claude 3.7 Sonnet's agentic coding capabilities](https://www.anthrop
### Use any API and Model
Cline supports API providers like OpenRouter, Anthropic, OpenAI, Google Gemini, AWS Bedrock, Azure, GCP Vertex, and Cerebras. You can also configure any OpenAI compatible API, or use a local model through LM Studio/Ollama. If you're using OpenRouter, the extension fetches their latest model list, allowing you to use the newest models as soon as they're available.
Cline supports API providers like OpenRouter, Anthropic, OpenAI, Google Gemini, AWS Bedrock, Azure, GCP Vertex, Cerebras and Groq. You can also configure any OpenAI compatible API, or use a local model through LM Studio/Ollama. If you're using OpenRouter, the extension fetches their latest model list, allowing you to use the newest models as soon as they're available.
The extension also keeps track of total tokens and API usage cost for the entire task loop and individual requests, keeping you informed of spend every step of the way.
-1
View File
@@ -9,7 +9,6 @@ lint:
except: # Add exceptions for current patterns that contradict STANDARD settings
- RPC_PASCAL_CASE # rpcs are camel case (start with lowercase)
- PACKAGE_DIRECTORY_MATCH # the protos in the cline package are not in a dir named cline.
- RPC_REQUEST_RESPONSE_UNIQUE # request messages are not unique.
- RPC_REQUEST_STANDARD_NAME # request messages dont all end with Request
- RPC_RESPONSE_STANDARD_NAME # response messages dont all end with Response
+2 -2
View File
@@ -61,7 +61,6 @@
"getting-started/installing-cline",
"getting-started/installing-dev-essentials",
"getting-started/model-selection-guide",
"getting-started/our-favorite-tech-stack",
"getting-started/task-management",
"getting-started/understanding-context-management",
"getting-started/what-is-cline"
@@ -160,7 +159,8 @@
"provider-config/openai",
"provider-config/openai-compatible",
"provider-config/openrouter",
"provider-config/requesty"
"provider-config/requesty",
"provider-config/sap-aicore"
]
},
{
+13 -1
View File
@@ -11,7 +11,19 @@ You can create a rule by clicking the `+` button in the Rules tab. This will ope
Once you save the file:
- Your rule will be stored in the `.clinerules/` directory in your project (if it's a Workspace Rule)
- Or in the `Documents/Cline/Rules` directory (if it's a Global Rule).
- Or in the Global Rules directory (if it's a Global Rule):
### Global Rules Directory Location
The location of your Global Rules directory depends on your operating system:
| Operating System | Default Location | Notes |
|------------------|------------------|-------|
| **Windows** | `Documents\Cline\Rules` | Uses system Documents folder |
| **macOS** | `~/Documents/Cline/Rules` | Uses user Documents folder |
| **Linux/WSL** | `~/Documents/Cline/Rules` | May fall back to `~/Cline/Rules` on some systems |
> **Note for Linux/WSL users**: If you don't find your global rules in `~/Documents/Cline/Rules`, check `~/Cline/Rules` as the location may vary depending on your system configuration and whether the Documents directory exists.
You can also have Cline create a rule for you by using the [`/newrule` slash command](/features/slash-commands/new-rule) in the chat.
@@ -1,238 +0,0 @@
---
title: "Our Favorite Tech Stack"
description: "A curated list of our recommended technologies and tools for building modern web applications with Cline."
---
## Recommended Stack for New Cline Users (2025)
### Your Complete Development Environment
#### Development Tools
- **VS Code** - Your code editor, [download here](https://code.visualstudio.com/)
- **GitHub** - Where your code lives, [sign up here](https://github.com)
#### Frontend
- **Next.js 14+** - React framework with App Router
- **Tailwind CSS** - Beautiful styling without writing CSS
- **TypeScript** - JavaScript, but safer and smarter
#### Backend
- **Supabase** - Your complete backend solution, [sign up with GitHub](https://supabase.com)
- PostgreSQL database
- Authentication
- File storage
- Real-time updates
#### Deployment
- **Vercel** - Where your app runs, [sign up with GitHub](https://vercel.com)
- Automatic deployments from GitHub
- Preview deployments for testing
- Production-ready CDN
#### AI Development
Choose your AI assistant based on your needs:
| Model | Input Cost (per 1M tokens) | Output Cost (per 1M tokens) | Best For |
| ----------------- | -------------------------- | --------------------------- | ------------------------------ |
| Claude 3.5 Sonnet | $3.00 | $15.00 | Production apps, complex tasks |
| DeepSeek R1 | $1.00 | $3.00 | Budget-conscious production |
| DeepSeek V3 | $0.14 | $2.20 | Budget-conscious development |
#### Free Tier Benefits
**Vercel (Hobby)**
- 100 GB data transfer/month
- 100k serverless function invocations
- 100 MB deployment size
- Automatic HTTPS & CI/CD
**Supabase (Free)**
- 500 MB database storage
- 1 GB file storage
- 50k monthly active users
- 2M real-time messages/month
**GitHub (Free)**
- Unlimited public repositories
- GitHub Actions CI/CD
- Project management tools
- Collaboration features
### Getting Started
1. Install the development essentials:
- Follow our [Development Essentials Installation Guide](https://docs.cline.bot/getting-started/installing-dev-essentials)
2. Set up Cline's Memory Bank:
- Follow the [Memory Bank setup instructions](https://docs.cline.bot/prompting/cline-memory-bank)
- Create an empty `cline_docs` folder in your project root
- Create `projectBrief.md` in the `cline_docs` folder (see example below)
- Tell Cline to "initialize memory bank"
3. Add our recommended stack configuration:
- Create `.clinerules` file (see template below)
- Let Cline handle the rest!
#### Example Project Brief
```markdown
# Project Brief
## Overview
Building a [type of application] that will [main purpose].
## Core Features
- Feature 1
- Feature 2
- Feature 3
## Target Users
[Describe who will use your application]
## Technical Preferences (optional)
- Any specific technologies you want to use
- Any specific requirements or constraints
```
### .clinerules Template
```markdown
# Project Configuration
## Tech Stack
- Next.js 14+ with App Router
- Tailwind CSS for styling
- Supabase for backend
- Vercel for deployment
- GitHub for version control
## Project Structure
/src
/app # Next.js App Router pages
/components # React components
/lib # Utility functions
/types # TypeScript types
/supabase
/migrations # SQL migration files
/seed # Seed data files
/public # Static assets
## Database Migrations
SQL files in /supabase/migrations should:
- Use sequential numbering: 001, 002, etc.
- Include descriptive names
- Be reviewed by Cline before execution
Example: 001_create_users_table.sql
## Development Workflow
- Cline helps write and review code changes
- Vercel automatically deploys from main branch
- Database migrations reviewed by Cline before execution
## Security
DO NOT read or modify:
- .env files
- \*_/config/secrets._
- Any file containing API keys or credentials
```
### Learning Resources (2025)
Want to learn more about the technologies we're using? Here are some great resources:
#### Next.js and React
- [Official Learn Next.js Course](https://nextjs.org/learn) - Interactive tutorial
- [NextJS App Router: Modern Web Dev in 1 Hour](https://www.youtube.com/nextjs-modern) - Quick overview
- [Building Real-World Apps with Next.js](https://www.youtube.com/nextjs-real-world) - Practical examples
#### Supabase
- [Supabase From Scratch](https://www.udemy.com/supabase-scratch) - Comprehensive course
- [Official Quickstart Guides](https://supabase.com/docs/guides/getting-started)
- [Real-Time Apps with Next.js and Supabase](https://www.newline.co/courses/supabase-nextjs)
#### Tailwind CSS
- [Tailwind CSS Tutorial for Beginners](https://www.youtube.com/tailwind-2025)
- [Official Tailwind Documentation](https://tailwindcss.com/docs)
- Interactive course at [Scrimba Tailwind CSS Course](https://scrimba.com/learn/tailwind)
### Other Things to Know
#### Working with Git & GitHub
Git helps you track changes in your code and collaborate with others. Here are the essential commands you'll use:
**Daily Development**
```bash
# Save your changes (do this often!)
git add . # Stage all changed files
git commit -m "Add login page" # Save changes with a clear message
# Share your changes
git push origin main # Upload to GitHub
```
**Common Workflow**
1. **Start of day**: Get latest changes
```bash
git pull origin main # Download latest code
```
2. **During development**: Save work regularly
```bash
git add .
git commit -m "Clear message about changes"
```
3. **End of day**: Share your progress
```bash
git push origin main # Upload to GitHub
```
**Best Practices**
- Commit often with clear messages
- Pull before starting new work
- Push completed work to share with others
- Use `.gitignore` to avoid committing sensitive files
> **Tip**: Vercel automatically deploys when you push to main!
#### Environment Variables
- Store secrets in `.env.local` for development
- Add them to Vercel project settings for production
- Never commit `.env` files to Git
#### Getting Help
1. Use `/help` in Cline chat for immediate assistance
2. Check [Cline Documentation](https://docs.cline.bot)
3. Join our [Discord Community](https://discord.gg/cline)
4. Search GitHub issues for common problems
Remember: Cline is here to help at every step. Just ask for guidance or clarification when needed!
@@ -17,6 +17,7 @@ There are multiple places online to find MCP servers:
- [mcpservers.org](https://mcpservers.org/)
- [mcp.so](https://mcp.so/)
- [glama.ai/mcp/servers](https://glama.ai/mcp/servers)
- [mcp.composio.dev](https://mcp.composio.dev/)
These directories allow users to sort the servers by various criteria such as downloads, date, stars, and use case. Each entry provides information such as features, tools, and configuration instructions.
+4 -4
View File
@@ -4,17 +4,17 @@ title: "Telemetry"
### Overview
To help make Cline better for everyone, we collect anonymous usage data that helps us understand how developers are using our open-source AI coding agent. This feedback loop is crucial for improving Cline's capabilities and user experience.
To help make Cline better for everyone, we collect usage data that helps us understand how developers are using our open-source AI coding agent. This feedback loop is crucial for improving Cline's capabilities and user experience.
We use PostHog, an open-source analytics platform, for data collection and analysis. Our telemetry implementation is fully transparent - you can review the [source code](https://github.com/cline/cline/blob/main/src/services/posthog/telemetry/TelemetryService.ts) to see exactly what we track.
### Tracking Policy
Privacy is our priority. All collected data is anonymized before being sent to PostHog, with no personally identifiable information (PII) included. Your code, prompts, and conversation content always remain private and are never collected.
Privacy is our priority. By default, all collected data is anonymized. If you log in with a Cline account, your telemetry data will be associated with your account to help us improve the product and provide better support when you encounter issues. Your code, prompts, and conversation content always remain private and are never collected.
### What We Track
We collect basic anonymous usage data including:
We collect basic usage data including:
**Task Interactions:** When tasks start and finish, conversation flow (without content)\
**Mode and Tool Usage:** Switches between plan/act modes, which tools are being used\
@@ -28,7 +28,7 @@ For complete transparency, you can inspect our [telemetry implementation](https:
Telemetry in Cline is entirely optional:
- When you update or install our VS Code extension, you'll see a message about our anonymous telemetry
- When you update or install our VS Code extension, you'll see a message about our telemetry
- You can change your preference anytime in settings
Cline also respects VS Code's global telemetry settings. If you've disabled telemetry at the VS Code level, Cline's telemetry will automatically be disabled as well.
-10118
View File
File diff suppressed because it is too large Load Diff
+4 -2
View File
@@ -4,13 +4,15 @@
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"dev": "mintlify dev"
"dev": "mintlify dev",
"check": "mintlify broken-links",
"rename": "mintlify rename"
},
"keywords": [],
"author": "",
"license": "ISC",
"description": "",
"dependencies": {
"mintlify": "^4.0.538"
"mintlify": "^4.2.23"
}
}
+7
View File
@@ -32,6 +32,13 @@ First, you'll need to install and authenticate Claude Code on your system:
/>
</Frame>
<br />
<Accordion title="Windows Setup">
Anthropic introduced full support for Claude Code on Windows. Follow the [instructions on how to set up Claude Code
normally](#setup) and make sure you have the latest Claude Code and Cline versions.
</Accordion>
### Finding your Claude Code path
If you're not sure where Claude Code is installed:
+39
View File
@@ -0,0 +1,39 @@
---
title: "SAP AI Core"
description: "Learn how to configure and use LLM models from Generative AI Hub in SAP AI Core with Cline."
---
SAP AI Core and the generative AI hub help you to integrate LLMs and AI into new business processes in a cost-efficient manner.
**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.
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.
3. **Copy the Service Binding:** Copy the service binding values.
### Supported Models
SAP AI Core supports a large and growing number of models.
Refer to the [Generative AI Hub Supported Models page](https://me.sap.com/notes/3437766) for the complete and up-to-date list.
### Configuration in Cline
1. **Open Cline Settings:** Click the settings icon (⚙️) in the Cline panel.
2. **Select Provider:** Choose "SAP AI Core" from the "API Provider" dropdown.
3. **Enter Client Id:** Add the `.clientid` field from the service binding into the "AI Core Client Id" field.
4. **Enter Client Secret:** Add the `.clientsecret` field from the service binding into the "AI Core Client Secret" field.
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.
### Tips and Notes
- **Model Selection:** SAP AI Core offers a wide range of models. You won't be able to use the model, even if selected, if a deployment doesn't exist in the provided resource group.
@@ -244,13 +244,60 @@ Recent macOS versions have stricter terminal permissions:
### Windows Issues
#### PowerShell Execution Policy
If you're using Windows and still experiencing issues with shell integration after trying the previous steps, it's recommended you use Git Bash (or PowerShell).
If commands fail silently:
### Git Bash
Git Bash is a terminal emulator that provides a Unix-like command line experience on Windows. To use Git Bash, you need to:
1. Download and run the Git for Windows installer from [https://git-scm.com/downloads/win](https://git-scm.com/downloads/win)
2. Quit and re-open VSCode
3. Press `Ctrl + Shift + P` to open the Command Palette
4. Type "Terminal: Select Default Profile" and choose it
5. Select "Git Bash"
### PowerShell
If you'd still like to use PowerShell, make sure you're using an updated version (at least v7+).
- Check your current PowerShell version by running: `$PSVersionTable.PSVersion`
- If your version is below 7, [update PowerShell](https://learn.microsoft.com/en-us/powershell/scripting/whats-new/migrating-from-windows-powershell-51-to-powershell-7?view=powershell-7.4#installing-powershell-7).
You may also need to adjust your PowerShell execution policy. By default, PowerShell restricts script execution for security reasons.
#### Understanding PowerShell Execution Policies
PowerShell uses execution policies to determine which scripts can run on your system. Here are the most common policies:
- `Restricted`: No PowerShell scripts can run. This is the default setting.
- `AllSigned`: All scripts, including local ones, must be signed by a trusted publisher.
- `RemoteSigned`: Scripts created locally can run, but scripts downloaded from the internet must be signed.
- `Unrestricted`: No restrictions. Any script can run, though you will be warned before running internet-downloaded scripts.
For development work in VSCode, the `RemoteSigned` policy is generally recommended. It allows locally created scripts to run without restrictions while maintaining security for downloaded scripts. To learn more about PowerShell execution policies and understand the security implications of changing them, visit Microsoft's documentation: [About Execution Policies](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_execution_policies).
#### Steps to Change the Execution Policy
1. Open PowerShell as an Administrator: Press `Win + X` and select "Windows PowerShell (Administrator)" or "Windows Terminal (Administrator)".
2. Check Current Execution Policy by running this command:
```powershell
Get-ExecutionPolicy
```
- If the output is already `RemoteSigned`, `Unrestricted`, or `Bypass`, you likely don't need to change your execution policy. These policies should allow shell integration to work.
- If the output is `Restricted` or `AllSigned`, you may need to change your policy to enable shell integration.
3. Change the Execution Policy by running the following command:
```powershell
Set-ExecutionPolicy RemoteSigned -Scope CurrentUser
```
- This sets the policy to `RemoteSigned` for the current user only, which is safer than changing it system-wide.
4. Confirm the Change by typing `Y` and pressing Enter when prompted.
5. Verify the Policy Change by running `Get-ExecutionPolicy` again to confirm the new setting.
6. Restart VSCode and try the shell integration again.
```powershell
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser
```
#### WSL Integration
+24 -8
View File
@@ -1,10 +1,15 @@
const esbuild = require("esbuild")
const fs = require("fs")
const path = require("path")
import fs from "node:fs"
import * as esbuild from "esbuild"
import path from "node:path"
import { fileURLToPath } from "node:url"
const __filename = fileURLToPath(import.meta.url)
const __dirname = path.dirname(__filename)
const production = process.argv.includes("--production")
const watch = process.argv.includes("--watch")
const standalone = process.argv.includes("--standalone")
const e2eBuild = process.argv.includes("--e2e-build")
const destDir = standalone ? "dist-standalone" : "dist"
/**
@@ -126,10 +131,8 @@ const baseConfig = {
sourcemap: !production,
logLevel: "silent",
define: production
? {
"process.env.IS_DEV": JSON.stringify(!production),
}
: undefined,
? { "import.meta.url": "_importMetaUrl", "process.env.IS_DEV": JSON.stringify(!production) }
: { "import.meta.url": "_importMetaUrl" },
tsconfig: path.resolve(__dirname, "tsconfig.json"),
plugins: [
copyWasmFiles,
@@ -140,6 +143,9 @@ const baseConfig = {
format: "cjs",
sourcesContent: false,
platform: "node",
banner: {
js: "const _importMetaUrl=require('url').pathToFileURL(__filename)",
},
}
// Extension-specific configuration
@@ -160,8 +166,18 @@ const standaloneConfig = {
external: ["vscode", "@grpc/reflection", "grpc-health-check"],
}
// E2E build script configuration
const e2eBuildConfig = {
...baseConfig,
entryPoints: ["src/test/e2e/utils/build.ts"],
outfile: `${destDir}/e2e-build.js`,
external: ["@vscode/test-electron", "execa"],
sourcemap: false,
plugins: [aliasResolverPlugin, esbuildProblemMatcherPlugin],
}
async function main() {
const config = standalone ? standaloneConfig : extensionConfig
const config = standalone ? standaloneConfig : e2eBuild ? e2eBuildConfig : extensionConfig
const extensionCtx = await esbuild.context(config)
if (watch) {
await extensionCtx.watch()
@@ -85,7 +85,7 @@ directApiRuleTester.run("no-direct-vscode-api", noDirectVscodeApiRule, {
filename: "workspace.ts",
errors: [
{
messageId: "useHostBridge",
messageId: "useHostBridgeWorkspace",
},
],
},
@@ -1,174 +0,0 @@
const { RuleTester: GrpcRuleTester } = require("eslint")
const grpcRule = require("../no-grpc-client-object-literals")
const grpcRuleTester = new GrpcRuleTester({
parser: require.resolve("@typescript-eslint/parser"),
parserOptions: {
ecmaVersion: 2020,
sourceType: "module",
ecmaFeatures: {
jsx: true,
},
},
})
grpcRuleTester.run("no-grpc-client-object-literals", grpcRule, {
valid: [
// Valid case: Using .create() method with gRPC client
{
code: `
import { TogglePlanActModeRequest } from '@shared/proto/state';
import { StateServiceClient } from '../services/grpc-client';
StateServiceClient.togglePlanActMode(
TogglePlanActModeRequest.create({
chatSettings: {
mode: PlanActMode.PLAN,
preferredLanguage: 'en',
},
})
);
`,
},
// Valid case: Using .fromPartial() method with gRPC client
{
code: `
import { TogglePlanActModeRequest, ChatSettings } from '@shared/proto/state';
import { StateServiceClient } from '../services/grpc-client';
const chatSettings = ChatSettings.fromPartial({
mode: PlanActMode.PLAN,
preferredLanguage: 'en',
});
StateServiceClient.togglePlanActMode(
TogglePlanActModeRequest.create({
chatSettings: chatSettings,
})
);
`,
},
// Valid case: Regular function call with object literal (not a gRPC client)
{
code: `
function processData(data) {
console.log(data);
}
processData({
id: 123,
name: 'test',
});
`,
},
// Valid case: Using proper nested protobuf objects
{
code: `
import { TogglePlanActModeRequest, ChatSettings } from '@shared/proto/state';
import { StateServiceClient } from '../services/grpc-client';
// Using proper nested protobuf objects
const chatSettings = ChatSettings.create({
mode: 0,
preferredLanguage: 'en',
});
const request = TogglePlanActModeRequest.create({
chatSettings: chatSettings,
});
StateServiceClient.togglePlanActMode(request);
`,
},
// Valid case: Object literal in second parameter (should not be checked)
{
code: `
import { StateSubscribeRequest } from '@shared/proto/state';
import { StateServiceClient } from '../services/grpc-client';
const request = StateSubscribeRequest.create({
topics: ['apiConfig', 'tasks']
});
// Second parameter is an object literal but should not trigger the rule
StateServiceClient.subscribe(request, {
metadata: {
userId: 123,
sessionId: "abc-123"
}
});
`,
},
],
invalid: [
// Invalid case: Using object literal directly with gRPC client
{
code: `
import { StateServiceClient } from '../services/grpc-client';
StateServiceClient.togglePlanActMode({
chatSettings: {
mode: 0,
preferredLanguage: 'en',
},
});
`,
errors: [{ messageId: "useProtobufMethod" }],
},
// Invalid case: Using object literal with nested properties
{
code: `
import { ChatSettings } from '@shared/proto/state';
import { StateServiceClient } from '../services/grpc-client';
const chatSettings = ChatSettings.create({
mode: 0,
preferredLanguage: 'en',
});
StateServiceClient.togglePlanActMode({
chatSettings: {
mode: 1,
preferredLanguage: 'fr',
},
});
`,
errors: [{ messageId: "useProtobufMethod" }],
},
// Invalid case: Nested object literal in protobuf create method
{
code: `
import { TogglePlanActModeRequest, ChatSettings } from '@shared/proto/state';
import { StateServiceClient } from '../services/grpc-client';
// Using nested object literal instead of ChatSettings.create()
const request = TogglePlanActModeRequest.create({
chatSettings: {
mode: 0,
preferredLanguage: 'en',
},
});
StateServiceClient.togglePlanActMode(request);
`,
errors: [{ messageId: "useProtobufMethod" }],
},
// Invalid case: Object literal as first parameter to subscribe method
{
code: `
import { StateServiceClient } from '../services/grpc-client';
// First parameter is an object literal, which should trigger the rule
StateServiceClient.subscribe({
topics: ['apiConfig', 'tasks']
}, {
metadata: {
userId: 123,
sessionId: "abc-123"
}
});
`,
errors: [{ messageId: "useProtobufMethod" }],
},
],
})
@@ -1,214 +0,0 @@
const { RuleTester } = require("eslint")
const rule = require("../no-protobuf-object-literals")
const ruleTester = new RuleTester({
parser: require.resolve("@typescript-eslint/parser"),
parserOptions: {
ecmaVersion: 2020,
sourceType: "module",
ecmaFeatures: {
jsx: true,
},
},
})
ruleTester.run("no-protobuf-object-literals", rule, {
valid: [
// Valid case: Using .create() method
{
code: `
import { State } from '@shared/proto/state';
const state = State.create({
stateJson: '{"apiConfig":{"provider":"anthropic","model":"claude-3-haiku"}}'
});
`,
},
// Valid case: Using .fromPartial() method
{
code: `
import { ChatSettings } from '@shared/proto/state';
const settings = ChatSettings.fromPartial({
mode: 0,
preferredLanguage: 'en',
openAiReasoningEffort: 'thorough'
});
`,
},
// Valid case: Object literal not used with protobuf type
{
code: `
interface MyInterface {
id: number;
name: string;
}
const obj: MyInterface = {
id: 123,
name: 'test'
};
`,
},
// Valid case: Using object literal for non-protobuf import
{
code: `
import { SomeType } from '@some/other/package';
const obj: SomeType = {
id: 123,
name: 'test'
};
`,
},
// Valid case: Regular function call with object literal (should not be flagged)
{
code: `
import { State } from '@shared/proto/state';
// This should not be flagged because it's a regular function call
// not directly tied to a protobuf type
process({
id: 123,
name: 'test',
data: { nested: true }
});
`,
},
],
invalid: [
// Invalid case: Using object literal with imported protobuf type
{
code: `
import { State } from '@shared/proto/state';
const state: State = {
stateJson: '{"apiConfig":{"provider":"anthropic","model":"claude-3-haiku"}}'
};
`,
output: `
import { State } from '@shared/proto/state';
const state: State = State.create({
stateJson: '{"apiConfig":{"provider":"anthropic","model":"claude-3-haiku"}}'
});
`,
errors: [{ messageId: "useProtobufMethod" }],
},
// Invalid case: Using object literal with namespaced protobuf type
{
code: `
import * as stateProto from '@shared/proto/state';
const state: stateProto.State = {
stateJson: '{"apiConfig":{"provider":"anthropic","model":"claude-3-haiku"}}'
};
`,
output: `
import * as stateProto from '@shared/proto/state';
const state: stateProto.State = stateProto.State.create({
stateJson: '{"apiConfig":{"provider":"anthropic","model":"claude-3-haiku"}}'
});
`,
errors: [{ messageId: "useProtobufMethodGeneric" }],
},
// Invalid case: Using object literal in a return statement (with protobuf return type)
{
code: `
import { ChatSettings } from '@shared/proto/state';
function createSettings(): ChatSettings {
return {
mode: 0,
preferredLanguage: 'en',
openAiReasoningEffort: 'thorough'
};
}
`,
output: `
import { ChatSettings } from '@shared/proto/state';
function createSettings(): ChatSettings {
return ChatSettings.create({
mode: 0,
preferredLanguage: 'en',
openAiReasoningEffort: 'thorough'
});
}
`,
errors: [{ messageId: "useProtobufMethod" }],
},
// Invalid case: Using object literal in a function parameter (with protobuf types imported)
{
code: `
import { ChatContent } from '@shared/proto/state';
function processContent(content: ChatContent) {
// process the content
}
processContent({
message: 'Hello, this is a test message',
images: ['image1.png', 'image2.jpg'],
files: ['file1.txt', 'file2.pdf']
});
`,
output: `
import { ChatContent } from '@shared/proto/state';
function processContent(content: ChatContent) {
// process the content
}
processContent(ChatContent.create({
message: 'Hello, this is a test message',
images: ['image1.png', 'image2.jpg'],
files: ['file1.txt', 'file2.pdf']
}));
`,
errors: [{ messageId: "useProtobufMethodGeneric" }],
},
// Invalid case: Using object literal in assignment expression
{
code: `
import { State } from '@shared/proto/state';
let state: State;
state = {
stateJson: '{"apiConfig":{"provider":"anthropic","model":"claude-3-haiku"}}'
};
`,
output: `
import { State } from '@shared/proto/state';
let state: State;
state = State.create({
stateJson: '{"apiConfig":{"provider":"anthropic","model":"claude-3-haiku"}}'
});
`,
errors: [{ messageId: "useProtobufMethod" }],
},
// Test with custom protobufPackages option
{
code: `
import { CustomProto } from 'custom/proto/package';
const obj: CustomProto = {
field1: 'value',
field2: 123
};
`,
output: `
import { CustomProto } from 'custom/proto/package';
const obj: CustomProto = CustomProto.create({
field1: 'value',
field2: 123
});
`,
options: [{ protobufPackages: ["custom/proto"] }],
errors: [{ messageId: "useProtobufMethod" }],
},
],
})
-6
View File
@@ -1,20 +1,14 @@
// eslint-rules/index.js
const noProtobufObjectLiterals = require("./no-protobuf-object-literals")
const noGrpcClientObjectLiterals = require("./no-grpc-client-object-literals")
const noDirectVscodeApi = require("./no-direct-vscode-api")
module.exports = {
rules: {
"no-protobuf-object-literals": noProtobufObjectLiterals,
"no-grpc-client-object-literals": noGrpcClientObjectLiterals,
"no-direct-vscode-api": noDirectVscodeApi,
},
configs: {
recommended: {
plugins: ["local"],
rules: {
"local/no-protobuf-object-literals": "error",
"local/no-grpc-client-object-literals": "error",
"local/no-direct-vscode-api": "warn",
},
},
+70 -17
View File
@@ -11,8 +11,11 @@ const disallowedApis = {
"vscode.workspace.fs.stat": {
messageId: "useFsUtils",
},
"vscode.workspace.fs.writeFile": {
messageId: "useFsUtils",
},
"vscode.workspace.workspaceFolders": {
messageId: "useHostBridge",
messageId: "useHostBridgeWorkspace",
},
"vscode.workspace.asRelativePath": {
messageId: "usePathUtils",
@@ -20,6 +23,33 @@ const disallowedApis = {
"vscode.workspace.getWorkspaceFolder": {
messageId: "usePathUtils",
},
"vscode.window.showTextDocument": {
messageId: "useHostBridge",
},
"vscode.workspace.applyEdit": {
messageId: "useHostBridge",
},
"vscode.window.onDidChangeActiveTextEditor": {
messageId: "useHostBridge",
},
"vscode.env.openExternal": {
messageId: "useUtils",
},
// "vscode.window.showWarningMessage": {
// messageId: "useHostBridgeShowMessage",
// },
"vscode.window.showOpenDialog": {
messageId: "useHostBridgeShowMessage",
},
"vscode.window.showErrorMessage": {
messageId: "useHostBridgeShowMessage",
},
// "vscode.window.showInformationMessage": {
// messageId: "useHostBridgeShowMessage",
// },
"vscode.workspace.findFiles": {
messageId: "useNative",
},
}
module.exports = createRule({
@@ -37,16 +67,32 @@ module.exports = createRule({
"Example: AccountServiceClient.methodName(RequestType.create({...})) instead of vscode.postMessage({type: '...'}).\n" +
"Found: {{code}}",
useFsUtils:
"Use utilities in @/utils/fs instead of vscode.workspace.fs.stat.\n" +
"Use utilities in @/utils/fs instead of vscode.workspace.fs\n" +
"Example: import { isDirectory } from '@/utils/fs' or use the file system methods from the host bridge provider.\n" +
"Found: {{code}}",
useHostBridge:
"Use getHostBridgeProvider().workspaceClient.getWorkspacePaths({}) instead of vscode.workspace.workspaceFolders.\n" +
usePathUtils:
"Use path utilities from @/utils/path instead of VSCode workspace path methods.\n" +
"This provides consistent path handling across different environments.\n" +
"Found: {{code}}",
useHostBridgeWorkspace:
"Use HostProvider.workspace.getWorkspacePaths({}) instead of vscode.workspace.workspaceFolders.\n" +
"This provides a consistent abstraction across VSCode and standalone environments.\n" +
"Found: {{code}}",
usePathUtils:
"Use path utilities from @/utils/path instead of direct VSCode workspace path methods.\n" +
"This provides consistent path handling across different environments.\n" +
useHostBridgeShowMessage:
"Use HostProvider.window.showMessage instead of the vscode.window.showMessage.\n" +
"This provides a consistent abstraction across VSCode and standalone environments.\n" +
"Found: {{code}}",
useHostBridge:
"Use the host bridge instead of calling vscode APIs directly.\n" +
"This provides a consistent abstraction across VSCode and standalone environments.\n" +
"Found: {{code}}",
useUtils:
"Use utilities in @/utils instead of calling vscode APIs directly.\n" +
"This provides a consistent abstraction across VSCode and standalone environments.\n" +
"Found: {{code}}",
useNative:
"Use a native Javascript API instead of calling the vscode API.\n" +
"This provides a consistent abstraction across VSCode and standalone environments.\n" +
"Found: {{code}}",
},
schema: [],
@@ -54,17 +100,10 @@ module.exports = createRule({
defaultOptions: [],
create(context) {
// Check if current file is in an exception directory or is grpc-client-base.ts
const filename = context.filename
const isGrpcClientBase = path.basename(filename) === "grpc-client-base.ts"
// Skip checking files in src/hosts/vscode or standalone/runtime-files
const isExceptionDirectory = filename.includes("/src/hosts/vscode/") || filename.includes("/standalone/runtime-files/")
// Pattern for checking memberExpressions like vscode.workspace.fs.stat
function checkMemberExpression(node) {
// Skip if this file is in an exception directory or is grpc-client-base.ts
if (isGrpcClientBase || isExceptionDirectory) {
if (isExcluded(context.filename)) {
// Skip if this file is being excluded.
return
}
@@ -143,6 +182,20 @@ module.exports = createRule({
})
}
function isExcluded(filename) {
// Check if current file is in an exception directory or is grpc-client-base.ts
if (path.basename(filename) === "grpc-client-base.ts") {
return true
}
// Skip checking files in src/hosts/vscode or standalone/runtime-files
if (filename.includes("/src/hosts/vscode/")) {
return true
}
if (filename.includes("/standalone/runtime-files/")) {
return true
}
}
return {
// Detect basic member expressions (e.g., vscode.postMessage)
MemberExpression(node) {
@@ -152,7 +205,7 @@ module.exports = createRule({
// Detect property access through destructuring
VariableDeclarator(node) {
// Skip if this file is in an exception directory or is grpc-client-base.ts
if (isGrpcClientBase || isExceptionDirectory) {
if (isExcluded(context.filename)) {
return
}
@@ -1,216 +0,0 @@
const { ESLintUtils } = require("@typescript-eslint/utils")
const createRule = ESLintUtils.RuleCreator((name) => `https://cline.bot/eslint-rules/${name}`)
module.exports = createRule({
name: "no-grpc-client-object-literals",
meta: {
type: "problem",
docs: {
description:
"Enforce using .create() or .fromPartial() for gRPC service client parameters instead of object literals",
recommended: "error",
},
messages: {
useProtobufMethod:
"Use the appropriate protobuf .create() or .fromPartial() method instead of " +
"object literal for gRPC client parameters.\n" +
"Found: {{code}}\n" +
"gRPC client methods should always receive properly created protobuf objects.",
},
schema: [],
},
defaultOptions: [],
create(context) {
// Check if a name matches the gRPC service client pattern using regex
// Must start with an uppercase letter and end with ServiceClient
const isGrpcServiceClient = (name) => {
return typeof name === "string" && /^[A-Z].*ServiceClient$/.test(name)
}
const safeObjectExpressions = new Map() // Track object expressions in create/fromPartial calls
return {
// Skip object literals inside create() or fromPartial() method calls
CallExpression(node) {
if (
node.callee &&
node.callee.type === "MemberExpression" &&
(node.callee.property.name === "create" || node.callee.property.name === "fromPartial") &&
node.arguments.length > 0 &&
node.arguments[0].type === "ObjectExpression"
) {
// Track this object expression as being used with create/fromPartial
safeObjectExpressions.set(node.arguments[0], { isProblematic: false })
}
},
// Track create/fromPartial calls that contain nested object literals
"CallExpression[callee.type='MemberExpression'][callee.property.name=/^(create|fromPartial)$/]"(node) {
if (node.arguments.length > 0 && node.arguments[0].type === "ObjectExpression") {
// Track problematic nested object literals
const nestedObjectLiterals = new Map() // Map of object expressions to their containing property paths
// Search for nested object literals
const queue = [
...node.arguments[0].properties.map((prop) => ({
property: prop,
path: prop.key && prop.key.name ? prop.key.name : "unknown",
})),
]
while (queue.length > 0) {
const { property, path } = queue.shift()
// Skip spread elements
if (property.type !== "Property") continue
// If this is an object literal, mark it as problematic
if (property.value.type === "ObjectExpression") {
nestedObjectLiterals.set(property.value, path)
// Add nested properties to queue
queue.push(
...property.value.properties.map((prop) => ({
property: prop,
path: `${path}.${prop.key && prop.key.name ? prop.key.name : "unknown"}`,
})),
)
}
}
// For each problematic nested object, track it with its path
nestedObjectLiterals.forEach((path, objectExpr) => {
safeObjectExpressions.set(objectExpr, {
isProblematic: true,
path: path,
parentNode: node,
})
})
}
},
// Check calls to gRPC service clients
"CallExpression[callee.type='MemberExpression']"(node) {
// Get the object (left side) of the member expression
const callee = node.callee
if (callee.object && callee.object.type === "Identifier") {
const objectName = callee.object.name
// Check if this is a call to one of our gRPC service clients
if (isGrpcServiceClient(objectName)) {
// Only check the first argument of gRPC service client calls
if (node.arguments.length > 0) {
const arg = node.arguments[0] // Only check the first parameter
if (arg.type === "ObjectExpression" && !safeObjectExpressions.has(arg)) {
// This is an object literal being passed directly to a gRPC client
const sourceCode = context.getSourceCode()
const callText = sourceCode.getText(node).trim()
context.report({
node: arg,
messageId: "useProtobufMethod",
data: {
code: callText,
},
})
} else if (arg.type === "ObjectExpression") {
// Search for nested object literals that aren't protected
const queue = [...arg.properties]
while (queue.length > 0) {
const property = queue.shift()
// Skip spread elements
if (property.type !== "Property") continue
// Check value
if (
property.value.type === "ObjectExpression" &&
!safeObjectExpressions.has(property.value)
) {
// Found a nested object literal
const sourceCode = context.getSourceCode()
const propertyText = sourceCode.getText(property).trim()
context.report({
node: property.value,
messageId: "useProtobufMethod",
data: {
code: `${objectName}.${callee.property.name}(... ${propertyText} ...)`,
},
})
}
// Add any nested properties to the queue
if (property.value.type === "ObjectExpression") {
queue.push(...property.value.properties)
}
}
} else if (arg.type === "Identifier") {
// This is a variable - check if it references a problematic protobuf object
const varName = arg.name
const sourceCode = context.getSourceCode()
const scope = sourceCode.getScope(node)
// Find the variable declaration
const variable = scope.variables.find((v) => v.name === varName)
if (variable && variable.references && variable.references.length > 0) {
// Look for definitions
const def = variable.defs.find(
(d) => d.node && d.node.type === "VariableDeclarator" && d.node.init,
)
if (
def &&
def.node.init.type === "CallExpression" &&
def.node.init.callee.type === "MemberExpression" &&
(def.node.init.callee.property.name === "create" ||
def.node.init.callee.property.name === "fromPartial")
) {
// Flag if we find problematic nested object literals in this create/fromPartial call
const callText = sourceCode.getText(node).trim()
const initCallText = sourceCode.getText(def.node.init).trim()
// Check for nested object literals in init node
let foundNestedLiteral = false
if (
def.node.init.arguments.length > 0 &&
def.node.init.arguments[0].type === "ObjectExpression"
) {
// Find any nested object literals
const queue = [...def.node.init.arguments[0].properties]
while (queue.length > 0 && !foundNestedLiteral) {
const property = queue.shift()
// Skip spread elements
if (property.type !== "Property") continue
if (property.value.type === "ObjectExpression") {
foundNestedLiteral = true
context.report({
node,
messageId: "useProtobufMethod",
data: {
code: `${callText} - using request created with nested object literal at: ${property.key.name}`,
},
})
}
// Add any nested properties to the queue
if (property.value.type === "ObjectExpression") {
queue.push(...property.value.properties)
}
}
}
}
}
}
}
}
}
},
}
},
})
-556
View File
@@ -1,556 +0,0 @@
const { ESLintUtils } = require("@typescript-eslint/utils")
const createRule = ESLintUtils.RuleCreator((name) => `https://cline.bot/eslint-rules/${name}`)
module.exports = createRule({
name: "no-protobuf-object-literals",
meta: {
type: "problem",
docs: {
description: "Enforce using .create() or .fromPartial() for protobuf objects instead of object literals",
recommended: "error",
},
fixable: "code",
messages: {
useProtobufMethod:
"Use {{typeName}}.create() or {{typeName}}.fromPartial() instead of " +
"object literal for protobuf type from @shared/proto\n" +
"Found: {{code}}\n Suggestion: " +
"{{typeName}}.create({{objectContent}})",
useProtobufMethodGeneric:
"Use .create() or .fromPartial() instead of object literal for protobuf " +
"type from @shared/proto\n Found: {{code}}",
},
schema: [
{
type: "object",
properties: {
protobufPackages: {
type: "array",
items: { type: "string" },
default: ["shared/proto/"],
},
},
additionalProperties: false,
},
],
},
defaultOptions: [{ protobufPackages: ["shared/proto/"] }],
create(context, [options]) {
const protobufPackages = options.protobufPackages
const protobufImports = new Set() // Set of imported protobuf types
const protobufNamespaceImports = new Set() // For namespace imports like "import * as proto"
const safeObjectExpressions = new Set() // Track object expressions in create/fromPartial calls
return {
// Skip object literals inside create() or fromPartial() method calls
CallExpression(node) {
if (
node.callee &&
node.callee.type === "MemberExpression" &&
(node.callee.property.name === "create" || node.callee.property.name === "fromPartial") &&
node.arguments.length > 0 &&
node.arguments[0].type === "ObjectExpression"
) {
// Track this object expression as being used with create/fromPartial
safeObjectExpressions.add(node.arguments[0])
}
},
// Track imports from protobuf packages
ImportDeclaration(node) {
const packageName = node.source.value
if (matchesProtobufPackage(packageName, protobufPackages)) {
// This is a protobuf package.
node.specifiers.forEach((spec) => {
if (spec.type === "ImportSpecifier") {
// import { MyRequest } from '@shared/proto'
protobufImports.add(spec.imported.name)
} else if (spec.type === "ImportNamespaceSpecifier") {
// import * as proto from '@shared/proto'
protobufNamespaceImports.add(spec.local.name)
}
})
}
},
// Check variable declarations with type annotations
"VariableDeclarator > ObjectExpression"(node) {
// Skip if this is inside a create/fromPartial call
if (safeObjectExpressions.has(node)) {
return
}
// Found object literal in variable declaration
const declarator = node.parent
if (declarator.id && declarator.id.typeAnnotation) {
const typeName = getTypeName(declarator.id.typeAnnotation.typeAnnotation)
if (typeName) {
// Check if it's a direct protobuf import
if (protobufImports.has(typeName)) {
//console.log('🚨 VIOLATION: Using object literal for protobuf type:', typeName);
const sourceCode = context.getSourceCode()
const declaratorText = sourceCode.getText(declarator)
const objectText = sourceCode.getText(node)
context.report({
node,
messageId: "useProtobufMethod",
data: {
typeName,
code: declaratorText,
objectContent: objectText,
},
fix(fixer) {
// Replace the object literal with Type.create() call
return fixer.replaceText(node, `${typeName}.create(${objectText})`)
},
})
return
}
// Check if it's a namespaced protobuf type (e.g., proto.MyRequest)
if (isNamespacedProtobufType(protobufNamespaceImports, typeName)) {
//console.log('🚨 VIOLATION: Using object literal for namespaced protobuf type:', typeName);
const sourceCode = context.getSourceCode()
const declaratorText = sourceCode.getText(declarator)
context.report({
node,
messageId: "useProtobufMethodGeneric",
data: { code: declaratorText },
fix(fixer) {
// For namespaced types, use the full type name to call create()
return fixer.replaceText(node, `${typeName}.create(${sourceCode.getText(node)})`)
},
})
}
}
}
},
// Check assignment expressions
"AssignmentExpression > ObjectExpression"(node) {
// Skip if this is inside a create/fromPartial call
if (safeObjectExpressions.has(node)) {
return
}
const assignment = node.parent
// For assignment to variables without inline type annotation
if (assignment.left && assignment.right === node) {
let typeName = null
// Check if there's a typeAnnotation directly on the left
if (assignment.left.typeAnnotation) {
typeName = getTypeName(assignment.left.typeAnnotation.typeAnnotation)
}
// Otherwise try to infer from the variable name if it's a simple identifier
else if (assignment.left.type === "Identifier") {
const varName = assignment.left.name
// Check variable declarations in the current scope
const sourceCode = context.getSourceCode()
const scope = sourceCode.getScope(node)
const variable = scope.variables.find((v) => v.name === varName)
if (variable && variable.defs.length > 0) {
const def = variable.defs[0]
if (def.node.id && def.node.id.typeAnnotation) {
typeName = getTypeName(def.node.id.typeAnnotation.typeAnnotation)
}
}
}
if (typeName && protobufImports.has(typeName)) {
//console.log('🚨 VIOLATION: Using object literal in assignment for protobuf type:', typeName);
const sourceCode = context.getSourceCode()
const assignmentText = sourceCode.getText(assignment.left) + " = "
const objectText = sourceCode.getText(node)
context.report({
node,
messageId: "useProtobufMethod",
data: {
typeName,
code: assignmentText + "{",
objectContent: objectText,
},
fix(fixer) {
// Replace the object literal with Type.create() call in assignments
return fixer.replaceText(node, `${typeName}.create(${objectText})`)
},
})
}
}
},
// Check return statements
"ReturnStatement > ObjectExpression"(node) {
// Skip if this is inside a create/fromPartial call
if (safeObjectExpressions.has(node)) {
return
}
// Find the parent function to get its return type
const functionNode = findParentFunction(node)
if (!functionNode) {
return
}
// Try to get the return type using our enhanced helper
const sourceCode = context.getSourceCode()
let returnTypeName = getFunctionReturnType(functionNode, sourceCode)
// For async functions with Promise<Type> return type, extract the inner type
if (returnTypeName && returnTypeName.startsWith("Promise<") && returnTypeName.endsWith(">")) {
returnTypeName = returnTypeName.slice(8, -1)
}
// Check if the return type is a protobuf type
if (returnTypeName) {
if (protobufImports.has(returnTypeName)) {
//console.log('🚨 VIOLATION: Return type is a protobuf type:', returnTypeName);
const sourceCode = context.getSourceCode()
const returnText = sourceCode.getText(node.parent)
context.report({
node,
messageId: "useProtobufMethod",
data: {
typeName: returnTypeName,
code: returnText,
objectContent: sourceCode.getText(node),
},
fix(fixer) {
// Replace the object literal with Type.create() call in return statements
return fixer.replaceText(node, `${returnTypeName}.create(${sourceCode.getText(node)})`)
},
})
return
}
// Check if it's a namespaced protobuf type
if (isNamespacedProtobufType(protobufNamespaceImports, returnTypeName)) {
const sourceCode = context.getSourceCode()
const returnText = sourceCode.getText(node.parent)
//console.log('🚨 VIOLATION: Return type is a namespaced protobuf type:', returnTypeName);
context.report({
node,
messageId: "useProtobufMethodGeneric",
data: { code: returnText },
fix(fixer) {
// For namespaced types in return statements, we need to extract the full type name
const objectCode = sourceCode.getText(node)
// Since we may not know the exact type, we'll use the more generic namespaced type
return fixer.replaceText(node, `${returnTypeName}.create(${objectCode})`)
},
})
return
}
}
// Final fallback - if there are any protobuf imports and the function signature
// mentions a return type that matches one of the imported types
const functionText = functionNode ? sourceCode.getText(functionNode) : ""
for (const protoType of protobufImports) {
// Use more precise regex to match return type patterns specifically
// Rather than just checking if the type name appears anywhere in the signature
const returnTypeRegex = new RegExp(
// Match arrow function return type
`=>\\s*:?\\s*${protoType}\\b|` +
// Match function declaration return type
`\\)\\s*:?\\s*${protoType}\\b|` +
// Match Promise return type
`\\)\\s*:?\\s*Promise<\\s*${protoType}\\s*>|` +
// Match function type in variable declaration
`:\\s*\\(.*\\)\\s*=>\\s*${protoType}\\b`,
)
if (returnTypeRegex.test(functionText)) {
const returnText = sourceCode.getText(node.parent)
//console.log('🚨 VIOLATION: regex matched protobuf type:', functionText);
context.report({
node,
messageId: "useProtobufMethod",
data: {
typeName: protoType,
code: returnText,
objectContent: sourceCode.getText(node),
},
fix(fixer) {
// Replace the object literal with Type.create() call
return fixer.replaceText(node, `${protoType}.create(${sourceCode.getText(node)})`)
},
})
return
}
}
// Check for namespace imports too
for (const namespace of protobufNamespaceImports) {
// Similar to above, but for namespaced types
const namespaceReturnTypeRegex = new RegExp(
// Match arrow function return type
`=>\\s*:?\\s*${namespace}\\.\\w+\\b|` +
// Match function declaration return type
`\\)\\s*:?\\s*${namespace}\\.\\w+\\b|` +
// Match Promise return type
`\\)\\s*:?\\s*Promise<\\s*${namespace}\\.\\w+\\s*>|` +
// Match function type in variable declaration
`:\\s*\\(.*\\)\\s*=>\\s*${namespace}\\.\\w+\\b`,
)
if (namespaceReturnTypeRegex.test(functionText)) {
const returnText = sourceCode.getText(node.parent)
//console.log('🚨 VIOLATION: regex matched namespaced protobuf type:', functionText, "namespace:", namespace);
context.report({
node,
messageId: "useProtobufMethodGeneric",
data: { code: returnText },
fix(fixer) {
// For namespaced types based on function signature patterns
// Extract the namespace and type from the function text using more precise patterns
const match = functionText.match(
new RegExp(
// Match return type patterns more precisely
`\\)\\s*:?\\s*(${namespace}\\.[\\w]+)\\b|` + // Function declaration
`=>\\s*:?\\s*(${namespace}\\.[\\w]+)\\b|` + // Arrow function
`Promise<\\s*(${namespace}\\.[\\w]+)\\s*>`, // Promise wrapped
),
)
if (match) {
const fullType = match[1] || match[2]
return fixer.replaceText(node, `${fullType}.create(${sourceCode.getText(node)})`)
}
// Fallback - we can't determine the exact type, but we know it's from the namespace
// Use a namespace-based approach
return fixer.replaceText(node, `${namespace}.create(${sourceCode.getText(node)})`)
},
})
return
}
}
},
// Check function call arguments (more selective approach)
"CallExpression > ObjectExpression"(node) {
// Skip if this is inside a create/fromPartial call
if (safeObjectExpressions.has(node)) {
return
}
// We need to be more selective to avoid false positives
// Only warn if:
// 1. The function is called on a protobuf namespace
// 2. The call argument has a type annotation that matches a protobuf type
// 3. The call is to a function that we know takes a protobuf type
// Check if it's a call on a protobuf namespace
if (
node.parent.callee &&
node.parent.callee.type === "MemberExpression" &&
node.parent.callee.object.type === "Identifier"
) {
const namespace = node.parent.callee.object.name
if (protobufNamespaceImports.has(namespace)) {
const sourceCode = context.getSourceCode()
const callText = sourceCode.getText(node.parent)
//console.log('🚨 VIOLATION: Check function call arguments object literal:', callText);
context.report({
node,
messageId: "useProtobufMethodGeneric",
data: { code: callText },
fix(fixer) {
// For calls on a protobuf namespace
const memberExpr = node.parent.callee
// Try to determine if this is calling a method that expects a specific type
const methodName = memberExpr.property.name
// If method name looks like 'create' + Type, we can infer the type
const possibleTypeName = methodName.replace(/^create/, "")
// Check if namespace has a type with this name
// Since we can't directly check at lint time, we'll use the namespace + inferred type
if (possibleTypeName && possibleTypeName !== methodName) {
return fixer.replaceText(
node,
`${namespace}.${possibleTypeName}.create(${sourceCode.getText(node)})`,
)
}
// Fallback - use a more generic approach with namespace
return fixer.replaceText(node, `${namespace}.create(${sourceCode.getText(node)})`)
},
})
return
}
}
// For regular function calls with object literals, check if there are protobuf imports
// and if the function might expect a protobuf type
if (node.parent.callee) {
// This is a more permissive check to catch cases like processContent({ ... })
// which might be passing a protobuf type
const sourceCode = context.getSourceCode()
const scope = sourceCode.getScope(node)
// Try to find the function definition
if (node.parent.callee.type === "Identifier") {
const functionName = node.parent.callee.name
const variable = scope.variables.find((v) => v.name === functionName)
// If we found the function and it has parameter type annotations
// that match protobuf types, flag it
if (variable && variable.defs.length > 0) {
const def = variable.defs[0]
if (def.node.params && node.parent.arguments.indexOf(node) < def.node.params.length) {
const param = def.node.params[node.parent.arguments.indexOf(node)]
if (param.typeAnnotation) {
const typeName = getTypeName(param.typeAnnotation.typeAnnotation)
if (
typeName &&
(protobufImports.has(typeName) ||
isNamespacedProtobufType(protobufNamespaceImports, typeName))
) {
const callText = sourceCode.getText(node.parent)
//console.log('🚨 VIOLATION: Function call arguments object literal:', callText);
context.report({
node,
messageId: "useProtobufMethodGeneric",
data: { code: callText },
fix(fixer) {
// For function calls with protobuf type parameters
return fixer.replaceText(node, `${typeName}.create(${sourceCode.getText(node)})`)
},
})
return
}
}
}
}
}
}
},
}
},
})
// Helper functions
function getTypeName(typeAnnotation) {
if (!typeAnnotation) {
return null
}
if (typeAnnotation.type === "TSTypeReference") {
if (typeAnnotation.typeName.type === "Identifier") {
return typeAnnotation.typeName.name
} else if (typeAnnotation.typeName.type === "TSQualifiedName") {
// Handle namespaced types like proto.MyRequest
return `${typeAnnotation.typeName.left.name}.${typeAnnotation.typeName.right.name}`
}
}
return null
}
function matchesProtobufPackage(packageName, protobufPackages) {
return protobufPackages.some((protobufPackage) => {
// Remove leading and trailing @ and / from protobufPackage
const cleanedPackage = protobufPackage.replace(/^[@\/]/, "").replace(/[\/]$/, "")
const pattern = new RegExp(`(.*[@/]|)${escapeRegex(cleanedPackage)}[/].*`)
return pattern.test(packageName)
})
}
// Helper function to escape special regex characters
function escapeRegex(string) {
return string.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")
}
// Helper to extract function return type more reliably
function getFunctionReturnType(functionNode, sourceCode) {
// 1. Check explicit return type annotation
if (functionNode.returnType) {
return getTypeName(functionNode.returnType.typeAnnotation)
}
// 2. For variable declarations like const foo: (arg: Type) => ReturnType = ...
if (functionNode.parent && functionNode.parent.type === "VariableDeclarator") {
const declarator = functionNode.parent
if (declarator.id && declarator.id.typeAnnotation) {
const typeAnnotation = declarator.id.typeAnnotation.typeAnnotation
// Handle function type annotations
if (typeAnnotation.type === "TSFunctionType" && typeAnnotation.typeAnnotation) {
return getTypeName(typeAnnotation.typeAnnotation)
}
// Handle type references to function types
if (typeAnnotation.type === "TSTypeReference") {
// This might be a type like Promise<ReturnType>
if (
typeAnnotation.typeName.name === "Promise" &&
typeAnnotation.typeParameters &&
typeAnnotation.typeParameters.params.length > 0
) {
return getTypeName(typeAnnotation.typeParameters.params[0])
}
}
}
}
// 3. For class methods, check if it's part of an interface implementation
if (
functionNode.parent &&
functionNode.parent.type === "MethodDefinition" &&
functionNode.parent.parent &&
functionNode.parent.parent.type === "ClassBody"
) {
const className = getEnclosingClassName(functionNode)
const methodName = functionNode.parent.key.name
if (className && methodName) {
// Look for interface declarations in the scope
const scope = sourceCode.getScope(functionNode)
// This would require more complex scope analysis which is limited in ESLint
// For now, we'll return null and rely on other methods
}
}
return null
}
// Helper to get the class name for a method
function getEnclosingClassName(node) {
let current = node.parent
while (current) {
if (current.type === "ClassDeclaration" && current.id) {
return current.id.name
}
current = current.parent
}
return null
}
function isNamespacedProtobufType(protobufNamespaceImports, typeName) {
if (!typeName.includes(".")) {
return false
}
const namespace = typeName.split(".")[0]
return protobufNamespaceImports.has(namespace)
}
function findParentFunction(node) {
let current = node.parent
while (current) {
if (
current.type === "FunctionDeclaration" ||
current.type === "FunctionExpression" ||
current.type === "ArrowFunctionExpression"
) {
return current
}
current = current.parent
}
return null
}
+1 -1
View File
@@ -925,7 +925,7 @@ async function main() {
.option("--max-attempts-per-case <number>", "Maximum total attempts per test case (default: 10x valid attempts)")
.option("--max-cases <number>", "Maximum number of test cases to run (limits total cases loaded)")
.option("--parsing-function <name>", "The parsing function to use", "parseAssistantMessageV2")
.option("--diff-edit-function <name>", "The diff editing function to use", "diff-06-25-25")
.option("--diff-edit-function <name>", "The diff editing function to use", "diff-06-26-25")
.option("--thinking-budget <tokens>", "Set the thinking tokens budget", "0")
.option("--parallel", "Run tests in parallel", false)
.option("--replay", "Run evaluation from a pre-recorded LLM output, skipping the API call", false)
+12 -2
View File
@@ -937,8 +937,18 @@ def main():
# Build current URL
# Dynamically derive the base URL
server_address = st.server.server_address if hasattr(st.server, 'server_address') else "localhost"
server_port = st.server.server_port if hasattr(st.server, 'server_port') else "8501"
try:
# For older Streamlit versions
server_address = st.server.server_address
server_port = st.server.server_port
except AttributeError:
# Fallback for newer Streamlit versions where st.server is removed
# We can't reliably get the server address/port from within the script anymore.
# We'll default to localhost and the default port.
# The user can see the correct network URL in the terminal.
server_address = "localhost"
server_port = 8501
base_url = f"http://{server_address}:{server_port}"
current_url = f"{base_url}/?run_id={st.session_state.selected_run_id}"
if st.session_state.drill_down_model:
+4746 -12508
View File
File diff suppressed because it is too large Load Diff
+35 -15
View File
@@ -2,7 +2,7 @@
"name": "claude-dev",
"displayName": "Cline",
"description": "Autonomous coding agent right in your IDE, capable of creating/editing files, running commands, using the browser, and more with your permission every step of the way.",
"version": "3.19.4",
"version": "3.20.5",
"icon": "assets/icons/icon.png",
"engines": {
"vscode": "^1.84.0"
@@ -119,7 +119,8 @@
{
"type": "webview",
"id": "claude-dev.SidebarProvider",
"name": ""
"name": "",
"icon": "assets/icons/icon.svg"
}
]
},
@@ -186,6 +187,12 @@
"category": "Cline",
"icon": "$(robot)"
},
{
"command": "cline.abortGitCommitMessage",
"title": "Generate Commit Message with Cline - Stop",
"category": "Cline",
"icon": "$(debug-stop)"
},
{
"command": "cline.explainCode",
"title": "Explain with Cline",
@@ -213,7 +220,7 @@
},
{
"command": "cline.generateGitCommitMessage",
"when": "scmProvider == git"
"when": "config.git.enabled && scmProvider == git"
},
{
"command": "cline.focusChatInput",
@@ -306,13 +313,22 @@
{
"command": "cline.generateGitCommitMessage",
"group": "navigation",
"when": "scmProvider == git"
"when": "config.git.enabled && scmProvider == git && !cline.isGeneratingCommit"
},
{
"command": "cline.abortGitCommitMessage",
"group": "navigation",
"when": "config.git.enabled && scmProvider == git && cline.isGeneratingCommit"
}
],
"commandPalette": [
{
"command": "cline.generateGitCommitMessage",
"when": "scmProvider == git"
"when": "config.git.enabled && scmProvider == git && !cline.isGeneratingCommit"
},
{
"command": "cline.abortGitCommitMessage",
"when": "config.git.enabled && scmProvider == git && cline.isGeneratingCommit"
}
]
},
@@ -323,14 +339,14 @@
},
"scripts": {
"vscode:prepublish": "npm run package",
"compile": "npm run check-types && npm run lint && node esbuild.js",
"compile-standalone": "npm run check-types && npm run lint && node esbuild.js --standalone",
"compile": "npm run check-types && npm run lint && node esbuild.mjs",
"compile-standalone": "npm run check-types && npm run lint && node esbuild.mjs --standalone",
"postcompile-standalone": "node scripts/package-standalone.mjs",
"watch": "npm-run-all -p watch:*",
"watch:esbuild": "node esbuild.js --watch",
"watch:esbuild": "node esbuild.mjs --watch",
"watch:tsc": "tsc --noEmit --watch --project tsconfig.json",
"package": "npm run check-types && npm run build:webview && npm run lint && node esbuild.js --production",
"protos": "node scripts/build-proto.mjs && node scripts/generate-server-setup.mjs && node scripts/generate-host-bridge-client.mjs",
"package": "npm run check-types && npm run build:webview && npm run lint && node esbuild.mjs --production",
"protos": "node scripts/build-proto.mjs",
"postprotos": "prettier src/shared/proto src/core/controller src/hosts/ webview-ui/src/services src/generated --write --log-level warn",
"clean": "rimraf dist dist-standalone webview-ui/build src/generated out/",
"compile-tests": "node ./scripts/build-tests.js",
@@ -345,6 +361,9 @@
"test:integration": "vscode-test",
"test:unit": "TS_NODE_PROJECT='./tsconfig.unit-test.json' mocha",
"test:coverage": "vscode-test --coverage",
"e2e": "playwright test -c playwright.config.ts",
"test:e2e": "playwright install && vsce package --no-dependencies --out dist/e2e.vsix && node src/test/e2e/utils/build.js && playwright test",
"test:e2e:optimal": "vsce package --no-dependencies --out dist/e2e.vsix && node src/test/e2e/utils/build.js && 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",
@@ -354,9 +373,9 @@
"prepare": "husky",
"changeset": "changeset",
"version-packages": "changeset version",
"docs": "cd docs && mintlify dev",
"docs:check-links": "cd docs && mintlify broken-links",
"docs:rename-file": "cd docs && mintlify rename",
"docs": "cd docs && npm run dev",
"docs:check-links": "cd docs && npm run check",
"docs:rename-file": "cd docs && npm run rename",
"report-issue": "node scripts/report-issue.js"
},
"lint-staged": {
@@ -383,7 +402,8 @@
"@typescript-eslint/parser": "^7.18.0",
"@typescript-eslint/utils": "^8.33.0",
"@vscode/test-cli": "^0.0.10",
"@vscode/test-electron": "^2.4.1",
"@vscode/test-electron": "^2.5.2",
"@vscode/vsce": "^3.6.0",
"chai": "^4.3.10",
"chalk": "^5.3.0",
"esbuild": "^0.25.0",
@@ -393,7 +413,6 @@
"husky": "^9.1.7",
"lint-staged": "^16.1.0",
"minimatch": "^3.0.3",
"mintlify": "^4.0.515",
"npm-run-all": "^4.1.5",
"prettier": "^3.3.3",
"protoc-gen-ts": "^0.8.7",
@@ -425,6 +444,7 @@
"@opentelemetry/sdk-node": "^0.39.1",
"@opentelemetry/sdk-trace-node": "^1.30.1",
"@opentelemetry/semantic-conventions": "^1.30.0",
"@playwright/test": "^1.53.2",
"@sentry/browser": "^9.12.0",
"@streamparser/json": "^0.0.22",
"@vscode/codicons": "^0.0.36",
+32
View File
@@ -0,0 +1,32 @@
import { defineConfig } from "@playwright/test"
const isCI = !!process?.env?.CI
const isWindow = process?.platform?.startsWith("win")
export default defineConfig({
workers: 1,
retries: 1,
testDir: "src/test/e2e",
timeout: isCI || isWindow ? 40000 : 20000,
expect: {
timeout: isCI || isWindow ? 5000 : 2000,
},
fullyParallel: true,
reporter: isCI ? [["github"], ["list"]] : [["list"]],
projects: [
{
name: "setup test environment",
testMatch: /global\.setup\.ts/,
},
{
name: "e2e tests",
testMatch: /.*\.test\.ts/,
dependencies: ["setup test environment"],
},
{
name: "cleanup test environment",
testMatch: /global\.teardown\.ts/,
dependencies: ["e2e tests"],
},
],
})
@@ -1,7 +1,7 @@
syntax = "proto3";
package cline;
import "common.proto";
import "cline/common.proto";
option java_package = "bot.cline.proto";
option java_multiple_files = true;
@@ -53,6 +53,7 @@ message UserInfo {
optional string display_name = 2;
optional string email = 3;
optional string photo_url = 4;
optional string app_base_url = 5; // Cline app base URL
}
message UserOrganization {
@@ -126,4 +127,4 @@ message OrganizationUsageTransaction {
int32 prompt_tokens = 10;
int32 total_tokens = 11;
string user_id = 12;
}
}
@@ -1,7 +1,7 @@
syntax = "proto3";
package cline;
import "common.proto";
import "cline/common.proto";
option java_package = "bot.cline.proto";
option java_multiple_files = true;
@@ -1,7 +1,7 @@
syntax = "proto3";
package cline;
import "common.proto";
import "cline/common.proto";
option java_package = "bot.cline.proto";
option java_multiple_files = true;
+1 -1
View File
@@ -1,7 +1,7 @@
syntax = "proto3";
package cline;
import "common.proto";
import "cline/common.proto";
option java_package = "bot.cline.proto";
option java_multiple_files = true;
+1 -1
View File
@@ -1,7 +1,7 @@
syntax = "proto3";
package cline;
import "common.proto";
import "cline/common.proto";
option java_package = "bot.cline.proto";
option java_multiple_files = true;
+292
View File
@@ -0,0 +1,292 @@
syntax = "proto3";
package cline;
import "cline/common.proto";
option java_package = "bot.cline.proto";
option java_multiple_files = true;
// Service for model-related operations
service ModelsService {
// Fetches available models from Ollama
rpc getOllamaModels(StringRequest) returns (StringArray);
// Fetches available models from LM Studio
rpc getLmStudioModels(StringRequest) returns (StringArray);
// Fetches available models from VS Code LM API
rpc getVsCodeLmModels(EmptyRequest) returns (VsCodeLmModelsArray);
// Refreshes and returns OpenRouter models
rpc refreshOpenRouterModels(EmptyRequest) returns (OpenRouterCompatibleModelInfo);
// Refreshes and returns Hugging Face models
rpc refreshHuggingFaceModels(EmptyRequest) returns (OpenRouterCompatibleModelInfo);
// Refreshes and returns OpenAI models
rpc refreshOpenAiModels(OpenAiModelsRequest) returns (StringArray);
// Refreshes and returns Requesty models
rpc refreshRequestyModels(EmptyRequest) returns (OpenRouterCompatibleModelInfo);
// Subscribe to OpenRouter models updates
rpc subscribeToOpenRouterModels(EmptyRequest) returns (stream OpenRouterCompatibleModelInfo);
// Updates API configuration
rpc updateApiConfigurationProto(UpdateApiConfigurationRequest) returns (Empty);
// Refreshes and returns Groq models
rpc refreshGroqModels(EmptyRequest) returns (OpenRouterCompatibleModelInfo);
}
// List of VS Code LM models
message VsCodeLmModelsArray {
repeated LanguageModelChatSelector models = 1;
}
// Structure representing a language model chat selector
message LanguageModelChatSelector {
optional string vendor = 1;
optional string family = 2;
optional string version = 3;
optional string id = 4;
}
// Price tier for tiered pricing models
message PriceTier {
int32 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 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;
optional double input_price = 2;
optional double output_price = 3;
optional double cache_writes_price = 4;
optional double cache_reads_price = 5;
}
// For OpenRouterCompatibleModelInfo structure in OpenRouterModels
message OpenRouterModelInfo {
optional int32 max_tokens = 1;
optional int32 context_window = 2;
optional bool supports_images = 3;
bool supports_prompt_cache = 4;
optional double input_price = 5;
optional double output_price = 6;
optional double cache_writes_price = 7;
optional double cache_reads_price = 8;
optional string description = 9;
optional ThinkingConfig thinking_config = 10;
optional bool supports_global_endpoint = 11;
repeated ModelTier tiers = 12;
}
// Shared response message for model information
message OpenRouterCompatibleModelInfo {
map<string, OpenRouterModelInfo> models = 1;
}
// Request for fetching OpenAI models
message OpenAiModelsRequest {
Metadata metadata = 1;
string base_url = 2;
string api_key = 3;
}
// Request for updating API configuration
message UpdateApiConfigurationRequest {
Metadata metadata = 1;
ModelsApiConfiguration api_configuration = 2;
}
// API Provider enumeration
enum ApiProvider {
ANTHROPIC = 0;
OPENROUTER = 1;
BEDROCK = 2;
VERTEX = 3;
OPENAI = 4;
OLLAMA = 5;
LMSTUDIO = 6;
GEMINI = 7;
OPENAI_NATIVE = 8;
REQUESTY = 9;
TOGETHER = 10;
DEEPSEEK = 11;
QWEN = 12;
DOUBAO = 13;
MISTRAL = 14;
VSCODE_LM = 15;
CLINE = 16;
LITELLM = 17;
NEBIUS = 18;
FIREWORKS = 19;
ASKSAGE = 20;
XAI = 21;
SAMBANOVA = 22;
CEREBRAS = 23;
GROQ = 24;
SAPAICORE = 25;
CLAUDE_CODE = 26;
MOONSHOT = 27;
HUGGINGFACE = 28;
HUAWEI_CLOUD_MAAS = 29;
}
// Model info for OpenAI-compatible models
message OpenAiCompatibleModelInfo {
optional int32 max_tokens = 1;
optional int32 context_window = 2;
optional bool supports_images = 3;
bool supports_prompt_cache = 4;
optional double input_price = 5;
optional double output_price = 6;
optional ThinkingConfig thinking_config = 7;
optional bool supports_global_endpoint = 8;
optional double cache_writes_price = 9;
optional double cache_reads_price = 10;
optional string description = 11;
repeated ModelTier tiers = 12;
optional double temperature = 13;
optional bool is_r1_format_required = 14;
}
// Model info for LiteLLM models
message LiteLLMModelInfo {
optional int32 max_tokens = 1;
optional int32 context_window = 2;
optional bool supports_images = 3;
bool supports_prompt_cache = 4;
optional double input_price = 5;
optional double output_price = 6;
optional ThinkingConfig thinking_config = 7;
optional bool supports_global_endpoint = 8;
optional double cache_writes_price = 9;
optional double cache_reads_price = 10;
optional string description = 11;
repeated ModelTier tiers = 12;
optional double temperature = 13;
}
// Main ApiConfiguration message
message ModelsApiConfiguration {
// Global configuration fields (not mode-specific)
optional string api_key = 1;
optional string cline_api_key = 2;
optional string task_id = 3;
optional string lite_llm_base_url = 4;
optional string lite_llm_api_key = 5;
optional bool lite_llm_use_prompt_cache = 6;
map<string, string> open_ai_headers = 7;
optional string anthropic_base_url = 8;
optional string open_router_api_key = 9;
optional string open_router_provider_sorting = 10;
optional string aws_access_key = 11;
optional string aws_secret_key = 12;
optional string aws_session_token = 13;
optional string aws_region = 14;
optional bool aws_use_cross_region_inference = 15;
optional bool aws_bedrock_use_prompt_cache = 16;
optional bool aws_use_profile = 17;
optional string aws_profile = 18;
optional string aws_bedrock_endpoint = 19;
optional string claude_code_path = 20;
optional string vertex_project_id = 21;
optional string vertex_region = 22;
optional string open_ai_base_url = 23;
optional string open_ai_api_key = 24;
optional string ollama_base_url = 25;
optional string ollama_api_options_ctx_num = 26;
optional string lm_studio_base_url = 27;
optional string gemini_api_key = 28;
optional string gemini_base_url = 29;
optional string open_ai_native_api_key = 30;
optional string deep_seek_api_key = 31;
optional string requesty_api_key = 32;
optional string together_api_key = 33;
optional string fireworks_api_key = 34;
optional int32 fireworks_model_max_completion_tokens = 35;
optional int32 fireworks_model_max_tokens = 36;
optional string qwen_api_key = 37;
optional string doubao_api_key = 38;
optional string mistral_api_key = 39;
optional string azure_api_version = 40;
optional string qwen_api_line = 41;
optional string nebius_api_key = 42;
optional string asksage_api_url = 43;
optional string asksage_api_key = 44;
optional string xai_api_key = 45;
optional string sambanova_api_key = 46;
optional string cerebras_api_key = 47;
optional int32 request_timeout_ms = 48;
optional string sap_ai_core_client_id = 49;
optional string sap_ai_core_client_secret = 50;
optional string sap_ai_resource_group = 51;
optional string sap_ai_core_token_url = 52;
optional string sap_ai_core_base_url = 53;
optional string moonshot_api_key = 54;
optional string moonshot_api_line = 55;
optional string aws_authentication = 56;
optional string aws_bedrock_api_key = 57;
optional string cline_account_id = 58;
optional string groq_api_key = 59;
optional string hugging_face_api_key = 60;
optional string huawei_cloud_maas_api_key = 61;
// 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 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;
optional string plan_mode_aws_bedrock_custom_model_base_id = 106;
optional string plan_mode_open_router_model_id = 107;
optional OpenRouterModelInfo plan_mode_open_router_model_info = 108;
optional string plan_mode_open_ai_model_id = 109;
optional OpenAiCompatibleModelInfo plan_mode_open_ai_model_info = 110;
optional string plan_mode_ollama_model_id = 111;
optional string plan_mode_lm_studio_model_id = 112;
optional string plan_mode_lite_llm_model_id = 113;
optional LiteLLMModelInfo plan_mode_lite_llm_model_info = 114;
optional string plan_mode_requesty_model_id = 115;
optional OpenRouterModelInfo plan_mode_requesty_model_info = 116;
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;
// 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 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;
optional string act_mode_aws_bedrock_custom_model_base_id = 206;
optional string act_mode_open_router_model_id = 207;
optional OpenRouterModelInfo act_mode_open_router_model_info = 208;
optional string act_mode_open_ai_model_id = 209;
optional OpenAiCompatibleModelInfo act_mode_open_ai_model_info = 210;
optional string act_mode_ollama_model_id = 211;
optional string act_mode_lm_studio_model_id = 212;
optional string act_mode_lite_llm_model_id = 213;
optional LiteLLMModelInfo act_mode_lite_llm_model_info = 214;
optional string act_mode_requesty_model_id = 215;
optional OpenRouterModelInfo act_mode_requesty_model_info = 216;
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;
repeated string favorited_model_ids = 300;
}
@@ -1,7 +1,7 @@
syntax = "proto3";
package cline;
import "common.proto";
import "cline/common.proto";
option java_package = "bot.cline.proto";
option java_multiple_files = true;
+239
View File
@@ -0,0 +1,239 @@
syntax = "proto3";
package cline;
import "cline/common.proto";
option java_package = "bot.cline.proto";
option java_multiple_files = true;
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);
rpc resetState(ResetStateRequest) returns (Empty);
rpc togglePlanActModeProto(TogglePlanActModeRequest) returns (Boolean);
rpc updateAutoApprovalSettings(AutoApprovalSettingsRequest) returns (Empty);
rpc updateSettings(UpdateSettingsRequest) returns (Empty);
rpc updateTelemetrySetting(TelemetrySettingRequest) returns (Empty);
rpc setWelcomeViewCompleted(BooleanRequest) returns (Empty);
}
message State {
string state_json = 1;
}
message TerminalProfiles {
repeated TerminalProfile profiles = 1;
}
message TerminalProfile {
string id = 1;
string name = 2;
optional string path = 3;
optional string description = 4;
}
message TerminalProfileUpdateResponse {
int32 closed_count = 1;
int32 busy_terminals_count = 2;
bool has_busy_terminals = 3;
}
message TogglePlanActModeRequest {
Metadata metadata = 1;
PlanActMode mode = 2;
optional ChatContent chat_content = 3;
}
enum PlanActMode {
PLAN = 0;
ACT = 1;
}
message ChatContent {
optional string message = 1;
repeated string images = 2;
repeated string files = 3;
}
message ResetStateRequest {
Metadata metadata = 1;
optional bool global = 2;
}
message AutoApprovalSettingsRequest {
Metadata metadata = 1;
message Actions {
bool read_files = 1;
bool read_files_externally = 2;
bool edit_files = 3;
bool edit_files_externally = 4;
bool execute_safe_commands = 5;
bool execute_all_commands = 6;
bool use_browser = 7;
bool use_mcp = 8;
}
int32 version = 2;
bool enabled = 3;
Actions actions = 4;
int32 max_requests = 5;
bool enable_notifications = 6;
repeated string favorites = 7;
}
enum TelemetrySettingEnum {
UNSET = 0;
ENABLED = 1;
DISABLED = 2;
}
message TelemetrySettingRequest {
Metadata metadata = 1;
TelemetrySettingEnum setting = 2;
}
// Message for updating settings
message UpdateSettingsRequest {
Metadata metadata = 1;
optional ApiConfiguration api_configuration = 2;
optional string telemetry_setting = 3;
optional bool plan_act_separate_models_setting = 4;
optional bool enable_checkpoints_setting = 5;
optional bool mcp_marketplace_enabled = 6;
optional int32 shell_integration_timeout = 8;
optional bool terminal_reuse_enabled = 9;
optional bool mcp_responses_collapsed = 10;
optional string mcp_display_mode = 11;
optional int32 terminal_output_line_limit = 12;
optional PlanActMode mode = 13;
optional string preferred_language = 14;
optional string openai_reasoning_effort = 15;
}
// Complete API Configuration message
message ApiConfiguration {
// Global configuration fields (not mode-specific)
optional string api_key = 1; // anthropic
optional string cline_api_key = 2;
optional string task_id = 3;
optional string lite_llm_base_url = 4;
optional string lite_llm_api_key = 5;
optional bool lite_llm_use_prompt_cache = 6;
optional string openai_headers = 7; // JSON string
optional string anthropic_base_url = 8;
optional string openrouter_api_key = 9;
optional string openrouter_provider_sorting = 10;
optional string aws_access_key = 11;
optional string aws_secret_key = 12;
optional string aws_session_token = 13;
optional string aws_region = 14;
optional bool aws_use_cross_region_inference = 15;
optional bool aws_bedrock_use_prompt_cache = 16;
optional bool aws_use_profile = 17;
optional string aws_profile = 18;
optional string aws_bedrock_endpoint = 19;
optional string claude_code_path = 20;
optional string vertex_project_id = 21;
optional string vertex_region = 22;
optional string openai_base_url = 23;
optional string openai_api_key = 24;
optional string ollama_base_url = 25;
optional string ollama_api_options_ctx_num = 26;
optional string lm_studio_base_url = 27;
optional string gemini_api_key = 28;
optional string gemini_base_url = 29;
optional string openai_native_api_key = 30;
optional string deep_seek_api_key = 31;
optional string requesty_api_key = 32;
optional string together_api_key = 33;
optional string fireworks_api_key = 34;
optional int32 fireworks_model_max_completion_tokens = 35;
optional int32 fireworks_model_max_tokens = 36;
optional string qwen_api_key = 37;
optional string doubao_api_key = 38;
optional string mistral_api_key = 39;
optional string azure_api_version = 40;
optional string qwen_api_line = 41;
optional string nebius_api_key = 42;
optional string asksage_api_url = 43;
optional string asksage_api_key = 44;
optional string xai_api_key = 45;
optional string sambanova_api_key = 46;
optional string cerebras_api_key = 47;
optional int32 request_timeout_ms = 48;
optional string sap_ai_core_client_id = 49;
optional string sap_ai_core_client_secret = 50;
optional string sap_ai_resource_group = 51;
optional string sap_ai_core_token_url = 52;
optional string sap_ai_core_base_url = 53;
optional string moonshot_api_key = 54;
optional string moonshot_api_line = 55;
optional string huawei_cloud_maas_api_key = 56;
// Plan mode configurations
optional string plan_mode_api_provider = 100;
optional string plan_mode_api_model_id = 101;
optional int32 plan_mode_thinking_budget_tokens = 102;
optional string plan_mode_reasoning_effort = 103;
optional string plan_mode_vscode_lm_model_selector = 104; // JSON string
optional bool plan_mode_aws_bedrock_custom_selected = 105;
optional string plan_mode_aws_bedrock_custom_model_base_id = 106;
optional string plan_mode_openrouter_model_id = 107;
optional string plan_mode_openrouter_model_info = 108; // JSON string
optional string plan_mode_openai_model_id = 109;
optional string plan_mode_openai_model_info = 110; // JSON string
optional string plan_mode_ollama_model_id = 111;
optional string plan_mode_lm_studio_model_id = 112;
optional string plan_mode_lite_llm_model_id = 113;
optional string plan_mode_lite_llm_model_info = 114; // JSON string
optional string plan_mode_requesty_model_id = 115;
optional string plan_mode_requesty_model_info = 116; // JSON string
optional string plan_mode_together_model_id = 117;
optional string plan_mode_fireworks_model_id = 118;
optional string plan_mode_sap_ai_core_model_id = 119;
optional string plan_mode_huawei_cloud_maas_model_id = 120;
optional string plan_mode_huawei_cloud_maas_model_info = 121;
// Act mode configurations
optional string act_mode_api_provider = 200;
optional string act_mode_api_model_id = 201;
optional int32 act_mode_thinking_budget_tokens = 202;
optional string act_mode_reasoning_effort = 203;
optional string act_mode_vscode_lm_model_selector = 204; // JSON string
optional bool act_mode_aws_bedrock_custom_selected = 205;
optional string act_mode_aws_bedrock_custom_model_base_id = 206;
optional string act_mode_openrouter_model_id = 207;
optional string act_mode_openrouter_model_info = 208; // JSON string
optional string act_mode_openai_model_id = 209;
optional string act_mode_openai_model_info = 210; // JSON string
optional string act_mode_ollama_model_id = 211;
optional string act_mode_lm_studio_model_id = 212;
optional string act_mode_lite_llm_model_id = 213;
optional string act_mode_lite_llm_model_info = 214; // JSON string
optional string act_mode_requesty_model_id = 215;
optional string act_mode_requesty_model_info = 216; // JSON string
optional string act_mode_together_model_id = 217;
optional string act_mode_fireworks_model_id = 218;
optional string act_mode_sap_ai_core_model_id = 219;
optional string act_mode_huawei_cloud_maas_model_id = 220;
optional string act_mode_huawei_cloud_maas_model_info = 221;
// Favorited model IDs
repeated string favorited_model_ids = 300;
// Extension fields for Bedrock Api Keys
optional string aws_authentication = 301;
optional string aws_bedrock_api_key = 302;
optional string cline_account_id = 303;
}
message UpdateTerminalConnectionTimeoutRequest {
optional int32 timeout_ms = 1;
}
message UpdateTerminalConnectionTimeoutResponse {
optional int32 timeout_ms = 1;
}
+1 -1
View File
@@ -1,7 +1,7 @@
syntax = "proto3";
package cline;
import "common.proto";
import "cline/common.proto";
option java_package = "bot.cline.proto";
option java_multiple_files = true;
+1 -1
View File
@@ -1,7 +1,7 @@
syntax = "proto3";
package cline;
import "common.proto";
import "cline/common.proto";
option java_package = "bot.cline.proto";
option java_multiple_files = true;
+1 -1
View File
@@ -1,7 +1,7 @@
syntax = "proto3";
package cline;
import "common.proto";
import "cline/common.proto";
option java_package = "bot.cline.proto";
option java_multiple_files = true;
+49 -3
View File
@@ -4,13 +4,23 @@ package host;
option java_package = "bot.cline.host.proto";
option java_multiple_files = true;
import "common.proto";
import "cline/common.proto";
// Provides methods for diff views.
service DiffService {
// Open the diff view/editor.
rpc openDiff(OpenDiffRequest) returns (OpenDiffResponse);
// Get the contents of the diff view.
rpc getDocumentText(GetDocumentTextRequest) returns (GetDocumentTextResponse);
// Replace a text selection in the diff.
rpc replaceText(ReplaceTextRequest) returns (ReplaceTextResponse);
rpc scrollDiff(ScrollDiffRequest) returns (ScrollDiffResponse);
// Truncate the diff document.
rpc truncateDocument(TruncateDocumentRequest) returns (TruncateDocumentResponse);
// Save the diff document.
rpc saveDocument(SaveDocumentRequest) returns (SaveDocumentResponse);
// Close the diff editor UI.
rpc closeDiff(CloseDiffRequest) returns (CloseDiffResponse);
}
message OpenDiffRequest {
@@ -26,6 +36,15 @@ message OpenDiffResponse {
optional string diff_id = 1;
}
message GetDocumentTextRequest {
optional cline.Metadata metadata = 1;
optional string diff_id = 2;
}
message GetDocumentTextResponse {
optional string content = 1;
}
message ReplaceTextRequest {
optional cline.Metadata metadata = 1;
optional string diff_id = 2;
@@ -34,6 +53,33 @@ message ReplaceTextRequest {
optional int32 end_line = 5;
}
message ReplaceTextResponse {
// TBD
message ReplaceTextResponse {}
message ScrollDiffRequest {
optional string diff_id = 1;
optional int32 line = 2;
}
message ScrollDiffResponse {}
message TruncateDocumentRequest {
optional cline.Metadata metadata = 1;
optional string diff_id = 2;
optional int32 end_line = 3;
}
message TruncateDocumentResponse {}
message CloseDiffRequest {
optional cline.Metadata metadata = 1;
optional string diff_id = 2;
}
message CloseDiffResponse {}
message SaveDocumentRequest {
optional cline.Metadata metadata = 1;
optional string diff_id = 2;
}
message SaveDocumentResponse {}
+1 -4
View File
@@ -4,7 +4,7 @@ package host;
option java_package = "bot.cline.host.proto";
option java_multiple_files = true;
import "common.proto";
import "cline/common.proto";
// Provides methods for working with the user's environment.
service EnvService {
@@ -13,7 +13,4 @@ service EnvService {
// Reads text from the system clipboard.
rpc clipboardReadText(cline.EmptyRequest) returns (cline.String);
// Opens a URL in the user's default browser or application.
rpc openExternal(cline.StringRequest) returns (cline.Empty);
}
+5 -1
View File
@@ -4,8 +4,12 @@ package host;
option java_package = "bot.cline.host.proto";
option java_multiple_files = true;
import "common.proto";
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
+60 -1
View File
@@ -4,7 +4,7 @@ package host;
option java_package = "bot.cline.host.proto";
option java_multiple_files = true;
import "common.proto";
import "cline/common.proto";
// Provides methods for working with IDE windows and editors.
service WindowService {
@@ -12,6 +12,11 @@ service WindowService {
rpc showTextDocument(ShowTextDocumentRequest) returns (TextEditorInfo);
rpc showOpenDialogue(ShowOpenDialogueRequest) returns (SelectedResources);
rpc showMessage(ShowMessageRequest) returns (SelectedResponse);
rpc showInputBox(ShowInputBoxRequest) returns (ShowInputBoxResponse);
rpc showSaveDialog(ShowSaveDialogRequest) returns (ShowSaveDialogResponse);
rpc openFile(OpenFileRequest) returns (OpenFileResponse);
rpc getOpenTabs(GetOpenTabsRequest) returns (GetOpenTabsResponse);
rpc getVisibleTabs(GetVisibleTabsRequest) returns (GetVisibleTabsResponse);
}
message ShowTextDocumentRequest {
@@ -70,4 +75,58 @@ message ShowMessageRequestOptions {
message SelectedResponse {
optional string selected_option = 1;
}
message ShowSaveDialogRequest {
cline.Metadata metadata = 1;
optional ShowSaveDialogOptions options = 2;
}
message ShowSaveDialogOptions {
optional string default_path = 1;
map<string, FileExtensionList> filters = 2;
}
message FileExtensionList {
repeated string extensions = 1;
}
message ShowSaveDialogResponse {
optional string selected_path = 1;
}
message ShowInputBoxRequest {
cline.Metadata metadata = 1;
string title = 2;
optional string prompt = 3;
optional string value = 4;
}
message ShowInputBoxResponse {
optional string response = 1;
}
message OpenFileRequest {
cline.Metadata metadata = 1;
string file_path = 2;
}
message OpenFileResponse {
// empty
}
message GetOpenTabsRequest {
// empty
}
message GetOpenTabsResponse {
repeated string paths = 1;
}
message GetVisibleTabsRequest {
// empty
}
message GetVisibleTabsResponse {
repeated string paths = 1;
}
+9
View File
@@ -4,10 +4,14 @@ package host;
option java_package = "bot.cline.host.proto";
option java_multiple_files = true;
import "cline/common.proto";
// Provides methods for working with workspaces/projects.
service WorkspaceService {
// Returns a list of the top level directories of the workspace.
rpc getWorkspacePaths(GetWorkspacePathsRequest) returns (GetWorkspacePathsResponse);
// Saves an open document if it's dirty
rpc saveOpenDocumentIfDirty(SaveOpenDocumentIfDirtyRequest) returns (cline.Empty);
}
message GetWorkspacePathsRequest {
@@ -22,3 +26,8 @@ message GetWorkspacePathsResponse {
optional string id = 1;
repeated string paths = 2;
}
message SaveOpenDocumentIfDirtyRequest {
cline.Metadata metadata = 1;
string file_path = 2;
}
-243
View File
@@ -1,243 +0,0 @@
syntax = "proto3";
package cline;
import "common.proto";
option java_package = "bot.cline.proto";
option java_multiple_files = true;
// Service for model-related operations
service ModelsService {
// Fetches available models from Ollama
rpc getOllamaModels(StringRequest) returns (StringArray);
// Fetches available models from LM Studio
rpc getLmStudioModels(StringRequest) returns (StringArray);
// Fetches available models from VS Code LM API
rpc getVsCodeLmModels(EmptyRequest) returns (VsCodeLmModelsArray);
// Refreshes and returns OpenRouter models
rpc refreshOpenRouterModels(EmptyRequest) returns (OpenRouterCompatibleModelInfo);
// Refreshes and returns OpenAI models
rpc refreshOpenAiModels(OpenAiModelsRequest) returns (StringArray);
// Refreshes and returns Requesty models
rpc refreshRequestyModels(EmptyRequest) returns (OpenRouterCompatibleModelInfo);
// Subscribe to OpenRouter models updates
rpc subscribeToOpenRouterModels(EmptyRequest) returns (stream OpenRouterCompatibleModelInfo);
// Updates API configuration
rpc updateApiConfigurationProto(UpdateApiConfigurationRequest) returns (Empty);
}
// List of VS Code LM models
message VsCodeLmModelsArray {
repeated LanguageModelChatSelector models = 1;
}
// Structure representing a language model chat selector
message LanguageModelChatSelector {
optional string vendor = 1;
optional string family = 2;
optional string version = 3;
optional string id = 4;
}
// Price tier for tiered pricing models
message PriceTier {
int32 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 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;
optional double input_price = 2;
optional double output_price = 3;
optional double cache_writes_price = 4;
optional double cache_reads_price = 5;
}
// For OpenRouterCompatibleModelInfo structure in OpenRouterModels
message OpenRouterModelInfo {
optional int32 max_tokens = 1;
optional int32 context_window = 2;
optional bool supports_images = 3;
bool supports_prompt_cache = 4;
optional double input_price = 5;
optional double output_price = 6;
optional double cache_writes_price = 7;
optional double cache_reads_price = 8;
optional string description = 9;
optional ThinkingConfig thinking_config = 10;
optional bool supports_global_endpoint = 11;
repeated ModelTier tiers = 12;
}
// Shared response message for model information
message OpenRouterCompatibleModelInfo {
map<string, OpenRouterModelInfo> models = 1;
}
// Request for fetching OpenAI models
message OpenAiModelsRequest {
Metadata metadata = 1;
string base_url = 2;
string api_key = 3;
}
// Request for updating API configuration
message UpdateApiConfigurationRequest {
Metadata metadata = 1;
ModelsApiConfiguration api_configuration = 2;
}
// API Provider enumeration
enum ApiProvider {
ANTHROPIC = 0;
OPENROUTER = 1;
BEDROCK = 2;
VERTEX = 3;
OPENAI = 4;
OLLAMA = 5;
LMSTUDIO = 6;
GEMINI = 7;
OPENAI_NATIVE = 8;
REQUESTY = 9;
TOGETHER = 10;
DEEPSEEK = 11;
QWEN = 12;
DOUBAO = 13;
MISTRAL = 14;
VSCODE_LM = 15;
CLINE = 16;
LITELLM = 17;
NEBIUS = 18;
FIREWORKS = 19;
ASKSAGE = 20;
XAI = 21;
SAMBANOVA = 22;
CEREBRAS = 23;
SAPAICORE = 24;
CLAUDE_CODE = 25;
MOONSHOT = 26;
}
// Model info for OpenAI-compatible models
message OpenAiCompatibleModelInfo {
optional int32 max_tokens = 1;
optional int32 context_window = 2;
optional bool supports_images = 3;
bool supports_prompt_cache = 4;
optional double input_price = 5;
optional double output_price = 6;
optional ThinkingConfig thinking_config = 7;
optional bool supports_global_endpoint = 8;
optional double cache_writes_price = 9;
optional double cache_reads_price = 10;
optional string description = 11;
repeated ModelTier tiers = 12;
optional double temperature = 13;
optional bool is_r1_format_required = 14;
}
// Model info for LiteLLM models
message LiteLLMModelInfo {
optional int32 max_tokens = 1;
optional int32 context_window = 2;
optional bool supports_images = 3;
bool supports_prompt_cache = 4;
optional double input_price = 5;
optional double output_price = 6;
optional ThinkingConfig thinking_config = 7;
optional bool supports_global_endpoint = 8;
optional double cache_writes_price = 9;
optional double cache_reads_price = 10;
optional string description = 11;
repeated ModelTier tiers = 12;
optional double temperature = 13;
}
// Main ApiConfiguration message
message ModelsApiConfiguration {
// From ApiHandlerOptions (excluding onRetryAttempt function)
optional string api_model_id = 1;
optional string api_key = 2;
optional string cline_account_id = 3;
optional string task_id = 4;
optional string lite_llm_base_url = 5;
optional string lite_llm_model_id = 6;
optional string lite_llm_api_key = 7;
optional bool lite_llm_use_prompt_cache = 8;
map<string, string> open_ai_headers = 9;
optional LiteLLMModelInfo lite_llm_model_info = 10;
optional string anthropic_base_url = 11;
optional string open_router_api_key = 12;
optional string open_router_model_id = 13;
optional OpenRouterModelInfo open_router_model_info = 14;
optional string open_router_provider_sorting = 15;
optional string aws_access_key = 16;
optional string aws_secret_key = 17;
optional string aws_session_token = 18;
optional string aws_region = 19;
optional bool aws_use_cross_region_inference = 20;
optional bool aws_bedrock_use_prompt_cache = 21;
optional bool aws_use_profile = 22;
optional string aws_profile = 23;
optional string aws_bedrock_endpoint = 24;
optional bool aws_bedrock_custom_selected = 25;
optional string aws_bedrock_custom_model_base_id = 26;
optional string vertex_project_id = 27;
optional string vertex_region = 28;
optional string open_ai_base_url = 29;
optional string open_ai_api_key = 30;
optional string open_ai_model_id = 31;
optional OpenAiCompatibleModelInfo open_ai_model_info = 32;
optional string ollama_model_id = 33;
optional string ollama_base_url = 34;
optional string ollama_api_options_ctx_num = 35;
optional string lm_studio_model_id = 36;
optional string lm_studio_base_url = 37;
optional string gemini_api_key = 38;
optional string gemini_base_url = 39;
optional string open_ai_native_api_key = 40;
optional string deep_seek_api_key = 41;
optional string requesty_api_key = 42;
optional string requesty_model_id = 43;
optional OpenRouterModelInfo requesty_model_info = 44;
optional string together_api_key = 45;
optional string together_model_id = 46;
optional string fireworks_api_key = 47;
optional string fireworks_model_id = 48;
optional int32 fireworks_model_max_completion_tokens = 49;
optional int32 fireworks_model_max_tokens = 50;
optional string qwen_api_key = 51;
optional string doubao_api_key = 52;
optional string mistral_api_key = 53;
optional string azure_api_version = 54;
optional LanguageModelChatSelector vs_code_lm_model_selector = 55;
optional string qwen_api_line = 56;
optional string nebius_api_key = 57;
optional string asksage_api_url = 58;
optional string asksage_api_key = 59;
optional string xai_api_key = 60;
optional int32 thinking_budget_tokens = 61;
optional string reasoning_effort = 62;
optional string sambanova_api_key = 63;
optional string cerebras_api_key = 64;
optional int32 request_timeout_ms = 65;
optional ApiProvider api_provider = 66;
repeated string favorited_model_ids = 67;
optional string sap_ai_core_client_id = 68;
optional string sap_ai_core_client_secret = 69;
optional string sap_ai_resource_group = 70;
optional string sap_ai_core_token_url = 71;
optional string sap_ai_core_base_url = 72;
optional string claude_code_path = 73;
optional string aws_authentication = 74;
optional string aws_bedrock_api_key = 75;
optional string moonshot_api_key = 76;
optional string moonshot_api_line = 77;
}
-243
View File
@@ -1,243 +0,0 @@
syntax = "proto3";
package cline;
import "common.proto";
option java_package = "bot.cline.proto";
option java_multiple_files = true;
service StateService {
rpc getLatestState(EmptyRequest) returns (State);
rpc updateTerminalConnectionTimeout(Int64Request) returns (Int64);
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);
rpc resetState(ResetStateRequest) returns (Empty);
rpc togglePlanActMode(TogglePlanActModeRequest) returns (Boolean);
rpc updateAutoApprovalSettings(AutoApprovalSettingsRequest) returns (Empty);
rpc updateSettings(UpdateSettingsRequest) returns (Empty);
rpc updateTelemetrySetting(TelemetrySettingRequest) returns (Empty);
rpc setWelcomeViewCompleted(BooleanRequest) returns (Empty);
}
message State {
string state_json = 1;
}
message TerminalProfiles {
repeated TerminalProfile profiles = 1;
}
message TerminalProfile {
string id = 1;
string name = 2;
optional string path = 3;
optional string description = 4;
}
message TerminalProfileUpdateResponse {
int32 closed_count = 1;
int32 busy_terminals_count = 2;
bool has_busy_terminals = 3;
}
message TogglePlanActModeRequest {
Metadata metadata = 1;
ChatSettings chat_settings = 2;
optional ChatContent chat_content = 3;
}
enum PlanActMode {
PLAN = 0;
ACT = 1;
}
message ChatSettings {
PlanActMode mode = 1;
optional string preferred_language = 2;
optional string open_ai_reasoning_effort = 3;
}
message ChatContent {
optional string message = 1;
repeated string images = 2;
repeated string files = 3;
}
message ResetStateRequest {
Metadata metadata = 1;
optional bool global = 2;
}
message AutoApprovalSettingsRequest {
Metadata metadata = 1;
message Actions {
bool read_files = 1;
bool read_files_externally = 2;
bool edit_files = 3;
bool edit_files_externally = 4;
bool execute_safe_commands = 5;
bool execute_all_commands = 6;
bool use_browser = 7;
bool use_mcp = 8;
}
int32 version = 2;
bool enabled = 3;
Actions actions = 4;
int32 max_requests = 5;
bool enable_notifications = 6;
repeated string favorites = 7;
}
enum TelemetrySettingEnum {
UNSET = 0;
ENABLED = 1;
DISABLED = 2;
}
message TelemetrySettingRequest {
Metadata metadata = 1;
TelemetrySettingEnum setting = 2;
}
// Message for updating settings
message UpdateSettingsRequest {
Metadata metadata = 1;
optional ApiConfiguration api_configuration = 2;
optional string telemetry_setting = 3;
optional bool plan_act_separate_models_setting = 4;
optional bool enable_checkpoints_setting = 5;
optional bool mcp_marketplace_enabled = 6;
optional ChatSettings chat_settings = 7;
optional int64 shell_integration_timeout = 8;
optional bool terminal_reuse_enabled = 9;
optional bool mcp_responses_collapsed = 10;
optional string mcp_display_mode = 11;
optional int64 terminal_output_line_limit = 12;
}
// Complete API Configuration message
message ApiConfiguration {
// Core API fields
optional string api_provider = 1;
optional string api_model_id = 2;
optional string api_key = 3; // anthropic
optional string api_base_url = 4;
// Provider-specific API keys
optional string cline_account_id = 5;
optional string openrouter_api_key = 6;
optional string anthropic_base_url = 7;
optional string openai_api_key = 8;
optional string openai_native_api_key = 9;
optional string gemini_api_key = 10;
optional string deepseek_api_key = 11;
optional string requesty_api_key = 12;
optional string together_api_key = 13;
optional string fireworks_api_key = 14;
optional string qwen_api_key = 15;
optional string doubao_api_key = 16;
optional string mistral_api_key = 17;
optional string nebius_api_key = 18;
optional string asksage_api_key = 19;
optional string xai_api_key = 20;
optional string sambanova_api_key = 21;
optional string cerebras_api_key = 22;
// Model IDs
optional string openrouter_model_id = 23;
optional string openai_model_id = 24;
optional string anthropic_model_id = 25;
optional string bedrock_model_id = 26;
optional string vertex_model_id = 27;
optional string gemini_model_id = 28;
optional string ollama_model_id = 29;
optional string lm_studio_model_id = 30;
optional string litellm_model_id = 31;
optional string requesty_model_id = 32;
optional string together_model_id = 33;
optional string fireworks_model_id = 34;
// AWS Bedrock fields
optional bool aws_bedrock_custom_selected = 35;
optional string aws_bedrock_custom_model_base_id = 36;
optional string aws_access_key = 37;
optional string aws_secret_key = 38;
optional string aws_session_token = 39;
optional string aws_region = 40;
optional bool aws_use_cross_region_inference = 41;
optional bool aws_bedrock_use_prompt_cache = 42;
optional bool aws_use_profile = 43;
optional string aws_profile = 44;
optional string aws_bedrock_endpoint = 45;
// Vertex AI fields
optional string vertex_project_id = 46;
optional string vertex_region = 47;
// Base URLs and endpoints
optional string openai_base_url = 48;
optional string ollama_base_url = 49;
optional string lm_studio_base_url = 50;
optional string gemini_base_url = 51;
optional string litellm_base_url = 52;
optional string asksage_api_url = 53;
// LiteLLM specific fields
optional string litellm_api_key = 54;
optional bool litellm_use_prompt_cache = 55;
// Model configuration
optional int64 thinking_budget_tokens = 56;
optional string reasoning_effort = 57;
optional int64 request_timeout_ms = 58;
// Fireworks specific
optional int64 fireworks_model_max_completion_tokens = 59;
optional int64 fireworks_model_max_tokens = 60;
// Azure specific
optional string azure_api_version = 61;
// Ollama specific
optional string ollama_api_options_ctx_num = 62;
// Qwen specific
optional string qwen_api_line = 63;
// OpenRouter specific
optional string openrouter_provider_sorting = 64;
// VSCode LM (stored as JSON string due to complex type)
optional string vscode_lm_model_selector = 65;
// Model info objects (stored as JSON strings)
optional string openrouter_model_info = 66;
optional string openai_model_info = 67;
optional string requesty_model_info = 68;
optional string litellm_model_info = 69;
// OpenAI headers (stored as JSON string)
optional string openai_headers = 70;
// Favorited model IDs
repeated string favorited_model_ids = 71;
// SAP AI Core specific
optional string sap_ai_core_client_id = 72;
optional string sap_ai_core_client_secret = 73;
optional string sap_ai_core_base_url = 74;
optional string sap_ai_core_token_url = 75;
optional string sap_ai_resource_group = 76;
// Claude Code specific
optional string claude_code_path = 77;
// Extension fields for Bedrock Api Keys
optional string aws_authentication = 78;
optional string aws_bedrock_api_key = 79;
// Moonshot
optional string moonshot_api_key = 80;
optional string moonshot_api_line = 81;
}
-32
View File
@@ -1,32 +0,0 @@
// Configuration file for protocol buffer build scripts
// Contains service name mappings used by both build-proto.js and build-go-proto.js
// List of gRPC services
// To add a new service, simply add it to this map and run the build scripts
// The service handler will be automatically discovered and used by grpc-handler.ts
export const serviceNameMap = {
account: "cline.AccountService",
browser: "cline.BrowserService",
checkpoints: "cline.CheckpointsService",
file: "cline.FileService",
mcp: "cline.McpService",
state: "cline.StateService",
task: "cline.TaskService",
web: "cline.WebService",
models: "cline.ModelsService",
slash: "cline.SlashService",
ui: "cline.UiService",
// Add new services here - no other code changes needed!
}
// List of host gRPC services (IDE API bridge)
// These services are implemented in the IDE extension and called by the standalone Cline Core
export const hostServiceNameMap = {
uri: "host.UriService",
watch: "host.WatchService",
workspace: "host.WorkspaceService",
env: "host.EnvService",
window: "host.WindowService",
diff: "host.DiffService",
// Add new host services here
}
+94 -527
View File
@@ -1,21 +1,20 @@
#!/usr/bin/env node
import * as fs from "fs/promises"
import * as path from "path"
import { fileURLToPath } from "url"
import { execSync } from "child_process"
import { globby } from "globby"
import chalk from "chalk"
import os from "os"
import { execSync } from "child_process"
import * as fs from "fs/promises"
import { globby } from "globby"
import { createRequire } from "module"
import { serviceNameMap, hostServiceNameMap } from "./build-proto-config.mjs"
import os from "os"
import * as path from "path"
import { rmrf } from "./file-utils.mjs"
import { main as generateProtoBusSetup } from "./generate-protobus-setup.mjs"
import { main as generateHostBridgeClient } from "./generate-host-bridge-client.mjs"
import { loadProtoDescriptorSet } from "./proto-utils.mjs"
const require = createRequire(import.meta.url)
const PROTOC = path.join(require.resolve("grpc-tools"), "../bin/protoc")
const SCRIPT_NAME = path.relative(process.cwd(), fileURLToPath(import.meta.url))
const PROTO_DIR = path.resolve("proto")
const TS_OUT_DIR = path.resolve("src/shared/proto")
const GRPC_JS_OUT_DIR = path.resolve("src/generated/grpc-js")
@@ -36,11 +35,15 @@ const TS_PROTO_OPTIONS = [
"useDate=false", // Timestamp fields will not be automatically converted to Date.
]
// Service directories derived from imported serviceNameMap
const serviceDirs = Object.keys(serviceNameMap).map((serviceKey) => path.join("src/core/controller", serviceKey))
async function main() {
console.log(chalk.bold.blue("Starting Protocol Buffer code generation..."))
await cleanup()
await compileProtos()
await checkProtos()
await generateProtoBusSetup()
await generateHostBridgeClient()
}
async function compileProtos() {
console.log(chalk.bold.blue("Compiling Protocol Buffers..."))
// Check for Apple Silicon compatibility before proceeding
checkAppleSiliconCompatibility()
@@ -50,11 +53,6 @@ async function main() {
await fs.mkdir(dir, { recursive: true })
}
await cleanup()
// Check for missing proto files for services in serviceNameMap
await ensureProtoFilesExist()
// Process all proto files
const protoFiles = await globby("**/*.proto", { cwd: PROTO_DIR, realpath: true })
console.log(chalk.cyan(`Processing ${protoFiles.length} proto files from`), PROTO_DIR)
@@ -83,15 +81,6 @@ async function main() {
log_verbose(chalk.green("Protocol Buffer code generation completed successfully."))
log_verbose(chalk.green(`TypeScript files generated in: ${TS_OUT_DIR}`))
await generateProtoBusServiceConfig()
await generateProtoBusMethodRegistrations()
await generateProtoBusGrpcClientConfig()
await generateHostBridgeServiceConfig()
await generateHostBridgeMethodRegistrations()
console.log(chalk.bold.blue("Finished Protocol Buffer code generation."))
}
async function tsProtoc(outDir, protoFiles, protoOptions) {
@@ -114,486 +103,17 @@ async function tsProtoc(outDir, protoFiles, protoOptions) {
}
}
/**
* Generate a gRPC client configuration file for the webview
* This eliminates the need for manual imports and client creation in grpc-client.ts
*/
async function generateProtoBusGrpcClientConfig() {
log_verbose(chalk.cyan("Generating gRPC client configuration..."))
const serviceImports = []
const serviceClientCreations = []
const serviceExports = []
// Process each service in the serviceNameMap
for (const [dirName, _fullServiceName] of Object.entries(serviceNameMap)) {
const capitalizedName = dirName.charAt(0).toUpperCase() + dirName.slice(1)
// Add import statement
serviceImports.push(`import { ${capitalizedName}ServiceDefinition } from "@shared/proto/${dirName}"`)
// Add client creation
serviceClientCreations.push(
`const ${capitalizedName}ServiceClient = createGrpcClient(${capitalizedName}ServiceDefinition)`,
)
// Add to exports
serviceExports.push(`${capitalizedName}ServiceClient`)
}
// Generate the file content
const content = `// AUTO-GENERATED FILE - DO NOT MODIFY DIRECTLY
// Generated by ${SCRIPT_NAME}
import { createGrpcClient } from "./grpc-client-base"
${serviceImports.join("\n")}
${serviceClientCreations.join("\n")}
export {
${serviceExports.join(",\n\t")}
}`
const filePath = path.resolve("webview-ui/src/services/grpc-client.ts")
await writeFileWithMkdirs(filePath, content)
log_verbose(chalk.green(`Generated gRPC client at ${filePath}`))
}
/**
* Parse proto files to extract streaming method information
* @param protoFiles Array of proto file names
* @param scriptDir Directory containing proto files
* @returns Map of service names to their streaming methods
*/
async function parseProtoForStreamingMethods(protoFiles, scriptDir) {
log_verbose(chalk.cyan("Parsing proto files for streaming methods..."))
// Map of service name to array of streaming method names
const streamingMethodsMap = new Map()
for (const protoFile of protoFiles) {
const content = await fs.readFile(path.join(scriptDir, protoFile), "utf8")
// Extract package name
const packageMatch = content.match(/package\s+([^;]+);/)
const packageName = packageMatch ? packageMatch[1].trim() : "unknown"
// Extract service definitions
const serviceMatches = Array.from(content.matchAll(/service\s+(\w+)\s*\{([^}]+)\}/g))
for (const serviceMatch of serviceMatches) {
const serviceName = serviceMatch[1]
const serviceBody = serviceMatch[2]
const fullServiceName = `${packageName}.${serviceName}`
// Extract method definitions with streaming
const methodMatches = Array.from(
serviceBody.matchAll(/rpc\s+(\w+)\s*\(\s*(stream\s+)?(\w+)\s*\)\s*returns\s*\(\s*(stream\s+)?(\w+)\s*\)/g),
)
const streamingMethods = []
for (const methodMatch of methodMatches) {
const methodName = methodMatch[1]
const isRequestStreaming = !!methodMatch[2]
const requestType = methodMatch[3]
const isResponseStreaming = !!methodMatch[4]
const responseType = methodMatch[5]
if (isResponseStreaming) {
streamingMethods.push({
name: methodName,
requestType,
responseType,
isRequestStreaming,
})
}
}
if (streamingMethods.length > 0) {
streamingMethodsMap.set(fullServiceName, streamingMethods)
}
}
}
return streamingMethodsMap
}
async function generateProtoBusMethodRegistrations() {
log_verbose(chalk.cyan("Generating method registration files..."))
// Parse proto files for streaming methods
const protoFiles = await globby("*.proto", { cwd: PROTO_DIR })
const streamingMethodsMap = await parseProtoForStreamingMethods(protoFiles, PROTO_DIR)
for (const serviceDir of serviceDirs) {
const serviceName = path.basename(serviceDir)
const fullServiceName = serviceNameMap[serviceName]
const streamingMethods = streamingMethodsMap.get(fullServiceName) || []
log_verbose(chalk.cyan(`Generating method registrations for ${serviceName}...`))
// Get all TypeScript files in the service directory
const files = await globby("*.ts", { cwd: serviceDir })
// Filter out index.ts and methods.ts
const implementationFiles = files.filter((file) => file !== "index.ts" && file !== "methods.ts")
// Create the methods.ts file with header
let methodsContent = `// AUTO-GENERATED FILE - DO NOT MODIFY DIRECTLY
// Generated by ${SCRIPT_NAME}
// Import all method implementations
import { registerMethod } from "./index"\n`
// Import implementations directly
for (const file of implementationFiles) {
const baseName = path.basename(file, ".ts")
methodsContent += `import { ${baseName} } from "./${baseName}"\n`
}
// Add streaming methods information
if (streamingMethods.length > 0) {
methodsContent += `\n// Streaming methods for this service
export const streamingMethods = ${JSON.stringify(
streamingMethods.map((m) => m.name),
null,
2,
)}\n`
}
// Add registration function
methodsContent += `\n// Register all ${serviceName} service methods
export function registerAllMethods(): void {
\t// Register each method with the registry\n`
// Add registration statements
for (const file of implementationFiles) {
const baseName = path.basename(file, ".ts")
const isStreaming = streamingMethods.some((m) => m.name === baseName)
if (isStreaming) {
methodsContent += `\tregisterMethod("${baseName}", ${baseName}, { isStreaming: true })\n`
} else {
methodsContent += `\tregisterMethod("${baseName}", ${baseName})\n`
}
}
// Close the function
methodsContent += `}`
// Write the methods.ts file
const registryFile = path.join(serviceDir, "methods.ts")
await writeFileWithMkdirs(registryFile, methodsContent)
log_verbose(chalk.green(`Generated ${registryFile}`))
// Generate index.ts file
const capitalizedServiceName = serviceName.charAt(0).toUpperCase() + serviceName.slice(1)
const indexContent = `// AUTO-GENERATED FILE - DO NOT MODIFY DIRECTLY
// Generated by ${SCRIPT_NAME}
import { createServiceRegistry, ServiceMethodHandler, StreamingMethodHandler } from "../grpc-service"
import { StreamingResponseHandler } from "../grpc-handler"
import { registerAllMethods } from "./methods"
// Create ${serviceName} service registry
const ${serviceName}Service = createServiceRegistry("${serviceName}")
// Export the method handler types and registration function
export type ${capitalizedServiceName}MethodHandler = ServiceMethodHandler
export type ${capitalizedServiceName}StreamingMethodHandler = StreamingMethodHandler
export const registerMethod = ${serviceName}Service.registerMethod
// Export the request handlers
export const handle${capitalizedServiceName}ServiceRequest = ${serviceName}Service.handleRequest
export const handle${capitalizedServiceName}ServiceStreamingRequest = ${serviceName}Service.handleStreamingRequest
export const isStreamingMethod = ${serviceName}Service.isStreamingMethod
// Register all ${serviceName} methods
registerAllMethods()`
// Write the index.ts file
const indexFile = path.join(serviceDir, "index.ts")
await writeFileWithMkdirs(indexFile, indexContent)
log_verbose(chalk.green(`Generated ${indexFile}`))
}
log_verbose(chalk.green("Method registration files generated successfully."))
}
/**
* Generate a service configuration file that maps service names to their handlers
* This eliminates the need for manual switch/case statements in grpc-handler.ts
*/
async function generateProtoBusServiceConfig() {
log_verbose(chalk.cyan("Generating service configuration file..."))
const serviceImports = []
const serviceConfigs = []
// Add all services from the serviceNameMap
for (const [dirName, fullServiceName] of Object.entries(serviceNameMap)) {
const capitalizedName = dirName.charAt(0).toUpperCase() + dirName.slice(1)
serviceImports.push(
`import { handle${capitalizedName}ServiceRequest, handle${capitalizedName}ServiceStreamingRequest } from "./${dirName}/index"`,
)
serviceConfigs.push(`
"${fullServiceName}": {
requestHandler: handle${capitalizedName}ServiceRequest,
streamingHandler: handle${capitalizedName}ServiceStreamingRequest
}`)
}
const content = `// AUTO-GENERATED FILE - DO NOT MODIFY DIRECTLY
// Generated by ${SCRIPT_NAME}
import { Controller } from "./index"
import { StreamingResponseHandler } from "./grpc-handler"
${serviceImports.join("\n")}
/**
* Configuration for a service handler
*/
export interface ServiceHandlerConfig {
requestHandler: (controller: Controller, method: string, message: any) => Promise<any>;
streamingHandler: (controller: Controller, method: string, message: any, responseStream: StreamingResponseHandler, requestId?: string) => Promise<void>;
}
/**
* Map of service names to their handler configurations
*/
export const serviceHandlers: Record<string, ServiceHandlerConfig> = {${serviceConfigs.join(",")}
};`
const configPath = path.resolve("src/core/controller/grpc-service-config.ts")
await writeFileWithMkdirs(configPath, content)
log_verbose(chalk.green(`Generated service configuration at ${configPath}`))
}
/**
* Ensure that a .proto file exists for each service in the serviceNameMap
* If a .proto file doesn't exist, create a template file
*/
async function ensureProtoFilesExist() {
log_verbose(chalk.cyan("Checking for missing proto files..."))
// Get existing proto files
const existingProtoFiles = await globby("*.proto", { cwd: PROTO_DIR })
const existingProtoServices = existingProtoFiles.map((file) => path.basename(file, ".proto"))
// Check each service in serviceNameMap
for (const [serviceName, fullServiceName] of Object.entries(serviceNameMap)) {
if (!existingProtoServices.includes(serviceName)) {
log_verbose(chalk.yellow(`Creating template proto file for ${serviceName}...`))
// Extract service class name from full name (e.g., "cline.ModelsService" -> "ModelsService")
const serviceClassName = fullServiceName.split(".").pop()
// Create template proto file
const protoContent = `syntax = "proto3";
package cline;
option java_package = "bot.cline.proto";
option java_multiple_files = true;
import "common.proto";
// ${serviceClassName} provides methods for managing ${serviceName}
service ${serviceClassName} {
// Add your RPC methods here
// Example (String is from common.proto, responses should be generic types):
// rpc YourMethod(YourRequest) returns (String);
}
// Add your message definitions here
// Example (Requests must always start with Metadata):
// message YourRequest {
// Metadata metadata = 1;
// string stringField = 2;
// int32 int32Field = 3;
// }
`
// Write the template proto file
const protoFilePath = path.join(PROTO_DIR, `${serviceName}.proto`)
await fs.writeFile(protoFilePath, protoContent)
log_verbose(chalk.green(`Created template proto file at ${protoFilePath}`))
}
}
}
/**
* Generate method registration files for host services
*/
async function generateHostBridgeMethodRegistrations() {
log_verbose(chalk.cyan("Generating host method registration files..."))
// Host service directories derived from imported hostServiceNameMap
const hostServiceDirs = Object.keys(hostServiceNameMap).map((serviceKey) =>
path.join("src/hosts/vscode/hostbridge", serviceKey),
)
// Parse proto files for streaming methods
const hostProtoFiles = await globby("*.proto", { cwd: path.join(PROTO_DIR, "host") })
const streamingMethodsMap = await parseProtoForStreamingMethods(hostProtoFiles, path.join(PROTO_DIR, "host"))
for (const serviceDir of hostServiceDirs) {
const serviceName = path.basename(serviceDir)
const fullServiceName = hostServiceNameMap[serviceName]
const streamingMethods = streamingMethodsMap.get(fullServiceName) || []
const outputDir = path.join("src/generated/hosts/vscode/hostbridge", serviceName)
log_verbose(chalk.cyan(`Generating method registrations for host ${serviceName}...`))
// Get all TypeScript files in the service directory
const files = await globby("*.ts", { cwd: serviceDir })
// Filter out index.ts and methods.ts
const implementationFiles = files.filter((file) => file !== "index.ts" && file !== "methods.ts")
// Create the methods.ts file with header
let methodsContent = `// AUTO-GENERATED FILE - DO NOT MODIFY DIRECTLY
// Generated ${SCRIPT_NAME}
// Import all method implementations
import { registerMethod } from "./index"\n`
// Import implementations directly
for (const file of implementationFiles) {
const baseName = path.basename(file, ".ts")
methodsContent += `import { ${baseName} } from "@hosts/vscode/hostbridge/${serviceName}/${baseName}"\n`
}
// Add streaming methods information
if (streamingMethods.length > 0) {
methodsContent += `\n// Streaming methods for this service
export const streamingMethods = ${JSON.stringify(
streamingMethods.map((m) => m.name),
null,
2,
)}\n`
}
// Add registration function
methodsContent += `\n// Register all ${serviceName} service methods
export function registerAllMethods(): void {
\t// Register each method with the registry\n`
// Add registration statements
for (const file of implementationFiles) {
const baseName = path.basename(file, ".ts")
const isStreaming = streamingMethods.some((m) => m.name === baseName)
if (isStreaming) {
methodsContent += `\tregisterMethod("${baseName}", ${baseName}, { isStreaming: true })\n`
} else {
methodsContent += `\tregisterMethod("${baseName}", ${baseName})\n`
}
}
// Close the function
methodsContent += `}`
// Write the methods.ts file
const registryFile = path.join(outputDir, "methods.ts")
await writeFileWithMkdirs(registryFile, methodsContent)
log_verbose(chalk.green(`Generated ${registryFile}`))
// Generate index.ts file
const capitalizedServiceName = serviceName.charAt(0).toUpperCase() + serviceName.slice(1)
const indexContent = `// AUTO-GENERATED FILE - DO NOT MODIFY DIRECTLY
// Generated by ${SCRIPT_NAME}
import { createServiceRegistry, ServiceMethodHandler, StreamingMethodHandler } from "@hosts/vscode/hostbridge-grpc-service"
import { StreamingResponseHandler } from "@hosts/vscode/hostbridge-grpc-handler"
import { registerAllMethods } from "./methods"
// Create ${serviceName} service registry
const ${serviceName}Service = createServiceRegistry("${serviceName}")
// Export the method handler types and registration function
export type ${capitalizedServiceName}MethodHandler = ServiceMethodHandler
export type ${capitalizedServiceName}StreamingMethodHandler = StreamingMethodHandler
export const registerMethod = ${serviceName}Service.registerMethod
// Export the request handlers
export const handle${capitalizedServiceName}ServiceRequest = ${serviceName}Service.handleRequest
export const handle${capitalizedServiceName}ServiceStreamingRequest = ${serviceName}Service.handleStreamingRequest
export const isStreamingMethod = ${serviceName}Service.isStreamingMethod
// Register all ${serviceName} methods
registerAllMethods()`
// Write the index.ts file
const indexFile = path.join(outputDir, "index.ts")
await writeFileWithMkdirs(indexFile, indexContent)
log_verbose(chalk.green(`Generated ${indexFile}`))
}
log_verbose(chalk.green("Host method registration files generated successfully."))
}
/**
* Generate a service configuration file for host services
*/
async function generateHostBridgeServiceConfig() {
log_verbose(chalk.cyan("Generating host service configuration file..."))
const serviceImports = []
const serviceConfigs = []
// Add all services from the hostServiceNameMap
for (const [dirName, fullServiceName] of Object.entries(hostServiceNameMap)) {
const capitalizedName = dirName.charAt(0).toUpperCase() + dirName.slice(1)
serviceImports.push(
`import { handle${capitalizedName}ServiceRequest, handle${capitalizedName}ServiceStreamingRequest } from "@generated/hosts/vscode/hostbridge/${dirName}/index"`,
)
serviceConfigs.push(`
"${fullServiceName}": {
requestHandler: handle${capitalizedName}ServiceRequest,
streamingHandler: handle${capitalizedName}ServiceStreamingRequest
}`)
}
const content = `// AUTO-GENERATED FILE - DO NOT MODIFY DIRECTLY
// Generated by ${SCRIPT_NAME}
import { StreamingResponseHandler } from "@/hosts/vscode/hostbridge-grpc-handler"
${serviceImports.join("\n")}
/**
* Configuration for a host service handler
*/
export interface HostServiceHandlerConfig {
requestHandler: (method: string, message: any) => Promise<any>;
streamingHandler: (method: string, message: any, responseStream: StreamingResponseHandler, requestId?: string) => Promise<void>;
}
/**
* Map of host service names to their handler configurations
*/
export const hostServiceHandlers: Record<string, HostServiceHandlerConfig> = {${serviceConfigs.join(",")}
};`
const filePath = "src/generated/hosts/vscode/hostbridge-grpc-service-config.ts"
await writeFileWithMkdirs(filePath, content)
log_verbose(chalk.green(`Generated host service configuration at ${filePath}`))
}
async function cleanup() {
// Clean up existing generated files
log_verbose(chalk.cyan("Cleaning up existing generated TypeScript files..."))
const existingFiles = await globby("**/*.ts", { cwd: TS_OUT_DIR })
for (const file of existingFiles) {
await fs.unlink(path.join(TS_OUT_DIR, file))
}
await rmdir("src/generated")
await rmrf(TS_OUT_DIR)
await rmrf("src/generated")
// Clean up generated files that were moved.
await fs.rm("src/standalone/services/host-grpc-client.ts", { force: true })
await rmdir("src/standalone/services")
await fs.rm("hosts/vscode", { force: true, recursive: true })
await rmdir("hosts")
await fs.rm("src/standalone/server-setup.ts", { force: true })
await fs.rm("src/hosts/vscode/host-grpc-service-config.ts", { force: true })
await rmrf("src/standalone/services/host-grpc-client.ts")
await rmrf("src/standalone/server-setup.ts")
await rmrf("src/hosts/vscode/host-grpc-service-config.ts")
await rmrf("src/core/controller/grpc-service-config.ts")
const oldhostbridgefiles = [
"src/hosts/vscode/workspace/methods.ts",
"src/hosts/vscode/workspace/index.ts",
@@ -608,30 +128,32 @@ async function cleanup() {
"src/hosts/vscode/uri/methods.ts",
"src/hosts/vscode/uri/index.ts",
]
for (const file of oldhostbridgefiles) {
await fs.rm(file, { force: true })
}
}
/**
* Write `contents` to `filePath`, creating any necessary directories in `filePath`.
*/
async function writeFileWithMkdirs(filePath, content) {
await fs.mkdir(path.dirname(filePath), { recursive: true })
await fs.writeFile(filePath, content)
}
/**
* Remove an empty dir, do nothing if the directory doesn't exist or is not empty.
*/
async function rmdir(path) {
try {
await fs.rmdir(path)
} catch (error) {
if (error.code !== "ENOTEMPTY" && error.code !== "ENOENT") {
// Only re-throw if it's not "not empty" or "doesn't exist"
throw error
}
const oldprotobusfiles = [
"src/core/controller/account/index.ts",
"src/core/controller/account/methods.ts",
"src/core/controller/browser/index.ts",
"src/core/controller/browser/methods.ts",
"src/core/controller/checkpoints/index.ts",
"src/core/controller/checkpoints/methods.ts",
"src/core/controller/file/index.ts",
"src/core/controller/file/methods.ts",
"src/core/controller/mcp/index.ts",
"src/core/controller/mcp/methods.ts",
"src/core/controller/models/index.ts",
"src/core/controller/models/methods.ts",
"src/core/controller/slash/index.ts",
"src/core/controller/slash/methods.ts",
"src/core/controller/state/index.ts",
"src/core/controller/state/methods.ts",
"src/core/controller/task/index.ts",
"src/core/controller/task/methods.ts",
"src/core/controller/ui/index.ts",
"src/core/controller/ui/methods.ts",
"src/core/controller/web/index.ts",
"src/core/controller/web/methods.ts",
]
for (const file of [...oldhostbridgefiles, ...oldprotobusfiles]) {
await rmrf(file)
}
}
@@ -665,6 +187,51 @@ function checkAppleSiliconCompatibility() {
}
}
const int64TypeNames = ["TYPE_INT64", "TYPE_UINT64", "TYPE_SINT64", "TYPE_FIXED64", "TYPE_SFIXED64"]
async function checkProtos() {
const proto = await loadProtoDescriptorSet()
const int64Fields = []
for (const [packageName, packageDef] of Object.entries(proto)) {
for (const [messageName, def] of Object.entries(packageDef)) {
// Skip service definitions
if (def && typeof def === "object" && "service" in def) {
continue
}
// Check message fields
if (def && def.type && def.type.field) {
for (const field of def.type.field) {
if (int64TypeNames.includes(field.type)) {
const name = `${packageName}.${messageName}.${field.name}`
int64Fields.push({
name: name,
type: field.type,
})
}
}
}
}
}
if (int64Fields.length > 0) {
console.log(chalk.yellow(`\nWarning: Found ${int64Fields.length} fields using 64-bit integer types`))
for (const field of int64Fields) {
const typeNames = {
TYPE_INT64: "int64",
TYPE_UINT64: "uint64",
TYPE_SINT64: "sint64",
TYPE_FIXED64: "fixed64",
TYPE_SFIXED64: "sfixed64",
}
log_verbose(chalk.yellow(` - ${field.name} (${typeNames[field.type]})`))
}
log_verbose(chalk.yellow("\nWARNING: 64-bit integer fields detected in proto definitions"))
log_verbose(chalk.yellow("JavaScript cannot safely represent integers larger than 2^53-1 (Number.MAX_SAFE_INTEGER)."))
log_verbose(chalk.yellow("Consider using string representation for large numbers or implementing BigInt support.\n"))
}
}
function log_verbose(s) {
if (process.argv.includes("-v") || process.argv.includes("--verbose")) {
console.log(s)
Regular → Executable
+1
View File
@@ -1,3 +1,4 @@
#!/usr/bin/env node
const { execSync } = require("child_process")
const esbuild = require("esbuild")
+27
View File
@@ -0,0 +1,27 @@
import * as fs from "fs/promises"
import * as path from "path"
/**
* Write `contents` to `filePath`, creating any necessary directories in `filePath`.
*/
export async function writeFileWithMkdirs(filePath, content) {
await fs.mkdir(path.dirname(filePath), { recursive: true })
await fs.writeFile(filePath, content)
}
export async function rmrf(path) {
await fs.rm(path, { force: true, recursive: true })
}
/**
* Remove an empty dir, do nothing if the directory doesn't exist or is not empty.
*/
export async function rmdir(path) {
try {
await fs.rmdir(path)
} catch (error) {
if (error.code !== "ENOTEMPTY" && error.code !== "ENOENT") {
// Only re-throw if it's not "not empty" or "doesn't exist"
throw error
}
}
}
+131 -80
View File
@@ -1,71 +1,40 @@
#!/usr/bin/env node
import * as fs from "fs/promises"
import { writeFileWithMkdirs } from "./file-utils.mjs"
import * as path from "path"
import * as grpc from "@grpc/grpc-js"
import * as protoLoader from "@grpc/proto-loader"
import chalk from "chalk"
import { loadServicesFromProtoDescriptor, getFqn } from "./proto-utils.mjs"
const IMPL_FILE = path.resolve("src/generated/standalone/host-bridge-clients.ts")
const INTERFACE_FILE = path.resolve("src/generated/hosts/host-bridge-client-types.ts")
const DESCRIPTOR_SET = path.resolve("dist-standalone/proto/descriptor_set.pb")
// Contains the interface definitions for the host bridge clients.
const TYPES_FILE = path.resolve("src/generated/hosts/host-bridge-client-types.ts")
// Contains the ExternalHostBridgeClientManager for the external host bridge clients (using nice-grpc).
const EXTERNAL_CLIENT_FILE = path.resolve("src/generated/hosts/standalone/host-bridge-clients.ts")
// Contains the handler map for the external host bridge clients (using the custom service registry).
const VSCODE_CLIENT_FILE = path.resolve("src/generated/hosts/vscode/hostbridge-grpc-service-config.ts")
const typeNameToFQN = new Map()
function addTypeNameToFqn(name, fqn) {
if (typeNameToFQN.has(name)) {
throw new Error(`Proto type ${name} redefined (${fqn}).`)
}
typeNameToFQN.set(name, fqn)
}
function getFqn(name) {
if (!typeNameToFQN.has(name)) {
throw Error(`No FQN for ${name}`)
}
return typeNameToFQN.get(name)
}
/**
* Main function to generate the host bridge client
*/
async function main() {
// Load service definitions from descriptor set
const descriptorBuffer = await fs.readFile(DESCRIPTOR_SET)
const packageDefinition = protoLoader.loadFileDescriptorSetFromBuffer(descriptorBuffer)
const proto = grpc.loadPackageDefinition(packageDefinition)
export async function main() {
const { hostServices } = await loadServicesFromProtoDescriptor()
// Extract host services and proto messages from the proto definition
const hostServices = {}
for (const [name, def] of Object.entries(proto.host)) {
if (def && "service" in def) {
hostServices[name] = def
} else {
addTypeNameToFqn(name, `proto.host.${name}`)
}
}
for (const [name, def] of Object.entries(proto.cline)) {
if (def && !("service" in def)) {
addTypeNameToFqn(name, `proto.cline.${name}`)
}
}
await generateTypesFile(hostServices)
await generateExternalClientFile(hostServices)
await generateVscodeClientFile(hostServices)
// Generate interfaces file
await generateInterfacesFile(hostServices)
// // Generate implementation file
await generateImplementationFile(hostServices)
console.log(`Generated host bridge client files at:`)
console.log(`- ${INTERFACE_FILE}`)
console.log(`- ${IMPL_FILE}`)
console.log(`Generated Host Bridge client files at:`)
console.log(`- ${TYPES_FILE}`)
console.log(`- ${EXTERNAL_CLIENT_FILE}`)
console.log(`- ${VSCODE_CLIENT_FILE}`)
}
/**
* Generate the client interfaces file.
*/
async function generateInterfacesFile(hostServices) {
async function generateTypesFile(hostServices) {
const clientInterfaces = []
for (const [name, def] of Object.entries(hostServices)) {
const clientInterface = generateClientInterface(name, def)
const clientInterface = generateClientInterfaceType(name, def)
clientInterfaces.push(clientInterface)
}
const content = `// GENERATED CODE -- DO NOT EDIT!
@@ -76,14 +45,13 @@ import { StreamingCallbacks } from "@hosts/host-provider-types"
${clientInterfaces.join("\n\n")}
`
// Write output file
await fs.mkdir(path.dirname(INTERFACE_FILE), { recursive: true })
await fs.writeFile(INTERFACE_FILE, content)
await writeFileWithMkdirs(TYPES_FILE, content)
}
/**
* Generate a client interface for a service.
*/
function generateClientInterface(serviceName, serviceDefinition) {
function generateClientInterfaceType(serviceName, serviceDefinition) {
// Get the methods from the service definition
const methods = Object.entries(serviceDefinition.service)
.map(([methodName, methodDef]) => {
@@ -110,9 +78,9 @@ ${methods}
}
/**
* Generate the client implementations file.
* Generate the external client implementations file.
*/
async function generateImplementationFile(hostServices) {
async function generateExternalClientFile(hostServices) {
// Generate imports
const imports = []
// Add imports for the interfaces
@@ -121,7 +89,7 @@ async function generateImplementationFile(hostServices) {
}
const clientImplementations = []
for (const [name, def] of Object.entries(hostServices)) {
clientImplementations.push(generateClientImplementation(name, def))
clientImplementations.push(generateExternalClientSetup(name, def))
}
const content = `// GENERATED CODE -- DO NOT EDIT!
@@ -131,21 +99,20 @@ import * as niceGrpc from "@generated/nice-grpc/index"
import { StreamingCallbacks } from "@hosts/host-provider-types"
import * as proto from "@shared/proto/index"
import { Channel, createClient } from "nice-grpc"
import { BaseGrpcClient } from "@/hosts/external/grpc-types"
${imports.join("\n")}
${clientImplementations.join("\n\n")}
`
// Write output file
await fs.mkdir(path.dirname(IMPL_FILE), { recursive: true })
await fs.writeFile(IMPL_FILE, content)
await writeFileWithMkdirs(EXTERNAL_CLIENT_FILE, content)
}
/**
* Generate a client implementation class for a service
*/
function generateClientImplementation(serviceName, serviceDefinition) {
function generateExternalClientSetup(serviceName, serviceDefinition) {
// Get the methods from the service definition
const methods = Object.entries(serviceDefinition.service)
.map(([methodName, methodDef]) => {
@@ -155,38 +122,122 @@ function generateClientImplementation(serviceName, serviceDefinition) {
const isStreamingResponse = methodDef.responseStream
if (!isStreamingResponse) {
return ` ${methodName}(request: ${requestType}): Promise<${responseType}> {
return this.client.${methodName}(request)
}`
return ` ${methodName}(request: ${requestType}): Promise<${responseType}> {
return this.makeRequest((client) => client.${methodName}(request))
}`
} else {
// Generate streaming method
return ` ${methodName}(request: ${requestType}, callbacks: StreamingCallbacks<${responseType}>): () => void {
const abortController = new AbortController()
const stream: AsyncIterable<${responseType}> = this.client.${methodName}(request, {signal: abortController.signal})
asyncIteratorToCallbacks(stream, callbacks)
return () => {abortController.abort()}
}`
return ` ${methodName}(
request: ${requestType},
callbacks: StreamingCallbacks<${responseType}>,
): () => void {
const client = this.getClient()
const abortController = new AbortController()
const stream: AsyncIterable<${responseType}> = client.${methodName}(request, {
signal: abortController.signal,
})
const wrappedCallbacks: StreamingCallbacks<${responseType}> = {
...callbacks,
onError: (error: any) => {
if (error?.code === "UNAVAILABLE") {
this.destroyClient()
}
callbacks.onError?.(error)
},
}
asyncIteratorToCallbacks(stream, wrappedCallbacks)
return () => {
abortController.abort()
}
}\n`
}
})
.join("\n\n")
.join("\n")
// Generate the class
return `/**
* Type-safe client implementation for ${serviceName}.
*/
export class ${serviceName}ClientImpl implements ${serviceName}ClientInterface {
private client: niceGrpc.host.${serviceName}Client
export class ${serviceName}ClientImpl
extends BaseGrpcClient<niceGrpc.host.${serviceName}Client>
implements ${serviceName}ClientInterface {
constructor(channel: Channel) {
this.client = createClient(niceGrpc.host.${serviceName}Definition, channel)
}
protected createClient(channel: Channel): niceGrpc.host.${serviceName}Client {
return createClient(niceGrpc.host.${serviceName}Definition, channel)
}
${methods}
}`
}
// Run the main function
main().catch((error) => {
console.error(chalk.red("Error:"), error)
process.exit(1)
})
/**
* Generate the Vscode client setup file.
*/
async function generateVscodeClientFile(hostServices) {
const imports = []
const clientImplementations = []
const handlerMap = []
for (const [serviceName, serviceDefinition] of Object.entries(hostServices)) {
const name = serviceName.replace(/Service$/, "").toLowerCase()
for (const [methodName, _methodDef] of Object.entries(serviceDefinition.service)) {
imports.push(`import { ${methodName} } from "@/hosts/vscode/hostbridge/${name}/${methodName}"`)
}
imports.push("")
clientImplementations.push(generateVscodeClientImplementation(name, serviceDefinition))
handlerMap.push(` "host.${serviceName}": {
requestHandler: ${name}ServiceRegistry.handleRequest,
streamingHandler: ${name}ServiceRegistry.handleStreamingRequest,
},`)
}
const content = `// GENERATED CODE -- DO NOT EDIT!
// Generated by scripts/generate-host-bridge-client.mjs
import { createServiceRegistry } from "@hosts/vscode/hostbridge-grpc-service"
import { HostServiceHandlerConfig } from "@hosts/vscode/hostbridge-grpc-handler"
${imports.join("\n")}
${clientImplementations.join("\n\n")}
/**
* Map of host service names to their handler configurations
*/
export const hostServiceHandlers: Record<string, HostServiceHandlerConfig> = {
${handlerMap.join("\n")}
}
`
// Write output file
await writeFileWithMkdirs(VSCODE_CLIENT_FILE, content)
}
function generateVscodeClientImplementation(serviceName, serviceDefinition) {
// Get the methods from the service definition
const name = serviceName.replace(/Service$/, "").toLowerCase()
const methods = Object.entries(serviceDefinition.service)
.map(([methodName, methodDef]) => {
// Get fully qualified type names
const isStreamingResponse = methodDef.responseStream
if (!isStreamingResponse) {
return `${name}ServiceRegistry.registerMethod("${methodName}", ${methodName})`
} else {
return `${name}ServiceRegistry.registerMethod("${methodName}", ${methodName}, { isStreaming: true })`
}
})
.join("\n")
// Generate the class
return `// Setup ${name} service registry
const ${name}ServiceRegistry = createServiceRegistry("${name}")
${methods}`
}
// Only run main if this script is executed directly
if (import.meta.url === `file://${process.argv[1]}`) {
main().catch((error) => {
console.error(chalk.red("Error:"), error)
process.exit(1)
})
}
+214
View File
@@ -0,0 +1,214 @@
#!/usr/bin/env node
import { writeFileWithMkdirs } from "./file-utils.mjs"
import path from "path"
import { fileURLToPath } from "url"
import { loadServicesFromProtoDescriptor, getFqn } from "./proto-utils.mjs"
const WEBVIEW_CLIENTS_FILE = path.resolve("webview-ui/src/services/grpc-client.ts")
const VSCODE_SERVICES_FILE = path.resolve("src/generated/hosts/vscode/protobus-services.ts")
const VSCODE_SERVICE_TYPES_FILE = path.resolve("src/generated/hosts/vscode/protobus-service-types.ts")
const STANDALONE_SERVER_SETUP_FILE = path.resolve("src/generated/hosts/standalone/protobus-server-setup.ts")
const SCRIPT_NAME = path.relative(process.cwd(), fileURLToPath(import.meta.url))
export async function main() {
const { protobusServices } = await loadServicesFromProtoDescriptor()
await generateWebviewProtobusClients(protobusServices)
await generateVscodeServiceTypes(protobusServices)
await generateVscodeProtobusServers(protobusServices)
await generateStandaloneProtobusServiceSetup(protobusServices)
console.log(`Generated ProtoBus files at:`)
console.log(`- ${WEBVIEW_CLIENTS_FILE}`)
console.log(`- ${VSCODE_SERVICE_TYPES_FILE}`)
console.log(`- ${VSCODE_SERVICES_FILE}`)
console.log(`- ${STANDALONE_SERVER_SETUP_FILE}`)
}
async function generateWebviewProtobusClients(protobusServices) {
const clients = []
for (const [serviceName, def] of Object.entries(protobusServices)) {
const rpcs = []
for (const [rpcName, rpc] of Object.entries(def.service)) {
const requestType = getFqn(rpc.requestType.type.name)
const responseType = getFqn(rpc.responseType.type.name)
if (rpc.requestStream) {
throw new Error("Request streaming is not supported")
}
if (!rpc.responseStream) {
rpcs.push(` static async ${rpcName}(request: ${requestType}): Promise<${responseType}> {
return this.makeRequest("${rpcName}", request)
}`)
} else {
rpcs.push(` static ${rpcName}(request: ${requestType}, callbacks: Callbacks<${responseType}>): ()=>void {
return this.makeStreamingRequest("${rpcName}", request, callbacks)
}`)
}
}
clients.push(`export class ${serviceName}Client extends ProtoBusClient {
static override serviceName: string = "cline.${serviceName}"
${rpcs.join("\n")}
}`)
}
// Create output file
let output = `// GENERATED CODE -- DO NOT EDIT!
// Generated by ${SCRIPT_NAME}
import * as proto from "@shared/proto/index"
import { ProtoBusClient, Callbacks } from "./grpc-client-base"
${clients.join("\n")}
`
// Write output file
await writeFileWithMkdirs(WEBVIEW_CLIENTS_FILE, output)
}
/**
* Generate imports and function to add all the handlers to the server for all services defined in the proto files.
*/
async function generateVscodeServiceTypes(protobusServices) {
const servers = []
for (const [serviceName, def] of Object.entries(protobusServices)) {
const domain = getDomainName(serviceName)
servers.push(`// ${domain} Service Handler Types`)
servers.push(`export type ${serviceName}Handlers = {`)
for (const [rpcName, rpc] of Object.entries(def.service)) {
const requestType = getFqn(rpc.requestType.type.name)
const responseType = getFqn(rpc.responseType.type.name)
if (rpc.requestStream) {
throw new Error("Request streaming is not supported")
}
if (!rpc.responseStream) {
servers.push(` ${rpcName}:(controller: Controller, request: ${requestType}) => Promise<${responseType}>`)
} else {
servers.push(
` ${rpcName}:(controller: Controller, request: ${requestType}, responseStream: StreamingResponseHandler<${responseType}>, requestId?: string) => Promise<void>`,
)
}
}
servers.push(`}\n`)
}
// Create output file
let output = `// GENERATED CODE -- DO NOT EDIT!
// Generated by ${SCRIPT_NAME}
import * as proto from "@shared/proto/index"
import { Controller } from "@core/controller"
import { StreamingResponseHandler } from "@/core/controller/grpc-handler"
${servers.join("\n")}
`
// Write output file
await writeFileWithMkdirs(VSCODE_SERVICE_TYPES_FILE, output)
}
/**
* Generate imports and function to add all the handlers to the server for all services defined in the proto files.
*/
async function generateVscodeProtobusServers(protobusServices) {
const imports = []
const servers = []
const serviceMap = []
for (const [serviceName, def] of Object.entries(protobusServices)) {
const domain = getDomainName(serviceName)
const dir = getDirName(serviceName)
imports.push(`// ${domain} Service`)
servers.push(`const ${serviceName}Handlers: serviceTypes.${serviceName}Handlers = {`)
for (const [rpcName, _rpc] of Object.entries(def.service)) {
imports.push(`import { ${rpcName} } from "@core/controller/${dir}/${rpcName}"`)
servers.push(` ${rpcName}: ${rpcName},`)
}
servers.push(`} \n`)
serviceMap.push(` "cline.${serviceName}": ${serviceName}Handlers,`)
imports.push("")
}
// Create output file
let output = `// GENERATED CODE -- DO NOT EDIT!
// Generated by ${SCRIPT_NAME}
import * as serviceTypes from "src/generated/hosts/vscode/protobus-service-types"
${imports.join("\n")}
${servers.join("\n")}
export const serviceHandlers: Record<string, any> = {
${serviceMap.join("\n")}
}
`
// Write output file
await writeFileWithMkdirs(VSCODE_SERVICES_FILE, output)
}
/**
* Generate imports and function to add all the handlers to the server for all services defined in the proto files.
*/
async function generateStandaloneProtobusServiceSetup(protobusServices) {
const imports = []
const handlerSetup = []
for (const [name, def] of Object.entries(protobusServices)) {
const domain = getDomainName(name)
const dir = getDirName(name)
imports.push(`// ${domain} Service`)
handlerSetup.push(` // ${domain} Service`)
handlerSetup.push(` server.addService(cline.${name}Service, {`)
for (const [rpcName, rpc] of Object.entries(def.service)) {
imports.push(`import { ${rpcName} } from "@core/controller/${dir}/${rpcName}"`)
const requestType = "cline." + rpc.requestType.type.name
const responseType = "cline." + rpc.responseType.type.name
if (rpc.requestStream) {
throw new Error("Request streaming is not supported")
}
if (rpc.responseStream) {
handlerSetup.push(
` ${rpcName}: wrapStreamingResponse<${requestType},${responseType}>(${rpcName}, controller),`,
)
} else {
handlerSetup.push(` ${rpcName}: wrapper<${requestType},${responseType}>(${rpcName}, controller),`)
}
}
handlerSetup.push(` });`)
imports.push("")
handlerSetup.push("")
}
// Create output file
let output = `// GENERATED CODE -- DO NOT EDIT!
// Generated by ${SCRIPT_NAME}
import * as grpc from "@grpc/grpc-js"
import { cline } from "@generated/grpc-js"
import { Controller } from "@core/controller"
import { GrpcHandlerWrapper, GrpcStreamingResponseHandlerWrapper } from "@hosts/external/grpc-types"
${imports.join("\n")}
export function addProtobusServices(
server: grpc.Server,
controller: Controller,
wrapper: GrpcHandlerWrapper,
wrapStreamingResponse: GrpcStreamingResponseHandlerWrapper,
): void {
${handlerSetup.join("\n")}
}
`
// Write output file
await writeFileWithMkdirs(STANDALONE_SERVER_SETUP_FILE, output)
}
function getDomainName(serviceName) {
return serviceName.replace(/Service$/, "")
}
function getDirName(serviceName) {
const domain = getDomainName(serviceName)
return domain.charAt(0).toLowerCase() + domain.slice(1)
}
// Only run main if this script is executed directly
if (import.meta.url === `file://${process.argv[1]}`) {
main().catch((error) => {
console.error(chalk.red("Error:"), error)
process.exit(1)
})
}
-81
View File
@@ -1,81 +0,0 @@
import * as grpc from "@grpc/grpc-js"
import * as protoLoader from "@grpc/proto-loader"
import * as fs from "fs"
import * as health from "grpc-health-check"
import path, { basename, dirname } from "path"
import { fileURLToPath } from "url"
const OUT_FILE = path.resolve("src/generated/standalone/server-setup.ts")
const DESCRIPTOR_SET = path.resolve("dist-standalone/proto/descriptor_set.pb")
// Load service definitions.
const clineDef = protoLoader.loadFileDescriptorSetFromBuffer(fs.readFileSync(DESCRIPTOR_SET))
const healthDef = protoLoader.loadSync(health.protoPath)
const packageDefinition = { ...clineDef, ...healthDef }
const proto = grpc.loadPackageDefinition(packageDefinition)
/**
* Generate imports and function to add all the handlers to the server for all services defined in the proto files.
*/
function generateHandlersAndExports() {
let imports = []
let handlerSetup = []
for (const [name, def] of Object.entries(proto.cline)) {
if (!def || !("service" in def)) {
continue
}
const domain = name.replace(/Service$/, "")
const dir = domain.charAt(0).toLowerCase() + domain.slice(1)
imports.push(`// ${domain} Service`)
handlerSetup.push(` // ${domain} Service`)
handlerSetup.push(` server.addService(cline.${name}Service, {`)
for (const [rpcName, rpc] of Object.entries(def.service)) {
imports.push(`import { ${rpcName} } from "@core/controller/${dir}/${rpcName}"`)
const requestType = "cline." + rpc.requestType.type.name
if (rpc.requestStream) {
throw new Error("Request streaming is not supported")
}
if (rpc.responseStream) {
handlerSetup.push(` ${rpcName}: wrapStreamingResponse<${requestType},void>(${rpcName}, controller),`)
} else {
const responseType = "cline." + rpc.responseType.type.name
handlerSetup.push(` ${rpcName}: wrapper<${requestType},${responseType}>(${rpcName}, controller),`)
}
}
handlerSetup.push(` });`)
imports.push("")
handlerSetup.push("")
}
return {
imports: imports.join("\n"),
handlerSetup: handlerSetup.join("\n"),
}
}
const { imports, handlerSetup } = generateHandlersAndExports()
const scriptName = path.basename(fileURLToPath(import.meta.url))
// Create output file
let output = `// GENERATED CODE -- DO NOT EDIT!
// Generated by ${scriptName}
import * as grpc from "@grpc/grpc-js"
import { cline } from "@generated/grpc-js"
import { Controller } from "@core/controller"
import { GrpcHandlerWrapper, GrpcStreamingResponseHandlerWrapper } from "@/standalone/grpc-types"
${imports}
export function addProtobusServices(
server: grpc.Server,
controller: Controller,
wrapper: GrpcHandlerWrapper,
wrapStreamingResponse: GrpcStreamingResponseHandlerWrapper,
): void {
${handlerSetup}
}
`
// Write output file
fs.mkdirSync(dirname(OUT_FILE), { recursive: true })
fs.writeFileSync(OUT_FILE, output)
console.log(`Generated service handlers in ${OUT_FILE}.`)
+54
View File
@@ -0,0 +1,54 @@
#!/usr/bin/env node
import * as fs from "fs/promises"
import * as path from "path"
import * as grpc from "@grpc/grpc-js"
import * as protoLoader from "@grpc/proto-loader"
const DESCRIPTOR_SET = path.resolve("dist-standalone/proto/descriptor_set.pb")
const typeNameToFQN = new Map()
function addTypeNameToFqn(name, fqn) {
if (typeNameToFQN.has(name) && typeNameToFQN.get(name) !== fqn) {
throw new Error(`Proto type ${name} redefined (${fqn}).`)
}
typeNameToFQN.set(name, fqn)
}
// Get the fully qualified name for a proto type, e.g. getFqn('StringRequest') returns 'cline.StringRequest'
export function getFqn(name) {
if (!typeNameToFQN.has(name)) {
throw Error(`No FQN for ${name}`)
}
return typeNameToFQN.get(name)
}
export async function loadProtoDescriptorSet() {
const descriptorBuffer = await fs.readFile(DESCRIPTOR_SET)
const packageDefinition = protoLoader.loadFileDescriptorSetFromBuffer(descriptorBuffer)
return grpc.loadPackageDefinition(packageDefinition)
}
export async function loadServicesFromProtoDescriptor() {
// Load service definitions from descriptor set
const proto = await loadProtoDescriptorSet()
// Extract host services and proto messages from the proto definition
const hostServices = {}
for (const [name, def] of Object.entries(proto.host)) {
if (def && "service" in def) {
hostServices[name] = def
} else {
addTypeNameToFqn(name, `proto.host.${name}`)
}
}
const protobusServices = {}
for (const [name, def] of Object.entries(proto.cline)) {
if (def && "service" in def) {
protobusServices[name] = def
} else {
addTypeNameToFqn(name, `proto.cline.${name}`)
}
}
return { protobusServices, hostServices }
}
+21
View File
@@ -0,0 +1,21 @@
#!/usr/bin/env bash
set -eu #x
# This installs the cline-core app to the user's home directory,
# and starts the service.
CORE_DIR=~/.cline/core
INSTALL_DIR=$CORE_DIR/0.0.1
ZIP_FILE=standalone.zip
ZIP=dist-standalone/${ZIP_FILE}
# Remove old unpacked versions to force reinstall
rm -rf $CORE_DIR/* || true
mkdir -p $INSTALL_DIR
cp $ZIP $INSTALL_DIR
cd $INSTALL_DIR
unp $ZIP_FILE > /dev/null
pkill -f cline-core.js || true
NODE_PATH=./node_modules DEV_WORKSPACE_FOLDER=/tmp/ node cline-core.js
Regular → Executable
View File
+115 -62
View File
@@ -1,5 +1,5 @@
import { Anthropic } from "@anthropic-ai/sdk"
import { ApiConfiguration, ModelInfo } from "../shared/api"
import { ApiConfiguration, ModelInfo, QwenApiRegions } from "../shared/api"
import { AnthropicHandler } from "./providers/anthropic"
import { AwsBedrockHandler } from "./providers/bedrock"
import { OpenRouterHandler } from "./providers/openrouter"
@@ -28,6 +28,10 @@ import { CerebrasHandler } from "./providers/cerebras"
import { SapAiCoreHandler } from "./providers/sapaicore"
import { ClaudeCodeHandler } from "./providers/claude-code"
import { MoonshotHandler } from "./providers/moonshot"
import { GroqHandler } from "./providers/groq"
import { Mode } from "@shared/storage/types"
import { HuggingFaceHandler } from "./providers/huggingface"
import { HuaweiCloudMaaSHandler } from "./providers/huawei-cloud-maas"
export interface ApiHandler {
createMessage(systemPrompt: string, messages: Anthropic.Messages.MessageParam[]): ApiStream
@@ -39,27 +43,33 @@ export interface SingleCompletionHandler {
completePrompt(prompt: string): Promise<string>
}
function createHandlerForProvider(apiProvider: string | undefined, options: Omit<ApiConfiguration, "apiProvider">): ApiHandler {
function createHandlerForProvider(
apiProvider: string | undefined,
options: Omit<ApiConfiguration, "apiProvider">,
mode: Mode,
): ApiHandler {
switch (apiProvider) {
case "anthropic":
return new AnthropicHandler({
apiKey: options.apiKey,
anthropicBaseUrl: options.anthropicBaseUrl,
apiModelId: options.apiModelId,
thinkingBudgetTokens: options.thinkingBudgetTokens,
apiModelId: mode === "plan" ? options.planModeApiModelId : options.actModeApiModelId,
thinkingBudgetTokens:
mode === "plan" ? options.planModeThinkingBudgetTokens : options.actModeThinkingBudgetTokens,
})
case "openrouter":
return new OpenRouterHandler({
openRouterApiKey: options.openRouterApiKey,
openRouterModelId: options.openRouterModelId,
openRouterModelInfo: options.openRouterModelInfo,
openRouterModelId: mode === "plan" ? options.planModeOpenRouterModelId : options.actModeOpenRouterModelId,
openRouterModelInfo: mode === "plan" ? options.planModeOpenRouterModelInfo : options.actModeOpenRouterModelInfo,
openRouterProviderSorting: options.openRouterProviderSorting,
reasoningEffort: options.reasoningEffort,
thinkingBudgetTokens: options.thinkingBudgetTokens,
reasoningEffort: mode === "plan" ? options.planModeReasoningEffort : options.actModeReasoningEffort,
thinkingBudgetTokens:
mode === "plan" ? options.planModeThinkingBudgetTokens : options.actModeThinkingBudgetTokens,
})
case "bedrock":
return new AwsBedrockHandler({
apiModelId: options.apiModelId,
apiModelId: mode === "plan" ? options.planModeApiModelId : options.actModeApiModelId,
awsAccessKey: options.awsAccessKey,
awsSecretKey: options.awsSecretKey,
awsSessionToken: options.awsSessionToken,
@@ -71,16 +81,20 @@ function createHandlerForProvider(apiProvider: string | undefined, options: Omit
awsUseProfile: options.awsUseProfile,
awsProfile: options.awsProfile,
awsBedrockEndpoint: options.awsBedrockEndpoint,
awsBedrockCustomSelected: options.awsBedrockCustomSelected,
awsBedrockCustomModelBaseId: options.awsBedrockCustomModelBaseId,
thinkingBudgetTokens: options.thinkingBudgetTokens,
awsBedrockCustomSelected:
mode === "plan" ? options.planModeAwsBedrockCustomSelected : options.actModeAwsBedrockCustomSelected,
awsBedrockCustomModelBaseId:
mode === "plan" ? options.planModeAwsBedrockCustomModelBaseId : options.actModeAwsBedrockCustomModelBaseId,
thinkingBudgetTokens:
mode === "plan" ? options.planModeThinkingBudgetTokens : options.actModeThinkingBudgetTokens,
})
case "vertex":
return new VertexHandler({
vertexProjectId: options.vertexProjectId,
vertexRegion: options.vertexRegion,
apiModelId: options.apiModelId,
thinkingBudgetTokens: options.thinkingBudgetTokens,
apiModelId: mode === "plan" ? options.planModeApiModelId : options.actModeApiModelId,
thinkingBudgetTokens:
mode === "plan" ? options.planModeThinkingBudgetTokens : options.actModeThinkingBudgetTokens,
geminiApiKey: options.geminiApiKey,
geminiBaseUrl: options.geminiBaseUrl,
taskId: options.taskId,
@@ -91,21 +105,21 @@ function createHandlerForProvider(apiProvider: string | undefined, options: Omit
openAiBaseUrl: options.openAiBaseUrl,
azureApiVersion: options.azureApiVersion,
openAiHeaders: options.openAiHeaders,
openAiModelId: options.openAiModelId,
openAiModelInfo: options.openAiModelInfo,
reasoningEffort: options.reasoningEffort,
openAiModelId: mode === "plan" ? options.planModeOpenAiModelId : options.actModeOpenAiModelId,
openAiModelInfo: mode === "plan" ? options.planModeOpenAiModelInfo : options.actModeOpenAiModelInfo,
reasoningEffort: mode === "plan" ? options.planModeReasoningEffort : options.actModeReasoningEffort,
})
case "ollama":
return new OllamaHandler({
ollamaBaseUrl: options.ollamaBaseUrl,
ollamaModelId: options.ollamaModelId,
ollamaModelId: mode === "plan" ? options.planModeOllamaModelId : options.actModeOllamaModelId,
ollamaApiOptionsCtxNum: options.ollamaApiOptionsCtxNum,
requestTimeoutMs: options.requestTimeoutMs,
})
case "lmstudio":
return new LmStudioHandler({
lmStudioBaseUrl: options.lmStudioBaseUrl,
lmStudioModelId: options.lmStudioModelId,
lmStudioModelId: mode === "plan" ? options.planModeLmStudioModelId : options.actModeLmStudioModelId,
})
case "gemini":
return new GeminiHandler({
@@ -113,78 +127,86 @@ function createHandlerForProvider(apiProvider: string | undefined, options: Omit
vertexRegion: options.vertexRegion,
geminiApiKey: options.geminiApiKey,
geminiBaseUrl: options.geminiBaseUrl,
thinkingBudgetTokens: options.thinkingBudgetTokens,
apiModelId: options.apiModelId,
thinkingBudgetTokens:
mode === "plan" ? options.planModeThinkingBudgetTokens : options.actModeThinkingBudgetTokens,
apiModelId: mode === "plan" ? options.planModeApiModelId : options.actModeApiModelId,
taskId: options.taskId,
})
case "openai-native":
return new OpenAiNativeHandler({
openAiNativeApiKey: options.openAiNativeApiKey,
reasoningEffort: options.reasoningEffort,
apiModelId: options.apiModelId,
reasoningEffort: mode === "plan" ? options.planModeReasoningEffort : options.actModeReasoningEffort,
apiModelId: mode === "plan" ? options.planModeApiModelId : options.actModeApiModelId,
})
case "deepseek":
return new DeepSeekHandler({
deepSeekApiKey: options.deepSeekApiKey,
apiModelId: options.apiModelId,
apiModelId: mode === "plan" ? options.planModeApiModelId : options.actModeApiModelId,
})
case "requesty":
return new RequestyHandler({
requestyApiKey: options.requestyApiKey,
reasoningEffort: options.reasoningEffort,
thinkingBudgetTokens: options.thinkingBudgetTokens,
requestyModelId: options.requestyModelId,
requestyModelInfo: options.requestyModelInfo,
reasoningEffort: mode === "plan" ? options.planModeReasoningEffort : options.actModeReasoningEffort,
thinkingBudgetTokens:
mode === "plan" ? options.planModeThinkingBudgetTokens : options.actModeThinkingBudgetTokens,
requestyModelId: mode === "plan" ? options.planModeRequestyModelId : options.actModeRequestyModelId,
requestyModelInfo: mode === "plan" ? options.planModeRequestyModelInfo : options.actModeRequestyModelInfo,
})
case "fireworks":
return new FireworksHandler({
fireworksApiKey: options.fireworksApiKey,
fireworksModelId: options.fireworksModelId,
fireworksModelId: mode === "plan" ? options.planModeFireworksModelId : options.actModeFireworksModelId,
fireworksModelMaxCompletionTokens: options.fireworksModelMaxCompletionTokens,
fireworksModelMaxTokens: options.fireworksModelMaxTokens,
})
case "together":
return new TogetherHandler({
togetherApiKey: options.togetherApiKey,
togetherModelId: options.togetherModelId,
togetherModelId: mode === "plan" ? options.planModeTogetherModelId : options.actModeTogetherModelId,
})
case "qwen":
return new QwenHandler({
qwenApiKey: options.qwenApiKey,
qwenApiLine: options.qwenApiLine,
apiModelId: options.apiModelId,
thinkingBudgetTokens: options.thinkingBudgetTokens,
qwenApiLine:
options.qwenApiLine === QwenApiRegions.INTERNATIONAL ? QwenApiRegions.INTERNATIONAL : QwenApiRegions.CHINA,
apiModelId: mode === "plan" ? options.planModeApiModelId : options.actModeApiModelId,
thinkingBudgetTokens:
mode === "plan" ? options.planModeThinkingBudgetTokens : options.actModeThinkingBudgetTokens,
})
case "doubao":
return new DoubaoHandler({
doubaoApiKey: options.doubaoApiKey,
apiModelId: options.apiModelId,
apiModelId: mode === "plan" ? options.planModeApiModelId : options.actModeApiModelId,
})
case "mistral":
return new MistralHandler({
mistralApiKey: options.mistralApiKey,
apiModelId: options.apiModelId,
apiModelId: mode === "plan" ? options.planModeApiModelId : options.actModeApiModelId,
})
case "vscode-lm":
return new VsCodeLmHandler({
vsCodeLmModelSelector: options.vsCodeLmModelSelector,
vsCodeLmModelSelector:
mode === "plan" ? options.planModeVsCodeLmModelSelector : options.actModeVsCodeLmModelSelector,
})
case "cline":
return new ClineHandler({
clineAccountId: options.clineAccountId,
taskId: options.taskId,
reasoningEffort: options.reasoningEffort,
thinkingBudgetTokens: options.thinkingBudgetTokens,
reasoningEffort: mode === "plan" ? options.planModeReasoningEffort : options.actModeReasoningEffort,
thinkingBudgetTokens:
mode === "plan" ? options.planModeThinkingBudgetTokens : options.actModeThinkingBudgetTokens,
openRouterProviderSorting: options.openRouterProviderSorting,
openRouterModelId: options.openRouterModelId,
openRouterModelInfo: options.openRouterModelInfo,
openRouterModelId: mode === "plan" ? options.planModeOpenRouterModelId : options.actModeOpenRouterModelId,
openRouterModelInfo: mode === "plan" ? options.planModeOpenRouterModelInfo : options.actModeOpenRouterModelInfo,
})
case "litellm":
return new LiteLlmHandler({
liteLlmApiKey: options.liteLlmApiKey,
liteLlmBaseUrl: options.liteLlmBaseUrl,
liteLlmModelId: options.liteLlmModelId,
liteLlmModelInfo: options.liteLlmModelInfo,
thinkingBudgetTokens: options.thinkingBudgetTokens,
liteLlmModelId: mode === "plan" ? options.planModeLiteLlmModelId : options.actModeLiteLlmModelId,
liteLlmModelInfo: mode === "plan" ? options.planModeLiteLlmModelInfo : options.actModeLiteLlmModelInfo,
thinkingBudgetTokens:
mode === "plan" ? options.planModeThinkingBudgetTokens : options.actModeThinkingBudgetTokens,
liteLlmUsePromptCache: options.liteLlmUsePromptCache,
taskId: options.taskId,
})
@@ -192,34 +214,48 @@ function createHandlerForProvider(apiProvider: string | undefined, options: Omit
return new MoonshotHandler({
moonshotApiKey: options.moonshotApiKey,
moonshotApiLine: options.moonshotApiLine,
apiModelId: options.apiModelId,
apiModelId: mode === "plan" ? options.planModeApiModelId : options.actModeApiModelId,
})
case "huggingface":
return new HuggingFaceHandler({
huggingFaceApiKey: options.huggingFaceApiKey,
huggingFaceModelId: mode === "plan" ? options.planModeHuggingFaceModelId : options.actModeHuggingFaceModelId,
huggingFaceModelInfo:
mode === "plan" ? options.planModeHuggingFaceModelInfo : options.actModeHuggingFaceModelInfo,
})
case "nebius":
return new NebiusHandler({
nebiusApiKey: options.nebiusApiKey,
apiModelId: options.apiModelId,
apiModelId: mode === "plan" ? options.planModeApiModelId : options.actModeApiModelId,
})
case "asksage":
return new AskSageHandler({
asksageApiKey: options.asksageApiKey,
asksageApiUrl: options.asksageApiUrl,
apiModelId: options.apiModelId,
apiModelId: mode === "plan" ? options.planModeApiModelId : options.actModeApiModelId,
})
case "xai":
return new XAIHandler({
xaiApiKey: options.xaiApiKey,
reasoningEffort: options.reasoningEffort,
apiModelId: options.apiModelId,
reasoningEffort: mode === "plan" ? options.planModeReasoningEffort : options.actModeReasoningEffort,
apiModelId: mode === "plan" ? options.planModeApiModelId : options.actModeApiModelId,
})
case "sambanova":
return new SambanovaHandler({
sambanovaApiKey: options.sambanovaApiKey,
apiModelId: options.apiModelId,
apiModelId: mode === "plan" ? options.planModeApiModelId : options.actModeApiModelId,
})
case "cerebras":
return new CerebrasHandler({
cerebrasApiKey: options.cerebrasApiKey,
apiModelId: options.apiModelId,
apiModelId: mode === "plan" ? options.planModeApiModelId : options.actModeApiModelId,
})
case "groq":
return new GroqHandler({
groqApiKey: options.groqApiKey,
groqModelId: mode === "plan" ? options.planModeGroqModelId : options.actModeGroqModelId,
groqModelInfo: mode === "plan" ? options.planModeGroqModelInfo : options.actModeGroqModelInfo,
apiModelId: mode === "plan" ? options.planModeApiModelId : options.actModeApiModelId,
})
case "sapaicore":
return new SapAiCoreHandler({
@@ -228,37 +264,54 @@ function createHandlerForProvider(apiProvider: string | undefined, options: Omit
sapAiCoreTokenUrl: options.sapAiCoreTokenUrl,
sapAiResourceGroup: options.sapAiResourceGroup,
sapAiCoreBaseUrl: options.sapAiCoreBaseUrl,
apiModelId: options.apiModelId,
apiModelId: mode === "plan" ? options.planModeApiModelId : options.actModeApiModelId,
})
case "claude-code":
return new ClaudeCodeHandler({
claudeCodePath: options.claudeCodePath,
apiModelId: options.apiModelId,
thinkingBudgetTokens: options.thinkingBudgetTokens,
apiModelId: mode === "plan" ? options.planModeApiModelId : options.actModeApiModelId,
thinkingBudgetTokens:
mode === "plan" ? options.planModeThinkingBudgetTokens : options.actModeThinkingBudgetTokens,
})
case "huawei-cloud-maas":
return new HuaweiCloudMaaSHandler({
huaweiCloudMaasApiKey: options.huaweiCloudMaasApiKey,
huaweiCloudMaasModelId:
mode === "plan" ? options.planModeHuaweiCloudMaasModelId : options.actModeHuaweiCloudMaasModelId,
huaweiCloudMaasModelInfo:
mode === "plan" ? options.planModeHuaweiCloudMaasModelInfo : options.actModeHuaweiCloudMaasModelInfo,
})
default:
return new AnthropicHandler({
apiKey: options.apiKey,
anthropicBaseUrl: options.anthropicBaseUrl,
apiModelId: options.apiModelId,
thinkingBudgetTokens: options.thinkingBudgetTokens,
apiModelId: mode === "plan" ? options.planModeApiModelId : options.actModeApiModelId,
thinkingBudgetTokens:
mode === "plan" ? options.planModeThinkingBudgetTokens : options.actModeThinkingBudgetTokens,
})
}
}
export function buildApiHandler(configuration: ApiConfiguration): ApiHandler {
const { apiProvider, ...options } = configuration
export function buildApiHandler(configuration: ApiConfiguration, mode: Mode): ApiHandler {
const { planModeApiProvider, actModeApiProvider, ...options } = configuration
const apiProvider = mode === "plan" ? planModeApiProvider : actModeApiProvider
// Validate thinking budget tokens against model's maxTokens to prevent API errors
// wrapped in a try-catch for safety, but this should never throw
try {
if (options.thinkingBudgetTokens && options.thinkingBudgetTokens > 0) {
const handler = createHandlerForProvider(apiProvider, options)
const thinkingBudgetTokens = mode === "plan" ? options.planModeThinkingBudgetTokens : options.actModeThinkingBudgetTokens
if (thinkingBudgetTokens && thinkingBudgetTokens > 0) {
const handler = createHandlerForProvider(apiProvider, options, mode)
const modelInfo = handler.getModel().info
if (modelInfo.maxTokens && options.thinkingBudgetTokens > modelInfo.maxTokens) {
if (modelInfo.maxTokens && thinkingBudgetTokens > modelInfo.maxTokens) {
const clippedValue = modelInfo.maxTokens - 1
options.thinkingBudgetTokens = clippedValue
if (mode === "plan") {
options.planModeThinkingBudgetTokens = clippedValue
} else {
options.actModeThinkingBudgetTokens = clippedValue
}
} else {
return handler // don't rebuild unless its necessary
}
@@ -267,5 +320,5 @@ export function buildApiHandler(configuration: ApiConfiguration): ApiHandler {
console.error("buildApiHandler error:", error)
}
return createHandlerForProvider(apiProvider, options)
return createHandlerForProvider(apiProvider, options, mode)
}
+89 -88
View File
@@ -203,7 +203,7 @@ describe("AwsBedrockHandler", () => {
})
const mockOptions: ApiHandlerOptions = {
apiModelId: "anthropic.claude-3-7-sonnet-20250219-v1:0",
actModeApiModelId: "anthropic.claude-3-7-sonnet-20250219-v1:0",
awsRegion: "us-east-1",
awsAccessKey: "test-key",
awsSecretKey: "test-secret",
@@ -214,9 +214,9 @@ describe("AwsBedrockHandler", () => {
awsBedrockUsePromptCache: false,
awsUseCrossRegionInference: false,
awsBedrockEndpoint: "",
awsBedrockCustomSelected: false,
awsBedrockCustomModelBaseId: undefined,
thinkingBudgetTokens: 1600,
actModeAwsBedrockCustomSelected: false,
actModeAwsBedrockCustomModelBaseId: undefined,
actModeThinkingBudgetTokens: 1600,
}
const mockModelInfo = {
@@ -612,101 +612,102 @@ describe("AwsBedrockHandler", () => {
})
})
describe("getModelId", () => {
it("should return raw model ID for custom models", async () => {
const customOptions: ApiHandlerOptions = {
...mockOptions,
awsBedrockCustomSelected: true,
apiModelId:
"arn:aws:bedrock:us-west-2:123456789012:custom-model/anthropic.claude-3-5-sonnet-20241022-v2:0/Qk8MMyLmRd",
}
const customHandler = new AwsBedrockHandler(customOptions)
// TODO: Re-enable or remove these tests.
// describe("getModelId", () => {
// it("should return raw model ID for custom models", async () => {
// const customOptions: ApiHandlerOptions = {
// ...mockOptions,
// actModeAwsBedrockCustomSelected: true,
// actModeApiModelId:
// "arn:aws:bedrock:us-west-2:123456789012:custom-model/anthropic.claude-3-5-sonnet-20241022-v2:0/Qk8MMyLmRd",
// }
// const customHandler = new AwsBedrockHandler(customOptions)
const modelId = await customHandler.getModelId()
modelId.should.equal(
"arn:aws:bedrock:us-west-2:123456789012:custom-model/anthropic.claude-3-5-sonnet-20241022-v2:0/Qk8MMyLmRd",
)
})
// const modelId = await customHandler.getModelId()
// modelId.should.equal(
// "arn:aws:bedrock:us-west-2:123456789012:custom-model/anthropic.claude-3-5-sonnet-20241022-v2:0/Qk8MMyLmRd",
// )
// })
it("should not encode custom model IDs with slashes", async () => {
const customOptions: ApiHandlerOptions = {
...mockOptions,
awsBedrockCustomSelected: true,
apiModelId: "my-namespace/my-custom-model",
}
const customHandler = new AwsBedrockHandler(customOptions)
// it("should not encode custom model IDs with slashes", async () => {
// const customOptions: ApiHandlerOptions = {
// ...mockOptions,
// actModeAwsBedrockCustomSelected: true,
// actModeApiModelId: "my-namespace/my-custom-model",
// }
// const customHandler = new AwsBedrockHandler(customOptions)
const modelId = await customHandler.getModelId()
modelId.should.equal("my-namespace/my-custom-model")
modelId.should.not.match(/%2F/)
})
// const modelId = await customHandler.getModelId()
// modelId.should.equal("my-namespace/my-custom-model")
// modelId.should.not.match(/%2F/)
// })
it("should apply cross-region prefix for non-custom models when enabled", async () => {
const crossRegionOptions: ApiHandlerOptions = {
...mockOptions,
awsUseCrossRegionInference: true,
awsRegion: "us-west-2",
}
const crossRegionHandler = new AwsBedrockHandler(crossRegionOptions)
// it("should apply cross-region prefix for non-custom models when enabled", async () => {
// const crossRegionOptions: ApiHandlerOptions = {
// ...mockOptions,
// awsUseCrossRegionInference: true,
// awsRegion: "us-west-2",
// }
// const crossRegionHandler = new AwsBedrockHandler(crossRegionOptions)
const modelId = await crossRegionHandler.getModelId()
modelId.should.equal("us.anthropic.claude-3-7-sonnet-20250219-v1:0")
})
// const modelId = await crossRegionHandler.getModelId()
// modelId.should.equal("us.anthropic.claude-3-7-sonnet-20250219-v1:0")
// })
it("should apply EU cross-region prefix", async () => {
const euOptions: ApiHandlerOptions = {
...mockOptions,
awsUseCrossRegionInference: true,
awsRegion: "eu-central-1",
}
const euHandler = new AwsBedrockHandler(euOptions)
// it("should apply EU cross-region prefix", async () => {
// const euOptions: ApiHandlerOptions = {
// ...mockOptions,
// awsUseCrossRegionInference: true,
// awsRegion: "eu-central-1",
// }
// const euHandler = new AwsBedrockHandler(euOptions)
const modelId = await euHandler.getModelId()
modelId.should.equal("eu.anthropic.claude-3-7-sonnet-20250219-v1:0")
})
// const modelId = await euHandler.getModelId()
// modelId.should.equal("eu.anthropic.claude-3-7-sonnet-20250219-v1:0")
// })
it("should apply APAC cross-region prefix", async () => {
const apacOptions: ApiHandlerOptions = {
...mockOptions,
awsUseCrossRegionInference: true,
awsRegion: "ap-northeast-1",
}
const apacHandler = new AwsBedrockHandler(apacOptions)
// it("should apply APAC cross-region prefix", async () => {
// const apacOptions: ApiHandlerOptions = {
// ...mockOptions,
// awsUseCrossRegionInference: true,
// awsRegion: "ap-northeast-1",
// }
// const apacHandler = new AwsBedrockHandler(apacOptions)
const modelId = await apacHandler.getModelId()
modelId.should.equal("apac.anthropic.claude-3-7-sonnet-20250219-v1:0")
})
// const modelId = await apacHandler.getModelId()
// modelId.should.equal("apac.anthropic.claude-3-7-sonnet-20250219-v1:0")
// })
it("should not apply cross-region prefix for custom models even when enabled", async () => {
const customCrossRegionOptions: ApiHandlerOptions = {
...mockOptions,
awsBedrockCustomSelected: true,
apiModelId: "arn:aws:bedrock:us-west-2:123456789012:custom-model/my-model",
awsUseCrossRegionInference: true,
}
const customCrossRegionHandler = new AwsBedrockHandler(customCrossRegionOptions)
// it("should not apply cross-region prefix for custom models even when enabled", async () => {
// const customCrossRegionOptions: ApiHandlerOptions = {
// ...mockOptions,
// actModeAwsBedrockCustomSelected: true,
// actModeApiModelId: "arn:aws:bedrock:us-west-2:123456789012:custom-model/my-model",
// awsUseCrossRegionInference: true,
// }
// const customCrossRegionHandler = new AwsBedrockHandler(customCrossRegionOptions)
const modelId = await customCrossRegionHandler.getModelId()
modelId.should.equal("arn:aws:bedrock:us-west-2:123456789012:custom-model/my-model")
})
// const modelId = await customCrossRegionHandler.getModelId()
// modelId.should.equal("arn:aws:bedrock:us-west-2:123456789012:custom-model/my-model")
// })
it("should handle UltraThink model ARN correctly", async () => {
const ultraThinkOptions: ApiHandlerOptions = {
...mockOptions,
awsBedrockCustomSelected: true,
apiModelId:
"arn:aws:bedrock:us-west-2:123456789012:custom-model/anthropic.claude-3-5-sonnet-20241022-v2:0/Qk8MMyLmRd",
awsBedrockCustomModelBaseId: "anthropic.claude-3-5-sonnet-20241022-v2:0",
}
const ultraThinkHandler = new AwsBedrockHandler(ultraThinkOptions)
// it("should handle UltraThink model ARN correctly", async () => {
// const ultraThinkOptions: ApiHandlerOptions = {
// ...mockOptions,
// actModeAwsBedrockCustomSelected: true,
// actModeApiModelId:
// "arn:aws:bedrock:us-west-2:123456789012:custom-model/anthropic.claude-3-5-sonnet-20241022-v2:0/Qk8MMyLmRd",
// actModeAwsBedrockCustomModelBaseId: "anthropic.claude-3-5-sonnet-20241022-v2:0",
// }
// const ultraThinkHandler = new AwsBedrockHandler(ultraThinkOptions)
const modelId = await ultraThinkHandler.getModelId()
// Should return the raw ARN without any encoding
modelId.should.equal(
"arn:aws:bedrock:us-west-2:123456789012:custom-model/anthropic.claude-3-5-sonnet-20241022-v2:0/Qk8MMyLmRd",
)
modelId.should.not.match(/%2F/)
modelId.should.not.match(/%3A/)
})
})
// const modelId = await ultraThinkHandler.getModelId()
// // Should return the raw ARN without any encoding
// modelId.should.equal(
// "arn:aws:bedrock:us-west-2:123456789012:custom-model/anthropic.claude-3-5-sonnet-20241022-v2:0/Qk8MMyLmRd",
// )
// modelId.should.not.match(/%2F/)
// modelId.should.not.match(/%3A/)
// })
// })
})
+1 -1
View File
@@ -26,7 +26,7 @@ describe("OllamaHandler", () => {
beforeEach(() => {
options = {
ollamaModelId: "llama2",
actModeOllamaModelId: "llama2",
ollamaBaseUrl: "http://localhost:11434",
}
handler = new OllamaHandler(options)
+1 -1
View File
@@ -13,7 +13,7 @@ interface AnthropicHandlerOptions {
}
export class AnthropicHandler implements ApiHandler {
private options: ApiHandlerOptions
private options: AnthropicHandlerOptions
private client: Anthropic | undefined
constructor(options: AnthropicHandlerOptions) {
+11 -4
View File
@@ -56,7 +56,7 @@ export class CerebrasHandler implements ApiHandler {
// Check if this is a reasoning model that uses thinking tags
const modelId = this.getModel().id
const isReasoningModel = modelId.includes("qwen") || modelId.includes("deepseek-r1-distill")
const isReasoningModel = modelId.includes("qwen")
// Convert Anthropic messages to Cerebras format
for (const message of messages) {
@@ -102,6 +102,7 @@ export class CerebrasHandler implements ApiHandler {
messages: cerebrasMessages,
temperature: 0,
stream: true,
max_tokens: this.getModel().info.maxTokens,
})
// Handle streaming response
@@ -175,9 +176,15 @@ export class CerebrasHandler implements ApiHandler {
}
getModel(): { id: string; info: ModelInfo } {
const modelId = this.options.apiModelId
if (modelId && modelId in cerebrasModels) {
const id = modelId as CerebrasModelId
const originalModelId = this.options.apiModelId
let apiModelId = originalModelId
if (originalModelId === "qwen-3-coder-480b-free") {
apiModelId = "qwen-3-coder-480b"
return { id: apiModelId, info: cerebrasModels[originalModelId as CerebrasModelId] }
}
if (originalModelId && originalModelId in cerebrasModels) {
const id = originalModelId as CerebrasModelId
return { id, info: cerebrasModels[id] }
}
return {
+3 -16
View File
@@ -12,6 +12,7 @@ import OpenAI from "openai"
import { version as extensionVersion } from "../../../package.json"
import { shouldSkipReasoningForModel } from "@utils/model-utils"
import { CLINE_ACCOUNT_AUTH_ERROR_MESSAGE } from "@/shared/ClineAccount"
import { clineEnvConfig } from "@/config"
interface ClineHandlerOptions {
taskId?: string
@@ -28,10 +29,7 @@ export class ClineHandler implements ApiHandler {
private clineAccountService = ClineAccountService.getInstance()
private _authService: AuthService
private client: OpenAI | undefined
// TODO: replace this with a global API Host
private readonly _baseUrl = "https://api.cline.bot"
// private readonly _baseUrl = "https://core-api.staging.int.cline.bot"
// private readonly _baseUrl = "http://localhost:7777"
private readonly _baseUrl = clineEnvConfig.apiBaseUrl
lastGenerationId?: string
private counter = 0
@@ -179,18 +177,7 @@ export class ClineHandler implements ApiHandler {
}
} catch (error) {
console.error("Cline API Error:", error)
const requestId = error?.request_id ? ` (Request ID: ${error.request_id})` : ""
if (error.code === "ERR_BAD_REQUEST" || error.status === 401) {
throw new Error(CLINE_ACCOUNT_AUTH_ERROR_MESSAGE + requestId)
} else if (error.code === "insufficient_credits" || error.status === 402) {
if (error.error) {
error.error.message = error.error.message + requestId
throw new Error(JSON.stringify(error.error))
}
}
const _error = error instanceof Error ? error : new Error(String(error))
_error.message = _error.message + requestId
throw _error
throw error
}
}
+53
View File
@@ -0,0 +1,53 @@
// Mock for @google/genai module to avoid ESM compatibility issues in tests
export class GoogleGenAI {
constructor(options: any) {
// Mock constructor
}
models = {
generateContentStream: async (params: any) => {
// Mock implementation that returns an async iterator
return {
async *[Symbol.asyncIterator]() {
yield {
text: "Mock response",
candidates: [],
usageMetadata: {
promptTokenCount: 100,
candidatesTokenCount: 50,
thoughtsTokenCount: 0,
cachedContentTokenCount: 0,
},
}
},
}
},
countTokens: async (params: any) => {
// Mock token counting
return {
totalTokens: 100,
}
},
}
}
// Export mock types
export interface GenerateContentConfig {
httpOptions?: any
systemInstruction?: string
temperature?: number
thinkingConfig?: any
}
export interface GenerateContentResponseUsageMetadata {
promptTokenCount?: number
candidatesTokenCount?: number
thoughtsTokenCount?: number
cachedContentTokenCount?: number
}
export interface Part {
thought?: boolean
text?: string
}
+13 -18
View File
@@ -44,7 +44,7 @@ interface GeminiHandlerOptions {
* 4. Separating immediate costs from ongoing costs to avoid double-counting
*/
export class GeminiHandler implements ApiHandler {
private options: ApiHandlerOptions
private options: GeminiHandlerOptions
private client: GoogleGenAI | undefined
constructor(options: GeminiHandlerOptions) {
@@ -256,23 +256,18 @@ export class GeminiHandler implements ApiHandler {
totalDurationSdkMs > 0 && outputTokens > 0 ? outputTokens / (totalDurationSdkMs / 1000) : undefined
if (this.options.taskId) {
telemetryService.captureGeminiApiPerformance(
this.options.taskId,
modelId,
{
ttftSec: ttftSdkMs !== undefined ? ttftSdkMs / 1000 : undefined,
totalDurationSec: totalDurationSdkMs / 1000,
promptTokens,
outputTokens,
cacheReadTokens,
cacheHit,
cacheHitPercentage,
apiSuccess,
apiError,
throughputTokensPerSec: throughputTokensPerSecSdk,
},
true,
)
telemetryService.captureGeminiApiPerformance(this.options.taskId, modelId, {
ttftSec: ttftSdkMs !== undefined ? ttftSdkMs / 1000 : undefined,
totalDurationSec: totalDurationSdkMs / 1000,
promptTokens,
outputTokens,
cacheReadTokens,
cacheHit,
cacheHitPercentage,
apiSuccess,
apiError,
throughputTokensPerSec: throughputTokensPerSecSdk,
})
} else {
console.warn("GeminiHandler: taskId not available for telemetry in createMessage.")
}
+290
View File
@@ -0,0 +1,290 @@
import { Anthropic } from "@anthropic-ai/sdk"
import OpenAI from "openai"
import { withRetry } from "../retry"
import { ApiHandler } from "../"
import { GroqModelId, ModelInfo, groqDefaultModelId, groqModels } from "@shared/api"
import { calculateApiCostOpenAI } from "../../utils/cost"
import { convertToOpenAiMessages } from "../transform/openai-format"
import { ApiStream } from "../transform/stream"
interface GroqHandlerOptions {
groqApiKey?: string
groqModelId?: string
groqModelInfo?: ModelInfo
apiModelId?: string // For backward compatibility
}
// Model family definitions for enhanced behavior
interface GroqModelFamily {
name: string
supportedFeatures: {
streaming: boolean
temperature: boolean
vision: boolean
tools: boolean
}
maxTokensOverride?: number
specialParams?: Record<string, any>
}
const MODEL_FAMILIES: Record<string, GroqModelFamily> = {
// Moonshort 4 Family - Latest generation with vision support
"kimi-k2": {
name: "kimi-k2",
supportedFeatures: { streaming: true, temperature: true, vision: true, tools: true },
maxTokensOverride: 8192,
},
// Llama 4 Family - Latest generation with vision support
llama4: {
name: "Llama 4",
supportedFeatures: { streaming: true, temperature: true, vision: true, tools: true },
maxTokensOverride: 8192,
},
// Llama 3.3 Family - Balanced performance
"llama3.3": {
name: "Llama 3.3",
supportedFeatures: { streaming: true, temperature: true, vision: false, tools: true },
maxTokensOverride: 32768,
},
// Llama 3.1 Family - Fast inference
"llama3.1": {
name: "Llama 3.1",
supportedFeatures: { streaming: true, temperature: true, vision: false, tools: true },
maxTokensOverride: 131072,
},
// DeepSeek Family - Reasoning-optimized
deepseek: {
name: "DeepSeek",
supportedFeatures: { streaming: true, temperature: true, vision: false, tools: true },
maxTokensOverride: 8192,
specialParams: {
top_p: 0.95,
reasoning_format: "parsed",
},
},
// Qwen Family - Enhanced for Q&A
qwen: {
name: "Qwen",
supportedFeatures: { streaming: true, temperature: true, vision: false, tools: true },
maxTokensOverride: 32768,
},
// Compound Models - Hybrid architectures
compound: {
name: "Compound",
supportedFeatures: { streaming: true, temperature: true, vision: false, tools: true },
maxTokensOverride: 8192,
},
}
export class GroqHandler implements ApiHandler {
private options: GroqHandlerOptions
private client: OpenAI | undefined
constructor(options: GroqHandlerOptions) {
this.options = options
}
private ensureClient(): OpenAI {
if (!this.client) {
if (!this.options.groqApiKey) {
throw new Error("Groq API key is required")
}
try {
this.client = new OpenAI({
baseURL: "https://api.groq.com/openai/v1",
apiKey: this.options.groqApiKey,
})
} catch (error) {
throw new Error(`Error creating Groq client: ${error.message}`)
}
}
return this.client
}
private async *yieldUsage(info: ModelInfo, usage: OpenAI.Completions.CompletionUsage | undefined): ApiStream {
const inputTokens = usage?.prompt_tokens || 0
const outputTokens = usage?.completion_tokens || 0
const totalCost = calculateApiCostOpenAI(info, inputTokens, outputTokens)
yield {
type: "usage",
inputTokens,
outputTokens,
cacheWriteTokens: 0,
cacheReadTokens: 0,
totalCost,
}
}
/**
* Detects the model family based on the model ID
*/
private detectModelFamily(modelId: string): GroqModelFamily {
if (modelId.includes("kimi-k2")) {
return MODEL_FAMILIES["kimi-k2"]
}
// Llama 4 variants
if (modelId.includes("llama-4") || modelId.includes("llama/llama-4")) {
return MODEL_FAMILIES.llama4
}
// Llama 3.3 variants
if (modelId.includes("llama-3.3")) {
return MODEL_FAMILIES["llama3.3"]
}
// Llama 3.1 variants
if (modelId.includes("llama-3.1")) {
return MODEL_FAMILIES["llama3.1"]
}
// DeepSeek variants
if (modelId.includes("deepseek")) {
return MODEL_FAMILIES.deepseek
}
// Qwen variants
if (modelId.includes("qwen")) {
return MODEL_FAMILIES.qwen
}
// Compound variants
if (modelId.includes("compound")) {
return MODEL_FAMILIES.compound
}
// Default fallback to Llama 3.3 behavior
return MODEL_FAMILIES["kimi-k2"]
}
/**
* Gets the optimal max_tokens based on model family and capabilities
*/
private getOptimalMaxTokens(model: { id: string; info: ModelInfo }, modelFamily: GroqModelFamily): number {
// Use model-specific max tokens if available
if (model.info.maxTokens && model.info.maxTokens > 0) {
return model.info.maxTokens
}
// Use family override if available
if (modelFamily.maxTokensOverride) {
return modelFamily.maxTokensOverride
}
// Default fallback
return 8192
}
@withRetry()
async *createMessage(systemPrompt: string, messages: Anthropic.Messages.MessageParam[]): ApiStream {
const client = this.ensureClient()
const model = this.getModel()
const modelFamily = this.detectModelFamily(model.id)
// Optimize parameters based on model family
const temperature = 0
const maxTokens = this.getOptimalMaxTokens(model, modelFamily)
const openAiMessages: OpenAI.Chat.ChatCompletionMessageParam[] = [
{ role: "system", content: systemPrompt },
...convertToOpenAiMessages(messages),
]
// Build request parameters with model-specific optimizations
const requestParams: OpenAI.Chat.ChatCompletionCreateParamsStreaming & {
reasoning_format?: "parsed" | "raw" | "hidden"
top_p?: number
} = {
model: model.id,
max_tokens: maxTokens,
messages: openAiMessages,
stream: true,
stream_options: { include_usage: true },
temperature,
}
// Add any special parameters for specific model families
if (modelFamily.specialParams) {
Object.assign(requestParams, modelFamily.specialParams)
}
const stream = await client.chat.completions.create(requestParams)
for await (const chunk of stream) {
const delta = chunk.choices[0]?.delta
// Handle reasoning field if present (for reasoning models with parsed output)
if ((delta as any)?.reasoning) {
const reasoningContent = (delta as any).reasoning as string
yield {
type: "reasoning",
reasoning: reasoningContent,
}
continue
}
// Handle content field - trust the parsed output from Groq
if (delta?.content) {
yield {
type: "text",
text: delta.content,
}
}
// Handle usage information
if (chunk.usage) {
yield* this.yieldUsage(model.info, chunk.usage)
}
}
}
/**
* Checks if the current model supports vision/images
*/
supportsImages(): boolean {
const model = this.getModel()
return model.info.supportsImages === true
}
/**
* Checks if the current model supports tools
*/
supportsTools(): boolean {
const model = this.getModel()
const modelFamily = this.detectModelFamily(model.id)
return modelFamily.supportedFeatures.tools
}
/**
* Gets model information with enhanced family detection
*/
getModel(): { id: string; info: ModelInfo } {
// First priority: groqModelId and groqModelInfo (like Requesty does)
const groqModelId = this.options.groqModelId
const groqModelInfo = this.options.groqModelInfo
if (groqModelId && groqModelInfo) {
return { id: groqModelId, info: groqModelInfo }
}
// Second priority: groqModelId with static model info
if (groqModelId && groqModelId in groqModels) {
const id = groqModelId as GroqModelId
return { id, info: groqModels[id] }
}
// Third priority: apiModelId (for backward compatibility)
const apiModelId = this.options.apiModelId
if (apiModelId && apiModelId in groqModels) {
const id = apiModelId as GroqModelId
return { id, info: groqModels[id] }
}
// Default fallback
return {
id: groqDefaultModelId,
info: groqModels[groqDefaultModelId],
}
}
/**
* Gets model family information for debugging/introspection
*/
getModelFamily(): GroqModelFamily {
const model = this.getModel()
return this.detectModelFamily(model.id)
}
}
+132
View File
@@ -0,0 +1,132 @@
import { ApiHandler } from ".."
import { huaweiCloudMaasDefaultModelId, HuaweiCloudMaasModelId, huaweiCloudMaasModels, ModelInfo } from "@shared/api"
import { Anthropic } from "@anthropic-ai/sdk"
import OpenAI from "openai"
import { convertToOpenAiMessages } from "../transform/openai-format"
import { ApiStream } from "../transform/stream"
import { withRetry } from "../retry"
interface HuaweiCloudMaaSHandlerOptions {
huaweiCloudMaasApiKey?: string
huaweiCloudMaasModelId?: string
huaweiCloudMaasModelInfo?: ModelInfo
}
export class HuaweiCloudMaaSHandler implements ApiHandler {
private options: HuaweiCloudMaaSHandlerOptions
private client: OpenAI | undefined
constructor(options: HuaweiCloudMaaSHandlerOptions) {
this.options = options
}
private ensureClient(): OpenAI {
if (!this.client) {
if (!this.options.huaweiCloudMaasApiKey) {
throw new Error("Huawei Cloud MaaS API key is required")
}
try {
this.client = new OpenAI({
baseURL: "https://api.modelarts-maas.com/v1/",
apiKey: this.options.huaweiCloudMaasApiKey,
})
} catch (error) {
throw new Error(`Error creating Huawei Cloud MaaS client: ${error.message}`)
}
}
return this.client
}
getModel(): { id: HuaweiCloudMaasModelId; info: ModelInfo } {
// First priority: huaweiCloudMaasModelId and huaweiCloudMaasModelInfo (like Groq does)
const huaweiCloudMaasModelId = this.options.huaweiCloudMaasModelId
const huaweiCloudMaasModelInfo = this.options.huaweiCloudMaasModelInfo
if (huaweiCloudMaasModelId && huaweiCloudMaasModelInfo) {
return { id: huaweiCloudMaasModelId as HuaweiCloudMaasModelId, info: huaweiCloudMaasModelInfo }
}
// Second priority: huaweiCloudMaasModelId with static model info
if (huaweiCloudMaasModelId && huaweiCloudMaasModelId in huaweiCloudMaasModels) {
const id = huaweiCloudMaasModelId as HuaweiCloudMaasModelId
return { id, info: huaweiCloudMaasModels[id] }
}
// Default fallback
return {
id: huaweiCloudMaasDefaultModelId,
info: huaweiCloudMaasModels[huaweiCloudMaasDefaultModelId],
}
}
@withRetry()
async *createMessage(systemPrompt: string, messages: Anthropic.Messages.MessageParam[]): ApiStream {
const client = this.ensureClient()
const model = this.getModel()
let openAiMessages: OpenAI.Chat.ChatCompletionMessageParam[] = [
{ role: "system", content: systemPrompt },
...convertToOpenAiMessages(messages),
]
const stream = await client.chat.completions.create({
model: model.id,
max_completion_tokens: model.info.maxTokens,
messages: openAiMessages,
stream: true,
stream_options: { include_usage: true },
temperature: 0,
})
let reasoning: string | null = null
let didOutputUsage: boolean = false
let finalUsage: any = null
for await (const chunk of stream) {
const delta = chunk.choices[0]?.delta
// Handle reasoning content detection
if (delta?.content) {
if (reasoning || delta.content.includes("<think>")) {
reasoning = (reasoning || "") + delta.content
} else if (!reasoning) {
yield {
type: "text",
text: delta.content,
}
}
}
// Handle reasoning output
if (reasoning || (delta && "reasoning_content" in delta && delta.reasoning_content)) {
const reasoningContent = delta?.content || ((delta as any)?.reasoning_content as string | undefined) || ""
if (reasoningContent.trim()) {
yield {
type: "reasoning",
reasoning: reasoningContent,
}
}
// Check if reasoning is complete
if (reasoning?.includes("</think>")) {
reasoning = null
}
}
// Store usage information for later output
if (chunk.usage) {
finalUsage = chunk.usage
}
// Output usage when stream is finished
if (!didOutputUsage && chunk.choices?.[0]?.finish_reason) {
if (finalUsage) {
yield {
type: "usage",
inputTokens: finalUsage.prompt_tokens || 0,
outputTokens: finalUsage.completion_tokens || 0,
cacheWriteTokens: 0,
cacheReadTokens: 0,
}
}
didOutputUsage = true
}
}
}
}
+142
View File
@@ -0,0 +1,142 @@
import { Anthropic } from "@anthropic-ai/sdk"
import OpenAI from "openai"
import { withRetry } from "../retry"
import { ApiHandler } from "../"
import { ApiHandlerOptions, HuggingFaceModelId, ModelInfo, huggingFaceDefaultModelId, huggingFaceModels } from "@shared/api"
import { calculateApiCostOpenAI } from "../../utils/cost"
import { convertToOpenAiMessages } from "../transform/openai-format"
import { ApiStream } from "../transform/stream"
interface HuggingFaceHandlerOptions {
huggingFaceApiKey?: string
huggingFaceModelId?: string
huggingFaceModelInfo?: ModelInfo
}
export class HuggingFaceHandler implements ApiHandler {
private options: HuggingFaceHandlerOptions
private client: OpenAI | undefined
private cachedModel: { id: HuggingFaceModelId; info: ModelInfo } | undefined
constructor(options: HuggingFaceHandlerOptions) {
this.options = options
}
private ensureClient(): OpenAI {
if (!this.client) {
if (!this.options.huggingFaceApiKey) {
throw new Error("Hugging Face API key is required")
}
try {
this.client = new OpenAI({
baseURL: "https://router.huggingface.co/v1",
apiKey: this.options.huggingFaceApiKey,
defaultHeaders: {
"User-Agent": "Cline/1.0",
},
})
} catch (error: any) {
throw new Error(`Error creating Hugging Face client: ${error.message}`)
}
}
return this.client
}
private async *yieldUsage(info: ModelInfo, usage: OpenAI.Completions.CompletionUsage | undefined): ApiStream {
if (!usage) {
return
}
const inputTokens = usage.prompt_tokens || 0
const outputTokens = usage.completion_tokens || 0
const totalCost = calculateApiCostOpenAI(info, inputTokens, outputTokens)
const usageData = {
type: "usage" as const,
inputTokens: inputTokens,
outputTokens: outputTokens,
cacheWriteTokens: 0,
cacheReadTokens: 0,
totalCost: totalCost,
}
yield usageData
}
@withRetry()
async *createMessage(systemPrompt: string, messages: Anthropic.Messages.MessageParam[]): ApiStream {
try {
const client = this.ensureClient()
const model = this.getModel()
const openAiMessages: OpenAI.Chat.ChatCompletionMessageParam[] = [
{ role: "system", content: systemPrompt },
...convertToOpenAiMessages(messages),
]
const requestParams = {
model: model.id,
max_tokens: model.info.maxTokens,
messages: openAiMessages,
stream: true,
stream_options: { include_usage: true },
temperature: 0,
}
const stream = (await client.chat.completions.create(requestParams)) as any
let chunkCount = 0
let totalContent = ""
for await (const chunk of stream) {
chunkCount++
const delta = chunk.choices[0]?.delta
if (delta?.content) {
totalContent += delta.content
yield {
type: "text",
text: delta.content,
}
}
if (chunk.usage) {
yield* this.yieldUsage(model.info, chunk.usage)
}
}
} catch (error: any) {
throw error
}
}
getModel(): { id: HuggingFaceModelId; info: ModelInfo } {
// Return cached model if available
if (this.cachedModel) {
return this.cachedModel
}
const modelId = this.options.huggingFaceModelId
// List all available models for debugging
const availableModels = Object.keys(huggingFaceModels)
let result: { id: HuggingFaceModelId; info: ModelInfo }
if (modelId && modelId in huggingFaceModels) {
const id = modelId as HuggingFaceModelId
const modelInfo = huggingFaceModels[id]
result = { id, info: modelInfo }
} else {
const defaultInfo = huggingFaceModels[huggingFaceDefaultModelId]
result = {
id: huggingFaceDefaultModelId,
info: defaultInfo,
}
}
// Cache the result for future calls
this.cachedModel = result
return result
}
}
+9
View File
@@ -19,6 +19,15 @@ interface OpenRouterHandlerOptions {
thinkingBudgetTokens?: number
}
interface OpenRouterHandlerOptions {
openRouterApiKey?: string
openRouterModelId?: string
openRouterModelInfo?: ModelInfo
openRouterProviderSorting?: string
reasoningEffort?: string
thinkingBudgetTokens?: number
}
export class OpenRouterHandler implements ApiHandler {
private options: OpenRouterHandlerOptions
private client: OpenAI | undefined
+15 -7
View File
@@ -9,6 +9,7 @@ import {
internationalQwenDefaultModelId,
MainlandQwenModelId,
InternationalQwenModelId,
QwenApiRegions,
} from "@shared/api"
import { convertToOpenAiMessages } from "../transform/openai-format"
import { ApiStream } from "../transform/stream"
@@ -17,7 +18,7 @@ import { withRetry } from "../retry"
interface QwenHandlerOptions {
qwenApiKey?: string
qwenApiLine?: string
qwenApiLine?: QwenApiRegions
apiModelId?: string
thinkingBudgetTokens?: number
}
@@ -27,7 +28,15 @@ export class QwenHandler implements ApiHandler {
private client: OpenAI | undefined
constructor(options: QwenHandlerOptions) {
this.options = options
// Ensure options start with defaults but allow overrides
this.options = {
qwenApiLine: QwenApiRegions.CHINA,
...options,
}
}
private useChinaApi(): boolean {
return this.options.qwenApiLine === QwenApiRegions.CHINA
}
private ensureClient(): OpenAI {
@@ -37,10 +46,9 @@ export class QwenHandler implements ApiHandler {
}
try {
this.client = new OpenAI({
baseURL:
this.options.qwenApiLine === "china"
? "https://dashscope.aliyuncs.com/compatible-mode/v1"
: "https://dashscope-intl.aliyuncs.com/compatible-mode/v1",
baseURL: this.useChinaApi()
? "https://dashscope.aliyuncs.com/compatible-mode/v1"
: "https://dashscope-intl.aliyuncs.com/compatible-mode/v1",
apiKey: this.options.qwenApiKey,
})
} catch (error: any) {
@@ -53,7 +61,7 @@ export class QwenHandler implements ApiHandler {
getModel(): { id: MainlandQwenModelId | InternationalQwenModelId; info: ModelInfo } {
const modelId = this.options.apiModelId
// Branch based on API line to let poor typescript know what to do
if (this.options.qwenApiLine === "china") {
if (this.useChinaApi()) {
return {
id: (modelId as MainlandQwenModelId) ?? mainlandQwenDefaultModelId,
info: mainlandQwenModels[modelId as MainlandQwenModelId] ?? mainlandQwenModels[mainlandQwenDefaultModelId],
+29 -13
View File
@@ -1,13 +1,13 @@
import { Anthropic } from "@anthropic-ai/sdk"
import * as vscode from "vscode"
import { ApiHandler, SingleCompletionHandler } from "../"
import { calculateApiCostAnthropic } from "@utils/cost"
import { ApiStream } from "@api/transform/stream"
import { convertToVsCodeLmMessages } from "@api/transform/vscode-lm-format"
import { SELECTOR_SEPARATOR, stringifyVsCodeLmModelSelector } from "@shared/vsCodeSelectorUtils"
import { ModelInfo, openAiModelInfoSaneDefaults } from "@shared/api"
import type { LanguageModelChatSelector as LanguageModelChatSelectorFromTypes } from "./types"
import { SELECTOR_SEPARATOR, stringifyVsCodeLmModelSelector } from "@shared/vsCodeSelectorUtils"
import { calculateApiCostAnthropic } from "@utils/cost"
import * as vscode from "vscode"
import { ApiHandler, SingleCompletionHandler } from "../"
import { withRetry } from "../retry"
import type { LanguageModelChatSelector as LanguageModelChatSelectorFromTypes } from "./types"
interface VsCodeLmHandlerOptions {
vsCodeLmModelSelector?: any
@@ -237,7 +237,28 @@ export class VsCodeLmHandler implements ApiHandler, SingleCompletionHandler {
}
}
private extractTextFromMessage(message: vscode.LanguageModelChatMessage): string {
if (Array.isArray(message.content)) {
return message.content
.filter((part) => part instanceof vscode.LanguageModelTextPart)
.map((part) => (part as vscode.LanguageModelTextPart).value)
.join("")
}
return ""
}
private isClaudeModel(): boolean {
return this.client?.family?.startsWith("claude") || false
}
private async countTokens(text: string | vscode.LanguageModelChatMessage): Promise<number> {
// For Claude models, use character-to-token ratio instead of VSCode LM's inaccurate counting
if (this.isClaudeModel()) {
const textContent = typeof text === "string" ? text : this.extractTextFromMessage(text)
// Use 4 character-to-token ratio for Claude models
return Math.ceil(textContent.length / 4)
}
// Check for required dependencies
if (!this.client) {
console.warn("Cline <Language Model API>: No client available for token counting")
@@ -304,15 +325,10 @@ export class VsCodeLmHandler implements ApiHandler, SingleCompletionHandler {
}
}
private async calculateTotalInputTokens(
systemPrompt: string,
vsCodeLmMessages: vscode.LanguageModelChatMessage[],
): Promise<number> {
const systemTokens: number = await this.countTokens(systemPrompt)
private async calculateTotalInputTokens(vsCodeLmMessages: vscode.LanguageModelChatMessage[]): Promise<number> {
const messageTokens: number[] = await Promise.all(vsCodeLmMessages.map((msg) => this.countTokens(msg)))
return systemTokens + messageTokens.reduce((sum: number, tokens: number): number => sum + tokens, 0)
return messageTokens.reduce((sum: number, tokens: number): number => sum + tokens, 0)
}
private ensureCleanState(): void {
@@ -434,7 +450,7 @@ export class VsCodeLmHandler implements ApiHandler, SingleCompletionHandler {
this.currentRequestCancellation = new vscode.CancellationTokenSource()
// Calculate input tokens before starting the stream
const totalInputTokens: number = await this.calculateTotalInputTokens(systemPrompt, vsCodeLmMessages)
const totalInputTokens: number = await this.calculateTotalInputTokens(vsCodeLmMessages)
// Accumulate the text and count at the end of the stream to reduce token counting overhead.
let accumulatedText: string = ""
+6
View File
@@ -14,6 +14,12 @@ interface XAIHandlerOptions {
apiModelId?: string
}
interface XAIHandlerOptions {
xaiApiKey?: string
reasoningEffort?: string
apiModelId?: string
}
export class XAIHandler implements ApiHandler {
private options: XAIHandlerOptions
private client: OpenAI | undefined
+4 -2
View File
@@ -140,7 +140,7 @@ export async function createOpenRouterStream(
}
// hardcoded provider sorting for kimi-k2
const isKimiK2 = model.id.startsWith("moonshotai/kimi-k2")
const isKimiK2 = model.id === "moonshotai/kimi-k2"
openRouterProviderSorting = isKimiK2 ? undefined : openRouterProviderSorting
// @ts-ignore-next-line
@@ -158,7 +158,9 @@ export async function createOpenRouterStream(
...(reasoning ? { reasoning } : {}),
...(openRouterProviderSorting ? { provider: { sort: openRouterProviderSorting } } : {}),
// limit providers to only those that support the 131k context window
...(isKimiK2 ? { provider: { order: ["groq", "together"], allow_fallbacks: false } } : {}),
...(isKimiK2
? { provider: { order: ["groq", "together", "baseten", "parasail", "novita", "deepinfra"], allow_fallbacks: false } }
: {}),
})
return stream
+80
View File
@@ -0,0 +1,80 @@
export enum Environment {
production = "production",
staging = "staging",
local = "local",
}
interface EnvironmentConfig {
appBaseUrl: string
apiBaseUrl: string
mcpBaseUrl: string
firebase: {
apiKey: string
authDomain: string
projectId: string
storageBucket?: string
messagingSenderId?: string
appId?: string
}
}
function getClineEnv(): Environment {
const _env = process?.env?.CLINE_ENVIRONMENT
if (_env && Object.values(Environment).includes(_env as Environment)) {
return _env as Environment
}
return Environment.production
}
// Config getter function to avoid storing all configs in memory
function getEnvironmentConfig(env: Environment): EnvironmentConfig {
switch (env) {
case Environment.staging:
return {
appBaseUrl: "https://staging-app.cline.bot",
apiBaseUrl: "https://core-api.staging.int.cline.bot",
mcpBaseUrl: "https://api.cline.bot/v1/mcp",
firebase: {
apiKey: "AIzaSyASSwkwX1kSO8vddjZkE5N19QU9cVQ0CIk",
authDomain: "cline-staging.firebaseapp.com",
projectId: "cline-staging",
storageBucket: "cline-staging.firebasestorage.app",
messagingSenderId: "853479478430",
appId: "1:853479478430:web:2de0dba1c63c3262d4578f",
},
}
case Environment.local:
return {
appBaseUrl: "http://localhost:3000",
apiBaseUrl: "http://localhost:7777",
mcpBaseUrl: "https://api.cline.bot/v1/mcp",
firebase: {
apiKey: "AIzaSyD8wtkd1I-EICuAg6xgAQpRdwYTvwxZG2w",
authDomain: "cline-preview.firebaseapp.com",
projectId: "cline-preview",
},
}
default:
return {
appBaseUrl: "https://app.cline.bot",
apiBaseUrl: "https://api.cline.bot",
mcpBaseUrl: "https://api.cline.bot/v1/mcp",
firebase: {
apiKey: "AIzaSyC5rx59Xt8UgwdU3PCfzUF7vCwmp9-K2vk",
authDomain: "cline-prod.firebaseapp.com",
projectId: "cline-prod",
storageBucket: "cline-prod.firebasestorage.app",
messagingSenderId: "941048379330",
appId: "1:941048379330:web:45058eedeefc5cdfcc485b",
},
}
}
}
// Get environment once at module load
const CLINE_ENVIRONMENT = getClineEnv()
const _configCache = getEnvironmentConfig(CLINE_ENVIRONMENT)
console.info("Cline environment:", CLINE_ENVIRONMENT)
export const clineEnvConfig = _configCache
@@ -6,8 +6,8 @@ import * as path from "path"
import { FileContextTracker } from "./FileContextTracker"
import * as diskModule from "@core/storage/disk"
import type { TaskMetadata, FileMetadataEntry } from "./ContextTrackerTypes"
import type { DiffViewProviderCreator, WebviewProviderCreator } from "@/hosts/host-providers"
import * as hostProviders from "@hosts/host-providers"
import type { DiffViewProviderCreator, WebviewProviderCreator } from "@/hosts/host-provider"
import { HostProvider } from "@/hosts/host-provider"
import { vscodeHostBridgeClient } from "@/hosts/vscode/hostbridge/client/host-grpc-client"
describe("FileContextTracker", () => {
@@ -53,10 +53,14 @@ describe("FileContextTracker", () => {
mockTaskMetadata = { files_in_context: [], model_usage: [] }
getTaskMetadataStub = sandbox.stub(diskModule, "getTaskMetadata").resolves(mockTaskMetadata)
saveTaskMetadataStub = sandbox.stub(diskModule, "saveTaskMetadata").resolves()
hostProviders.initializeHostProviders(
// Reset HostProvider before initializing to avoid "already initialized" errors
HostProvider.reset()
HostProvider.initialize(
((_) => {}) as WebviewProviderCreator,
(() => {}) as DiffViewProviderCreator,
vscodeHostBridgeClient,
(_) => {},
)
// Create tracker instance
@@ -66,6 +70,8 @@ describe("FileContextTracker", () => {
afterEach(() => {
sandbox.restore()
// Reset HostProvider after each test to ensure clean state
HostProvider.reset()
})
it("should add a record when a file is read by a tool", async () => {
@@ -5,7 +5,7 @@ import { getWorkspaceState, updateWorkspaceState } from "@core/storage/state"
import { getGlobalState } from "@core/storage/state"
import type { FileMetadataEntry } from "./ContextTrackerTypes"
import type { ClineMessage } from "@shared/ExtensionMessage"
import { getHostBridgeProvider } from "@/hosts/host-providers"
import { HostProvider } from "@/hosts/host-provider"
import { getCwd } from "@/utils/path"
// This class is responsible for tracking file operations that may result in stale context.
@@ -240,7 +240,7 @@ export async function deleteRuleFile(
}
// Delete the file from disk
await fs.unlink(rulePath)
await fs.rm(rulePath, { force: true })
// Get the filename for messages
const fileName = path.basename(rulePath)
@@ -1,7 +1,6 @@
import { Controller } from "../index"
import { AuthService } from "@/services/auth/AuthService"
import { EmptyRequest, String } from "../../../shared/proto/common"
import { openExternal } from "@utils/env"
import { EmptyRequest, String } from "@shared/proto/cline/common"
const authService = AuthService.getInstance()
@@ -13,6 +12,6 @@ const authService = AuthService.getInstance()
* @param controller The controller instance.
* @returns The login URL as a string.
*/
export async function accountLoginClicked(controller: Controller, _: EmptyRequest): Promise<String> {
export async function accountLoginClicked(_controller: Controller, _: EmptyRequest): Promise<String> {
return await authService.createAuthRequest()
}
@@ -1,6 +1,6 @@
import { AuthService } from "@/services/auth/AuthService"
import { Empty } from "../../../shared/proto/common"
import type { EmptyRequest } from "../../../shared/proto/common"
import { Empty } from "@shared/proto/cline/common"
import type { EmptyRequest } from "@shared/proto/cline/common"
import type { Controller } from "../index"
const authService = AuthService.getInstance()
@@ -1,4 +1,4 @@
import { AuthStateChangedRequest, AuthState } from "@shared/proto/account"
import { AuthStateChangedRequest, AuthState } from "@shared/proto/cline/account"
import type { Controller } from "../index"
import { updateGlobalState } from "../../storage/state"
@@ -1,5 +1,5 @@
import type { Controller } from "../index"
import { GetOrganizationCreditsRequest, OrganizationCreditsData, OrganizationUsageTransaction } from "@shared/proto/account"
import { GetOrganizationCreditsRequest, OrganizationCreditsData, OrganizationUsageTransaction } from "@shared/proto/cline/account"
/**
* Handles fetching all organization credits data (balance, usage, payments)
@@ -22,6 +22,11 @@ export async function getOrganizationCredits(
controller.accountService.fetchOrganizationUsageTransactionsRPC(request.organizationId),
])
// If balance call fails (returns undefined), throw an error
if (!balanceData) {
throw new Error("Failed to fetch organization credits data")
}
return OrganizationCreditsData.create({
balance: balanceData ? { currentBalance: balanceData.balance / 100 } : { currentBalance: 0 },
organizationId: balanceData?.organizationId || "",
@@ -1,6 +1,6 @@
import type { Controller } from "../index"
import type { EmptyRequest } from "@shared/proto/common"
import { UserCreditsData } from "@shared/proto/account"
import type { EmptyRequest } from "@shared/proto/cline/common"
import { UserCreditsData } from "@shared/proto/cline/account"
/**
* Handles fetching all user credits data (balance, usage, payments)
@@ -21,6 +21,11 @@ export async function getUserCredits(controller: Controller, request: EmptyReque
controller.accountService.fetchPaymentTransactionsRPC(),
])
// If either call fails (returns undefined), throw an error
if (balance === undefined) {
throw new Error("Failed to fetch user credits data")
}
return UserCreditsData.create({
balance: balance ? { currentBalance: balance.balance / 100 } : { currentBalance: 0 },
usageTransactions: usageTransactions,
@@ -1,6 +1,6 @@
import type { Controller } from "../index"
import type { EmptyRequest } from "@shared/proto/common"
import { UserOrganization, UserOrganizationsResponse } from "@shared/proto/account"
import type { EmptyRequest } from "@shared/proto/cline/common"
import { UserOrganization, UserOrganizationsResponse } from "@shared/proto/cline/account"
/**
* Handles fetching all user credits data (balance, usage, payments)
@@ -1,6 +1,6 @@
import type { Controller } from "../index"
import { Empty } from "@shared/proto/common"
import { UserOrganizationUpdateRequest } from "@shared/proto/account"
import { Empty } from "@shared/proto/cline/common"
import { UserOrganizationUpdateRequest } from "@shared/proto/cline/account"
/**
* Handles setting the user's active organization

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