Compare commits

...

88 Commits

Author SHA1 Message Date
Elephant Lumps 964ba104db merge conflicts 2025-05-05 10:16:25 -05:00
Toshii 274349f944 add ui component for external rules files (#3291)
* base

* svg

* delete refresh

* changeset
2025-05-05 09:49:35 -05:00
Frostbourne 6d24e22bf6 Make previous updates a dropdown (#3265)
* Add Dropdown for previous updates

* changeset
2025-05-04 17:25:16 -07:00
Frostbourne 8fae4e64d5 Allow for multiple dev server instances (#3288)
* Allow multiple dev servers at once

* logs

* fix portFilePath

* improve log

* default port fallback

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

---------

Co-authored-by: ellipsis-dev[bot] <65095814+ellipsis-dev[bot]@users.noreply.github.com>
2025-05-04 17:24:37 -07:00
Toshii fc5adcf8eb add open ai cache pricing & check to ui (#3268)
* base

* changeset

* Update src/core/controller/index.ts

Co-authored-by: Ara <arafat.da.khan@gmail.com>

---------

Co-authored-by: Ara <arafat.da.khan@gmail.com>
2025-05-04 12:16:46 -07:00
Toshii 9eaf023bac Update gemini caching for open router and cline provider (#3260)
* gemini caching

* changeset
2025-05-02 23:37:59 -07:00
github-actions[bot] cf9ce1d103 v3.14.0 Release Notes
v3.14.0 Release Notes
2025-05-02 20:53:15 -07:00
Ding Fei 675b5e1bed feat: support batch history deletion (#2918)
* feat: support batch history deletion

Single history item deletion is too small and "Delete All History" is
too large on granuality.

For long term Cline users and Cline devs/testers it would be convenient
to batch deletion these history items.

On `HistoryView` page, this commit add:

1. `CheckBox` for every history item
2. `Select All` & `Deselect All` buttons (work with search filter)
3. `Delete Selected` button for batch deletion (only appears when
   item(s) is/are selected)

History task's `onclick` is pointed to `showTaskWithId` for quick
showing this task.

* fix failed ellipsis checking

* HistoryView: remove unused import

* fix: style improvement

1. Selection buttons moved up to align with 'Done' button
2. Delete All History button hidden when any items are selected
3. Checkboxes moved below and align with message text

* restore unnecessary changes

* Improve styles and Delete selected button

* changeset

---------

Co-authored-by: frostbournesb <frostbournesb@protonmail.com>
2025-05-02 16:01:15 -07:00
Evan 2fe24055c0 Migrate tools section new docs (#3255)
* migrate cline tools section

* changeset

---------

Co-authored-by: Elephant Lumps <celestial_vault@mac.mynetworksettings.com>
2025-05-02 15:42:14 -07:00
Toshii e4d26bef97 enable cursorrules and windsurfrules (#3245)
* base

* task call

* base 2

* changeset

* wrap recursive dir
2025-05-02 13:45:08 -07:00
Elephant Lumps a8d00cbc40 changeset 2025-05-02 12:54:57 -05:00
Elephant Lumps 237de4e52d migrate getting-started to new docs 2025-05-02 12:54:27 -05:00
Evan 1c7d33a495 Add remote config webview. (#3243)
* added posthog remote config

* changeset

* add feature flags constant

* move init outside function to keep from potentially re-running

---------

Co-authored-by: Elephant Lumps <celestial_vault@mac.mynetworksettings.com>
2025-05-02 10:36:22 -05:00
Frostbourne eb6e4818d3 feat: LaTeX formatting (#3242)
* initial

* initial

* restored package-lock.json

* restored comment

* One line

* prettier

* do not throw on error

* escape backslashes in system notification

* better prompt

* reduce prompt size

* prettier

---------

Co-authored-by: canvrno <kevin@cline.bot>
2025-05-02 19:46:59 +05:30
pashpashpash 61d2f42955 gemini prompt caching (#3181)
* wip

* updated api tiered pricing schema for vertex and gemini to support tiered cache prices

* vertex too

* changeset

* pushing claude implementation

* addressing aras comments

* cleaning up caches

* linter complaining

* enabling total price for gemini provider

* Fixing Gemini Caching mechanism

* Update src/api/providers/vertex.ts

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

---------

Co-authored-by: Cline Evaluation <cline@example.com>
Co-authored-by: arafatkatze <arafat.da.khan@gmail.com>
Co-authored-by: ellipsis-dev[bot] <65095814+ellipsis-dev[bot]@users.noreply.github.com>
2025-05-02 00:50:48 -07:00
pashpashpash c78fe237e2 Terminal race condition addressed with awaits (#3240)
* terminal race condition addressed with awaits

* changeset

* added logger line

---------

Co-authored-by: Cline Evaluation <cline@example.com>
2025-05-02 07:03:06 +05:30
pashpashpash 0ffb7dd56b changeset (#3241)
Co-authored-by: Cline Evaluation <cline@example.com>
2025-05-02 07:02:22 +05:30
canvrno e9ce38472f [PROTOBUS] Move commitSearch to protobus (#3229)
* commitSearch protobus migration

* rename

* one small change to comments

* moved GitCommmit proto mapping to proto-conversions
2025-05-01 18:18:39 -07:00
canvrno 5802b6847e [PROTOBUS] Move createRuleFile to protobus 🚌💨 (#3122)
* createRuleFile protobus migration

* deleteRuleFile protobus

* mend

* mend

* mend

* Generic response for delete request

* refactored deleteRuleFile for consolidation

* rename ruleFileResult to ruleFile

* rebase and cleanup

* createRuleFile protobus migration

* ellipsis changes

* consolidated ruleFile protos

* prep for merge on to 3124

* removed ruleFileOperations
2025-05-01 17:25:29 -07:00
Dennis Bartlett 4a768702aa Fix Changeset (#3239) 2025-05-01 16:50:15 -07:00
canvrno 4565e067af [PROTOBUS] file checkIsImageUrl (#3109)
* checkIsImageURL protobus migration

* changeset

* rebase and move to web-content

* cleanup

* metadata

* rename return message

* removed old import, metadata
2025-05-01 16:11:58 -07:00
canvrno 4650ffa86b [PROTOBUS] Move deleteRuleFile to protobus 🚌💨 (#3124)
* createRuleFile protobus migration

* deleteRuleFile protobus

* mend

* mend

* mend

* ellipsis changes

* Generic response for delete request

* refactored deleteRuleFile for consolidation

* rename ruleFileResult to ruleFile
2025-05-01 16:06:54 -07:00
Evan f6d50ead3f Setup docs (#3230)
* rename old docs folder

* set up mintlify docs base

* add back script

---------

Co-authored-by: Elephant Lumps <celestial_vault@mac.mynetworksettings.com>
2025-05-01 16:04:07 -07:00
David Nanyan 70cc437d71 [ISSUE-3145] Fix Windows path issue: Correct handling of import.meta.url to avoid leading slash in pathname (#3237)
* [ISSUE-3145] Fix Windows path issue: Correct handling of import.meta.url to avoid leading slash in pathname

* Add changeset file
2025-05-01 14:42:35 -07:00
watany bdfda6f908 feat(bedrock): Introduce Amazon Nova Premier (#3225)
* feat(bedrock): Introduce Amazon Nova Premier

* changeset
2025-05-01 14:39:32 -07:00
David Nanyan c5de50fdd2 [3093] Fix Handle @withRetry() SyntaxError when running extension locally issue (#3190) 2025-05-02 02:14:13 +05:30
Toshii 77c9863b50 Create .clinerules directory when adding new cline rule in ui and .clinerules is currently a file (#3217)
* create clinerules dir

* change default

* changeset

* md
2025-05-01 10:27:37 -07:00
nomaven 03d44105cc Adding copy button to code blocks (#3011)
* feat: add copy button to code blocks

* Adding ability to copy Code blocks

* feat: add OpenRouter base URL and balance display component

---------

Co-authored-by: ShlomoCode <78599753+ShlomoCode@users.noreply.github.com>
2025-05-01 00:51:28 -07:00
clicube 79b76fd783 feat: Support AWS Bedrock Application Inference Profiles for Cost Tracking (#2078)
* feat: Add support for custom model ID in AWS Bedrock provider

* preserve settings when switching Act-Plan modes

* Use base model ID for ApiHandler behavior determination when using a custom model on AWS Bedrock.
2025-05-01 12:17:28 +05:30
Evan 19cc8bc9f8 Add terminal connection timeout (#3218)
* add terminal connection timeout

* changeset

---------

Co-authored-by: Elephant Lumps <celestial_vault@Elephants-MacBook-Pro.local>
2025-04-30 22:40:58 -05:00
Dennis Bartlett 08c04a3c67 Disable Codespell (#3224) 2025-04-30 19:21:09 -07:00
canvrno 41ae7326c0 Fix: Git mentions w/ no commits in workspace repo (#3179)
* fix for git mentions with no commits in repo
2025-04-30 19:15:35 -07:00
Trevor Hudson b0961f4538 Trevhud/remove linear (#3174)
* remove linear pull request action

* changeset
2025-04-30 18:51:16 -07:00
Tomás Barreiro 26242f6378 Fix tests: compile esmodules to cjs and bundle them (#3030)
* Run pretest in CI to build all tests

* Alias paths when running tests

* Bundle ES modules with esbuild

* alias packages
2025-04-30 17:51:32 -07:00
Tomás Barreiro 13228ed46f Fail the test workflow on test failures (#3197)
* Run pretest in CI to build all tests

* Alias paths when running tests

* Bundle ES modules with esbuild

* alias packages

* Preserve the test scripts exit code and display the output

* Remove outdated test
2025-04-30 17:51:03 -07:00
Tomás Barreiro d162a4b420 Alias paths on integration tests (#3196)
* Run pretest in CI to build all tests

* Alias paths when running tests
2025-04-30 17:49:40 -07:00
dependabot[bot] 1704684af8 Bump vite from 6.2.6 to 6.3.4 in /webview-ui in the npm_and_yarn group (#3214)
Bumps the npm_and_yarn group in /webview-ui with 1 update: [vite](https://github.com/vitejs/vite/tree/HEAD/packages/vite).


Updates `vite` from 6.2.6 to 6.3.4
- [Release notes](https://github.com/vitejs/vite/releases)
- [Changelog](https://github.com/vitejs/vite/blob/main/packages/vite/CHANGELOG.md)
- [Commits](https://github.com/vitejs/vite/commits/v6.3.4/packages/vite)

---
updated-dependencies:
- dependency-name: vite
  dependency-version: 6.3.4
  dependency-type: direct:development
  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-04-30 17:25:43 -07:00
pashpashpash c63d9a13a5 Fix text to say "drop" instead of "drag" (#3221)
* drag -> drop

* text fix

---------

Co-authored-by: Cline Evaluation <cline@example.com>
2025-04-30 17:18:48 -07:00
Frostbourne 65243adb24 [ENG-514] Introduce UI library (#3222)
* update tailwind

* install heroui

* Introduce HeroUIProvider and reorganize providers

* changeset

* use tailwind config

* use custom theme

* changeset

* Delete .changeset/large-boxes-behave.md
2025-04-30 17:18:18 -07:00
Tomás Barreiro e35f7b4e21 Run pretest in CI to build all tests (#2930) 2025-04-30 17:17:29 -07:00
Frostbourne 82449dabd6 Revert "actually stop tasks (#3061)" (#3220)
This reverts commit 29458d7675.
2025-04-30 15:53:36 -07:00
nomaven 74ec823017 Enhances visual feedback during drag-and-drop with dashed outline and transition effects. (#3184)
* Add drag-and-drop functionality to ChatTextArea component

- Introduced state management for drag feedback with `isDraggingOver`.
- Implemented drag event handlers: `handleDragEnter`, `handleDragLeave`, and updated `onDragOver`.
- Enhanced visual feedback during drag-and-drop with dashed outline and transition effects.
- Reset drag state on drop event.

* New Ast salvage

* shift to drag

* shift to drag

* shift to drag

* shift to drag

* shift to drag

* shift to drag

* quote

* quote

* 500ms -> 100ms

* updated language and 250ms delay sweetspot

* better transitions

---------

Co-authored-by: Cline Evaluation <cline@example.com>
2025-04-30 14:50:43 -07:00
Toshii 91e222fe37 Add checkpoints between all messages (#3213)
* checkpoints after messages

* changeset
2025-04-30 13:45:12 -07:00
Toshii 14230e7221 newrule (#3180)
* base

* words

* changeset
2025-04-29 15:40:51 -07:00
David Nanyan 4b697d8695 PROTOBUS: addRemoteServer message (#3147)
* PROTOBUS addRemoteServer

* Remove redundant types

* Properly handle any error when adding remote mcp server

* Refactor after code review

* remove redundant import
2025-04-29 11:33:43 -07:00
nomaven deeda6e273 Lowering the Gemini Caching TTL time to 15 minutes (#3116)
* Lowering the Gemini Cahcing TTL time to 15 minutes

* Lowering the Gemini Cahcing TTL time to 15 minutes
2025-04-29 23:55:35 +05:30
Trevor Hudson 7e7844529f add to launch json (#3173) 2025-04-29 11:09:41 -07:00
Toshii 4196c14c9c add openrouter / cline provider caching metrics to ui (#3176)
* cache reads

* changeset
2025-04-28 23:26:28 -07:00
Evan 5294e78dde Remove showMcpView message (#3171)
* refactor to not pass message for showMcpView

* changeset
2025-04-28 21:27:11 -07:00
pashpashpash d97424fcab Expanding task header by default (#3170)
* task expanded

* changeset

---------

Co-authored-by: Cline Evaluation <cline@example.com>
2025-04-28 21:26:12 -07:00
Dennis Bartlett 2b3c0bb633 Add warn setting to codespell workflow (#3175) 2025-04-28 18:46:47 -07:00
Tomás Barreiro b8e2fd669d fix unit test set-up and CI workflow (#3154)
* Fix unit test set-up

* run tests on CI

* update failing tests

* Update node

Update the coverage job node version
2025-04-28 16:30:40 -07:00
Evan df7f9fcba4 It depends... (#3126)
* add protos to more dependsOn, also make it so that the scripts are always displayed and the window does not automatically close

* changeset

* add back build script
2025-04-27 21:47:49 -07:00
nomaven db0b022b6e ENG-318 feat: Show openrouter balance next to provider (#3003)
* feat: add OpenRouter base URL and balance display component

* feat: add OpenRouter base URL and balance display component
2025-04-27 16:27:28 -07:00
Wesley Smith 459adf0450 Markdown copy (#3060)
* add markdown copy

* add changeset

* fmt

---------

Co-authored-by: Wesley Smith <wes@neofactory.ai>
2025-04-27 15:24:08 -07:00
WingsDrafterwork df37f29746 Support for custom timeout (#3029)
* Support for custom timeout

* Make custom timeout visible only for ollama

* Remove parameters from other providers, only kept for ollama

* Update webview-ui/src/components/settings/ApiOptions.tsx

Co-authored-by: nomaven <arafat.da.khan@gmail.com>

---------

Co-authored-by: nomaven <arafat.da.khan@gmail.com>
2025-04-27 15:17:04 -07:00
Sarah Fortune 60c210b017 Add java options to protobufs (#3141)
Set the java class path.
2025-04-27 09:25:37 -10:00
Tomás Barreiro d4bd755e60 Set the default output cost (#3079) 2025-04-26 23:03:04 -07:00
Toshii aed152b530 narrative narrative narrative (#3121)
* notice

* changeset
2025-04-25 19:42:24 -07:00
canvrno 5a8e9d8fa8 [PROTOBUS] file openImage (#3106)
* openFile protobus

* openImage protobus

* Delete .changeset/nine-numbers-boil.md
2025-04-25 19:21:07 -07:00
Sarah Fortune 7610cecde6 [PROTOBUS] Move accountLoginClicked to protobus (#3115)
* Move accountLoginClick to protobus

* Remove ununsed import

* Add account service to handleRequest in grpc handler.

* Add documentation

* github pr un-stick empty commit

---------

Co-authored-by: Andrei Edell <andrei@nugbase.com>
2025-04-25 12:45:28 -10:00
github-actions[bot] bb26b3b64d v3.13.3 Release Notes
v3.13.3 Release Notes
2025-04-25 13:43:23 -07:00
Dennis Bartlett aabdeba0f3 Feat/change reset state colors (#3112)
* Update Reset Button color to Red

* Add Changeset
2025-04-24 23:38:32 -07:00
Dennis Bartlett fd68a81a26 Alias smol to compact (#3111) 2025-04-24 22:02:36 -07:00
Toshii 0e07b92be2 Caching (#3110)
* add

* changeset

* Fix spelling error

---------

Co-authored-by: Dennis Bartlett <bartlett.dc.1@gmail.com>
2025-04-24 21:38:07 -07:00
Andrei Eternal 4addffe94c [PROTOBUS] browser getDetectedChromePath (#3001)
* protobus impl for getDetectedChromePath

* [PROTOBUS] browserSettings (#3007)

* protobus for browserSettings

* Update index.ts

---------

Co-authored-by: Andrei Edell <andrei@nugbase.com>

---------

Co-authored-by: Andrei Edell <andrei@nugbase.com>
2025-04-24 21:36:55 -07:00
Evan 0836e4d45a add npm protos to tests.json for dev build (#3107) 2025-04-24 17:07:31 -07:00
0x23d11 4a57e5a075 fix(settings): rename AWS Bedrock to Amazon Bedrock (#3094) 2025-04-24 16:17:05 -07:00
Wesley Smith 29458d7675 actually stop tasks (#3061)
Co-authored-by: Wesley Smith <wes@neofactory.ai>
2025-04-24 13:00:32 -10:00
pashpashpash 90b0d6a73b evals formatting (#3105)
Co-authored-by: Cline Evaluation <cline@example.com>
2025-04-24 15:26:12 -07:00
pashpashpash 547051bfa8 enabling download count on marketplace (#3104)
* enabling download count on marketplace

* changeset

---------

Co-authored-by: Cline Evaluation <cline@example.com>
2025-04-24 15:25:40 -07:00
Trevor Hudson 93595af09f Trevhud/eng 592 add title tags to buttons in the bottom left corner (#3080)
* add title tags

* add tooltips, change Cline Rules name, introduce contrast to auto approve + dismiss when click outside

* change to prompts and add hook for click outside to close

* use useClickAway, delete unused component, rename back to cline rules

---------

Co-authored-by: celestial-vault <58194240+celestial-vault@users.noreply.github.com>
2025-04-24 15:24:49 -07:00
Toshii 3828c0d1bc smol (#3086)
* base

* button callback

* prompt

* smol

* full truncate

* base 2

* changeset

* dup new task resp

* Update src/core/prompts/commands.ts

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

* comments

---------

Co-authored-by: ellipsis-dev[bot] <65095814+ellipsis-dev[bot]@users.noreply.github.com>
2025-04-24 15:00:44 -07:00
Evan a2263de7cb Protobus: updateMcpTimeout message (#3085)
* updateMcpTimeout protobus conversion

* changeset
2025-04-24 14:57:00 -07:00
Andrei Eternal e53fa8307d run protos, uh, more -- to prevent WAT maybe (#3091)
Co-authored-by: Andrei Edell <andrei@nugbase.com>
2025-04-24 11:01:21 -10:00
Dennis Bartlett b8cfb87121 Update CHANGELOG.md (#3100) 2025-04-24 12:54:00 -07:00
Dennis Bartlett 76a64ef77d Fix Protobuf WAT 2025-04-24 01:38:40 -07:00
github-actions[bot] 29bdb6c981 v3.13.2 Release Notes
v3.13.2 Release Notes
2025-04-24 00:46:46 -07:00
canvrno 9bbc0da821 [PROTOBUS] file openFile (#3052)
* openFile protobus

* merge conflicts

* fix whitespace

* Fix whitespace... Again

---------

Co-authored-by: Andrei Eternal <garoth@gmail.com>
Co-authored-by: Dennis Bartlett <bartlett.dc.1@gmail.com>
2025-04-23 21:40:46 -10:00
canvrno d2080c1f93 [PROTOBUS] task cancelTask (#3005)
* cancelTask protobuf

* changeset

* corrected changeset

* fixing bad push

* more fixes

* one small change

* ONE more change

* missing await

---------

Co-authored-by: Andrei Eternal <garoth@gmail.com>
2025-04-24 00:20:03 -07:00
canvrno 044dd686a0 Fix for terminal outputs missing commas and non-alphanumeric outputs (#3066) 2025-04-23 19:55:27 -10:00
canvrno ea4f571463 [PROTOBUS] checkpoints checkpointRestore (#3046)
* restoreTask protobus

* changeset

* changeset correction

* type safety change

* Fix Non-UTF-8 File Handling: Improve Encoding Detection to Prevent Garbled Text and Binary Misclassification (#2347)

* Fix Non-UTF-8 File Handling: Improve Encoding Detection to Prevent Garbled Text and Binary Misclassification

* update package-lock.json

* update

* update

* fix

* fix

* fix

* ENG 526/Fix: Versioned Auto Approve settings (#3014)

* added verisoning for autoApprove settings

* removed lines from source branch

* rebase

* changeset

* one small change

* activating extension with evals.env (#3041)

Co-authored-by: Cline Evaluation <cline@example.com>

* ripping out test build flag (#3043)

Co-authored-by: Cline Evaluation <cline@example.com>

* cleaning up evals.env logic in extension.ts (#3045)

Co-authored-by: Cline Evaluation <cline@example.com>

* ENG-516 Slash commands (#3044)

* scroll

* menu

* changeset

* nit

* What's yer path? (#3047)

* update extension imports to use aliasing

* changeset

* ENG-484 Enhance fixWithCline command execution by focusing chat input  (#3028)

* Enhance fixWithCline command execution by focusing chat input and adding a delay before processing the fixWithCline command.

* feat: add OpenRouter base URL and balance display component

* feat: add OpenRouter base URL and balance display component

* feat: add OpenRouter base URL and balance display component

* new_task prompt (#3049)

* prompt

* changeset

* words

* prettier

* Added metadata

---------

Co-authored-by: yt3trees <57471763+yt3trees@users.noreply.github.com>
Co-authored-by: pashpashpash <nik@cline.bot>
Co-authored-by: Cline Evaluation <cline@example.com>
Co-authored-by: Toshii <94262432+0xToshii@users.noreply.github.com>
Co-authored-by: Evan <58194240+celestial-vault@users.noreply.github.com>
Co-authored-by: nomaven <arafat.da.khan@gmail.com>
2025-04-23 19:48:06 -10:00
Sarah Fortune 8cddbcfd99 Install protoc with npm, don't ask the user to install it manually (#3082)
* Use grpc-tools module to install protoc

Add dependencies for npm modules that provide the protoc binary and the ts plugin.
Don't include protos in sub-directories to prevent including node_modules.

* Move proto generator dependencies into top level package.json

* Keep package.json

Otherwise node cannot tell build-proto.js is a module.
2025-04-23 19:39:27 -10:00
Xiaoli 4e0cb64e77 fix: fix mermaid render problem on github caused by space in subgraph name (#2985)
Co-authored-by: Frostbourne <frostbournesb@protonmail.com>
2025-04-23 00:19:05 -07:00
Evan 4aa3764beb Fix: Protoc script version check (#3071)
* update to split by parts

* remove comment
2025-04-22 15:30:40 -10:00
nomaven a525d6dd5e Adding Caching to gemini provider (#3072) 2025-04-23 06:39:49 +05:30
Trevor Hudson 59dd3236e4 add github action for creating linear tickets for unconnected PRs (#3021)
* add github action for creating linear tickets for unconnected PRs

* changset

* only load fetch if not present

* omit fetch

* add error handling

* fix gql query

* only run for opened PRs

* break out into actions

* fix folders

* checkout first

* remove the actions

* add sync

* remove sync
2025-04-22 18:08:47 -07:00
nomaven 5439426ff6 ENG-524 Remove supportsComputerUse restriction and support browser use through any model that supports images (#3048)
* Enhance fixWithCline command execution by focusing chat input and adding a delay before processing the fixWithCline command.

* feat: add OpenRouter base URL and balance display component

* refactor: remove supportsComputerUse from modelInfo and related components, replacing with supportsImages where applicable

* feat: add OpenRouter base URL and balance display component

* feat: add OpenRouter base URL and balance display component

* feat: add OpenRouter base URL and balance display component

* feat: add OpenRouter base URL and balance display component

* feat: add OpenRouter base URL and balance display component
2025-04-23 04:21:18 +04:00
206 changed files with 40955 additions and 3229 deletions
@@ -2,4 +2,4 @@
"claude-dev": minor
---
update prompt for new task
add open ai cache to ui
-5
View File
@@ -1,5 +0,0 @@
---
"claude-dev": minor
---
menu fix for slash commands
-5
View File
@@ -1,5 +0,0 @@
---
"claude-dev": minor
---
Add aliasing to imports in the extension
-5
View File
@@ -1,5 +0,0 @@
---
"claude-dev": patch
---
Add the o1 to the isReasoningModelFamily to avoid temperature be passed to the azure api
-5
View File
@@ -1,5 +0,0 @@
---
"claude-dev": minor
---
Fix add new rule file button not working
-5
View File
@@ -1,5 +0,0 @@
---
"claude-dev": patch
---
Add !include .file directive support for .clineignore
+5
View File
@@ -0,0 +1,5 @@
---
"claude-dev": minor
---
updated gemini caching for OR and cline provider
-5
View File
@@ -1,5 +0,0 @@
---
"claude-dev": patch
---
Fix Ollama provider timeout by increasing it from 30 sec to 120 seconds to accommodate model loading time
-5
View File
@@ -1,5 +0,0 @@
---
"claude-dev": patch
---
Fix Non-UTF-8 File Handling: Improve Encoding Detection to Prevent Garbled Text and Binary Misclassification
+5
View File
@@ -0,0 +1,5 @@
---
"claude-dev": patch
---
Make Previous Updates in the Announcement a dropdown
-5
View File
@@ -1,5 +0,0 @@
---
"claude-dev": minor
---
Update the extension import paths to use aliasing
-5
View File
@@ -1,5 +0,0 @@
---
"claude-dev": patch
---
Fixed bug causing saved settings to get reset by changing providers
-5
View File
@@ -1,5 +0,0 @@
---
"claude-dev": patch
---
Fixes auto approve settings becoming unset
+5
View File
@@ -0,0 +1,5 @@
---
"claude-dev": minor
---
add ui for windsurf and cursor rules
+5
View File
@@ -0,0 +1,5 @@
---
"claude-dev": patch
---
Batch selection and deletion of tasks in history
+5
View File
@@ -0,0 +1,5 @@
---
"claude-dev": minor
---
Migrate getting-started section to new docs
-5
View File
@@ -1,5 +0,0 @@
---
"claude-dev": minor
---
Migrate the toggleMcpServer message to protobus
+3 -3
View File
@@ -30,7 +30,7 @@ graph TB
CheckpointSystem[Git-based Checkpoints]
end
subgraph APIProviders[API Providers]
subgraph apiProviders[API Providers]
AnthropicAPI[Anthropic]
OpenRouterAPI[OpenRouter]
BedrockAPI[AWS Bedrock]
@@ -51,7 +51,7 @@ graph TB
Task --> SecretsStorage
Task --> TaskStorage
Task --> CheckpointSystem
Task --> |API Requests| APIProviders
Task --> |API Requests| apiProviders
McpHub --> |Connects to| ExternalMcpServers
Task --> |Uses| McpHub
@@ -67,7 +67,7 @@ graph TB
style ExtStateContext fill:#bbf,stroke:#333,stroke-width:2px
style WebviewProvider fill:#bfb,stroke:#333,stroke-width:2px
style McpHub fill:#bfb,stroke:#333,stroke-width:2px
style APIProviders fill:#fdb,stroke:#333,stroke-width:2px
style apiProviders fill:#fdb,stroke:#333,stroke-width:2px
```
## Definitions
+3
View File
@@ -13,6 +13,7 @@ permissions:
jobs:
codespell:
if: false
name: Check for spelling errors
runs-on: ubuntu-latest
@@ -23,3 +24,5 @@ jobs:
uses: codespell-project/codespell-problem-matcher@v1
- name: Codespell
uses: codespell-project/actions-codespell@v2
with:
only_warn: 1
+4 -4
View File
@@ -34,7 +34,7 @@ jobs:
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: 20.15.1
node-version: "lts/*"
# Cache root dependencies - only reuse if package-lock.json exactly matches
- name: Cache root dependencies
@@ -54,14 +54,14 @@ jobs:
- name: Install root dependencies
if: steps.root-cache.outputs.cache-hit != 'true'
run: npm ci
run: npm ci --include=optional
- name: Install webview-ui dependencies
if: steps.webview-cache.outputs.cache-hit != 'true'
run: cd webview-ui && npm ci
run: cd webview-ui && npm ci --include=optional
- name: Install Publishing Tools
run: npm install -g vsce ovsx
run: npm install -g @vscode/vsce ovsx
- name: Get Version
id: get_version
+19 -8
View File
@@ -23,7 +23,7 @@ jobs:
- name: Setup Node.js environment
uses: actions/setup-node@v4
with:
node-version: 20.15.1
node-version: 22
# Setup Python for coverage script
- name: Setup Python
@@ -70,19 +70,18 @@ jobs:
run: npm run format
# Build the extension before running tests
- name: Build Extension
run: npm run compile
- name: Build Tests and Extension
run: npm run pretest
# Disabling due to compatability with test framework and ESM modules
# - 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
id: extension_coverage
continue-on-error: true
run: |
xvfb-run -a npm run test:coverage > extension_coverage.txt 2>&1 || true
xvfb-run -a npm run test:coverage > extension_coverage.txt 2>&1
PYTHONPATH=.github/scripts python -m coverage_check extract-coverage extension_coverage.txt --type=extension --github-output --verbose
# Run webview tests with coverage
@@ -107,6 +106,18 @@ jobs:
webview-ui/webview_coverage.txt
retention-period: workflow # Artifacts are automatically deleted when the workflow completes
# Set the check as failed if any of the tests failed
- name: Check for test failures
run: |
# Check if any of the test steps failed
# https://docs.github.com/en/actions/writing-workflows/choosing-what-your-workflow-does/accessing-contextual-information-about-workflow-runs#steps-context
if [ "${{ steps.extension_coverage.outcome }}" != "success" ] || [ "${{ steps.webview_coverage.outcome }}" != "success" ]; then
echo "Tests failed."
cat extension_coverage.txt
cat webview-ui/webview_coverage.txt
exit 1
fi
coverage:
needs: test
runs-on: ubuntu-latest
@@ -132,7 +143,7 @@ jobs:
- name: Setup Node.js environment
uses: actions/setup-node@v4
with:
node-version: 20.15.1
node-version: 22
# Cache root dependencies - only reuse if package-lock.json exactly matches
- name: Cache root dependencies
+1 -1
View File
@@ -1,6 +1,6 @@
{
"extension": ["ts"],
"spec": "src/**/__tests__/*.ts",
"require": ["ts-node/register", "source-map-support/register"],
"require": ["ts-node/register", "source-map-support/register", "./src/test/requires.ts"],
"recursive": true
}
+4
View File
@@ -6,6 +6,10 @@ export default defineConfig({
mocha: {
ui: "bdd",
timeout: 20000, // Maximum time (in ms) that a test can run before failing
/** Set up alias path resolution during tests
* @See {@link file://./test-setup.js}
*/
require: ["./test-setup.js"],
},
workspaceFolder: "test-workspace",
version: "stable",
+1 -1
View File
@@ -9,7 +9,7 @@
"name": "Run Extension",
"type": "extensionHost",
"request": "launch",
"args": ["--extensionDevelopmentPath=${workspaceFolder}"],
"args": ["--extensionDevelopmentPath=${workspaceFolder}", "--disable-workspace-trust", "${workspaceFolder}"],
"outFiles": ["${workspaceFolder}/dist/**/*.js"],
"preLaunchTask": "${defaultBuildTask}",
"env": {
+41 -19
View File
@@ -4,10 +4,25 @@
"version": "2.0.0",
"tasks": [
{
"label": "watch",
"dependsOn": ["npm: build:webview", "npm: dev:webview", "npm: watch:tsc", "npm: watch:esbuild"],
"label": "npm: protos",
"type": "npm",
"script": "protos",
"problemMatcher": [],
"isBackground": false,
"presentation": {
"reveal": "never"
"reveal": "always"
},
"options": {
"env": {
"IS_DEV": "true"
}
}
},
{
"label": "watch",
"dependsOn": ["npm: protos", "npm: build:webview", "npm: dev:webview", "npm: watch:tsc", "npm: watch:esbuild"],
"presentation": {
"reveal": "always"
},
"group": {
"kind": "build",
@@ -16,9 +31,15 @@
},
{
"label": "watch:test",
"dependsOn": ["npm: build:webview:test", "npm: dev:webview", "npm: watch:tsc", "npm: watch:esbuild:test"],
"dependsOn": [
"npm: protos",
"npm: build:webview:test",
"npm: dev:webview",
"npm: watch:tsc",
"npm: watch:esbuild:test"
],
"presentation": {
"reveal": "never"
"reveal": "always"
},
"group": "build"
},
@@ -29,10 +50,10 @@
"problemMatcher": [],
"isBackground": true,
"label": "npm: build:webview",
"dependsOn": ["npm: protos"],
"presentation": {
"group": "watch",
"reveal": "never",
"close": true
"reveal": "always"
},
"options": {
"env": {
@@ -47,10 +68,10 @@
"problemMatcher": [],
"isBackground": true,
"label": "npm: build:webview:test",
"dependsOn": ["npm: protos"],
"presentation": {
"group": "watch",
"reveal": "never",
"close": true
"reveal": "always"
},
"options": {
"env": {
@@ -82,10 +103,10 @@
],
"isBackground": true,
"label": "npm: dev:webview",
"dependsOn": ["npm: protos"],
"presentation": {
"group": "watch",
"reveal": "never",
"close": true
"reveal": "always"
},
"options": {
"env": {
@@ -100,10 +121,10 @@
"problemMatcher": "$esbuild-watch",
"isBackground": true,
"label": "npm: watch:esbuild",
"dependsOn": ["npm: protos"],
"presentation": {
"group": "watch",
"reveal": "never",
"close": true
"reveal": "always"
},
"options": {
"env": {
@@ -118,10 +139,10 @@
"problemMatcher": "$esbuild-watch",
"isBackground": true,
"label": "npm: watch:esbuild:test",
"dependsOn": ["npm: protos"],
"presentation": {
"group": "watch",
"reveal": "never",
"close": true
"reveal": "always"
},
"options": {
"env": {
@@ -137,10 +158,10 @@
"problemMatcher": "$tsc-watch",
"isBackground": true,
"label": "npm: watch:tsc",
"dependsOn": ["npm: protos"],
"presentation": {
"group": "watch",
"reveal": "never",
"close": true
"reveal": "always"
}
},
{
@@ -148,15 +169,16 @@
"script": "watch-tests",
"problemMatcher": "$tsc-watch",
"isBackground": true,
"dependsOn": ["npm: protos"],
"presentation": {
"reveal": "never",
"reveal": "always",
"group": "watchers"
},
"group": "build"
},
{
"label": "tasks: watch-tests",
"dependsOn": ["npm: watch", "npm: watch-tests"],
"dependsOn": ["npm: protos", "npm: watch", "npm: watch-tests"],
"problemMatcher": []
},
{
+5 -1
View File
@@ -37,8 +37,12 @@ docs/**
!node_modules/@vscode/codicons/dist/codicon.css
!node_modules/@vscode/codicons/dist/codicon.ttf
# Include KaTeX CSS and fonts for LaTeX rendering
!webview-ui/node_modules/katex/dist/katex.min.css
!webview-ui/node_modules/katex/dist/fonts/**
# Include default themes JSON files used in getTheme
!src/integrations/theme/default-themes/**
# Include icons
!assets/icons/**
!assets/icons/**
+55
View File
@@ -1,5 +1,60 @@
# Changelog
## [3.14.0]
- Add support for custom model ID in AWS Bedrock provider, enabling use of Application Inference Profile (Thanks @clicube!)
- Add more robust caching & cache tracking for gemini & vertex providers
- Add support for LaTeX rendering
- Add support for custom API request timeout. Timeouts were 15-30s, but can now be configured via settings for OpenRouter/Cline & Ollama (Thanks @WingsDrafterwork!)
- Add truncation notice when truncating manually
- Add a timeout setting for the terminal connection, allowing users to set a time to wait for terminal startup
- Add copy button to code blocks
- Add copy button to markdown blocks (Thanks @weshoke!)
- Add checkpoints to more messages
- Add slash command to create a new rules file (/newrule)
- Add cache ui for open router and cline provider
- Add Amazon Nova Premier model to Bedrock (Thanks @watany!)
- Add support for cursorrules and windsurfrules
- Add support for batch history deletion (Thanks @danix800!)
- Improve Drag & Drop experience
- Create clinerules folder when creating new rule if it's needed
- Enable pricing calculation for gemini and vertex providers
- Refactor message handling to not show the MCP View of the server modal
- Migrate the addRemoteServer to protobus (Thanks @DaveFres!)
- Update task header to be expanded by default
- Update Gemini cache TTL time to 15 minutes
- Fix race condition in terminal command usage
- Fix to correctly handle `import.meta.url`, avoiding leading slash in pathname for Windows (Thanks @DaveFres!)
- Fix @withRetry() decoration syntax error when running extension locally (Thanks @DaveFres!)
- Fix for git commit mentions in repos with no git commits
- Fix cost calculation (Thanks @BarreiroT!)
## [3.13.3]
- Add download counts to MCP marketplace items
- Add `/compact` command
- Add prompt caching to gemini models in cline / openrouter providers
- Add tooltips to bottom row menu
## [3.13.2]
- Add Gemini 2.5 Flash model to Vertex and Gemini Providers (Thanks monotykamary!)
- Add Caching to gemini provider (Thanks arafatkatze!)
- Add thinking budget support to Gemini Models (Thanks monotykamary!)
- Add !include .file directive support for .clineignore (Thanks watany-dev!)
- Improve slash command functionality
- Improve prompting for new task tool
- Fix o1 temperature being passed to the azure api (Thanks treeleaves30760!)
- Fix to make "add new rule file" button functional
- Fix Ollama provider timeout, allowing for a larger loading time (Thanks suvarchal!)
- Fix Non-UTF-8 File Handling: Improve Encoding Detection to Prevent Garbled Text and Binary Misclassification (Thanks yt3trees!)
- Fix settings to not reset by changing providers
- Fix terminal outputs missing commas
- Fix terminal errors caused by starting non-alphanumeric outputs
- Fix auto approve settings becoming unset
- Fix Mermaid syntax error in documentation (Thanks tuki0918!)
- Remove supportsComputerUse restriction and support browser use through any model that supports images (Thanks arafatkatze!)
## [3.13.1]
- Fix bug where task cancellation during thinking stream would result in error state
Binary file not shown.

After

Width:  |  Height:  |  Size: 902 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 666 B

+95
View File
@@ -0,0 +1,95 @@
{
"$schema": "https://mintlify.com/docs.json",
"theme": "linden",
"name": "Cline",
"description": "AI-powered coding assistant for VSCode",
"colors": {
"primary": "#9D4EDD",
"light": "#F0E6FF",
"dark": "#000000"
},
"logo": {
"light": "/assets/robot_panel_light.png",
"dark": "/assets/robot_panel_dark.png"
},
"favicon": {
"light": "/assets/robot_panel_light.png",
"dark": "/assets/robot_panel_dark.png"
},
"background": {
"color": {
"light": "#F0E6FF",
"dark": "#000000"
},
"decoration": "gradient"
},
"styling": {
"eyebrows": "breadcrumbs",
"codeblocks": "system"
},
"appearance": {
"default": "system",
"strict": false
},
"fonts": {
"family": "Roboto",
"weight": 400
},
"navbar": {
"links": [
{
"label": "GitHub",
"href": "https://github.com/cline/cline"
},
{
"label": "Discord",
"href": "https://discord.gg/cline"
}
],
"primary": {
"type": "button",
"label": "Install Cline",
"href": "https://cline.bot/install?utm_source=website&utm_medium=header"
}
},
"navigation": {
"groups": [
{
"group": "Getting Started",
"pages": [
"getting-started/for-new-coders",
"getting-started/installing-cline",
"getting-started/installing-dev-essentials",
"getting-started/model-selection-guide",
"getting-started/our-favorite-tech-stack",
"getting-started/understanding-context-management",
"getting-started/what-is-cline"
]
},
{
"group": "Exploring Cline's Tools",
"pages": [
"exploring-clines-tools/cline-tools-guide",
"exploring-clines-tools/plan-and-act-modes-a-guide-to-effective-ai-development",
"exploring-clines-tools/checkpoints",
"exploring-clines-tools/new-task-tool",
"exploring-clines-tools/remote-browser-support",
"exploring-clines-tools/slash-commands"
]
}
]
},
"footer": {
"socials": {
"x": "https://x.com/cline",
"github": "https://github.com/cline/cline",
"discord": "https://discord.gg/cline"
}
},
"search": {
"prompt": "Search Cline documentation..."
},
"contextual": {
"options": ["copy"]
}
}
+108
View File
@@ -0,0 +1,108 @@
---
title: "Checkpoints and Messages"
description: "When working with AI coding assistants, it's easy to lose control as they make rapid changes to your codebase. That's why we built Checkpoints - your safety net for experimenting confidently."
---
Checkpoints automatically save snapshots of your workspace after each step in a task. This powerful feature lets you:
- Track and review changes made during a task
- Roll back to any previous point if needed
- Experiment confidently with auto-approve mode
- Maintain full control over your workspace
### ⚙️ How Checkpoints Work
Cline creates a checkpoint after each tool use (file edits, commands, etc.). These checkpoints:
- Work alongside your Git workflow without interference
- Maintain context between restores
- Use a shadow Git repository to track changes
For example, if you're working on a feature and Cline makes multiple file changes, each change creates a checkpoint. This means you can review each modification and, if needed, roll back to any point without affecting your main Git repository.
#### Viewing Changes & Restoring to Checkpoint
After each tool use, you can:
1. Click the "Compare" button to see modified files
2. Click the "Restore" button to open restore options
<Frame>
<img src="/assets/robot_panel_dark.png" alt="Checkpoint comparison and restore options" />
</Frame>
#### Rolling Back
To restore to a previous point:
1. Click the "Restore" button next to any step
2. Choose from three options:
- **Restore Task and Workspace**: Reset both codebase and task to that point
- **Restore Task Only**: Keep codebase changes but revert task context
- **Restore Workspace Only**: Reset codebase while preserving task context
Example: If Cline makes changes you don't like while styling a component, you can use "Restore Workspace Only" to revert the code changes while keeping the conversation context, allowing you to try a different approach.
### 💡 Use Cases
Checkpoints let you be more experimental with Cline. While human coding is often methodical and iterative, AI can make substantial changes quickly. Checkpoints help you track these changes and revert if needed.
#### 1. Using Auto-Approve Mode
- Provides safety net for rapid iterations
- Makes it easy to undo unexpected results
#### 2. Testing Different Approaches
- Try multiple solutions confidently
- Compare different implementations
- Quickly revert to working states
- Ideal for exploring different design patterns or architectural approaches
<Frame caption="In this case, I didn't like the changes Cline made to my robot dog-walking website (still working on the robots) and I wanted to revert both the codebase and the task to before any changes were made so I could start fresh.">
<img src="/assets/robot_panel_dark.png" alt="Checkpoint restore demo" />
</Frame>
### ✨ Best Practices
1. Use checkpoints as safety nets when experimenting
2. Leverage auto-approve mode more confidently, knowing you can always roll back
3. Restore selectively based on needs:
- Use "Restore Task and Workspace" for a fresh start, reversing changes to files and the task conversation.
- Use "Restore Task Only" to try different prompts, but leave all files as they exist
- Use "Restore Workspace Only" to attempt different implementations, or prune context from the task
🛟 Checkpoints are your safety net when working with Cline, enabling you to experiment freely while maintaining full control over your codebase. Whether you're refactoring a complex component, trying different implementation approaches, or using auto-approve mode for rapid development, checkpoints ensure you can always review changes and roll back if needed.
#### 🗑️ Deleting Checkpoints
You can delete all checkpoints by using the **"Delete All History"** button in the task history menu. Note that this will also delete all tasks. Checkpoints are stored in VS Code's globalStorage.
---
## Editing Messages
Cline allows you to edit chat messages in a task after they've been submitted (with the exception of the message that started the task).
Perhaps you didn't get the results you wanted, thought of a better way to phrase your request, or need to add more information. Editing your message allows you to re-submit a request without starting over or restoring your files or workspace with checkpoints. There are two Restore options:
- **"Restore Chat"** restores just the task state and re-submits an API request to your provider with your edited message.
- **"Restore All"** restores both the task state and workspace state before re-submitting an API request. "Workspace state" refers to the condition of your workspace (files, content, etc.) at different points in the conversation.
**Interactive Editing:**
- Messages can be clicked to enter edit mode
- Cline automatically selects all text when entering edit mode
**Keyboard Shortcuts:**
- Escape: Exit edit mode
- Enter: Restore just the task
- Cmd/Ctrl + Enter: Restore the task and workspace
- Shift + Enter: Insert new line / line break
<Frame>
<img src="/assets/robot_panel_dark.png" alt="Message editing interface" />
</Frame>
@@ -0,0 +1,139 @@
---
title: "Cline Tools Reference Guide"
---
## What Can Cline Do?
Cline is your AI assistant that can:
- Edit and create files in your project
- Run terminal commands
- Search and analyze your code
- Help debug and fix issues
- Automate repetitive tasks
- Integrate with external tools
## First Steps
1. **Start a Task**
- Type your request in the chat
- Example: "Create a new React component called Header"
2. **Provide Context**
- Use @ mentions to add files, folders, or URLs
- Example: "@file:src/components/App.tsx"
3. **Review Changes**
- Cline will show diffs before making changes
- You can edit or reject changes
## Key Features
1. **File Editing**
- Create new files
- Modify existing code
- Search and replace across files
2. **Terminal Commands**
- Run npm commands
- Start development servers
- Install dependencies
3. **Code Analysis**
- Find and fix errors
- Refactor code
- Add documentation
4. **Browser Integration**
- Test web pages
- Capture screenshots
- Inspect console logs
## Available Tools
For the most up-to-date implementation details, you can view the full source code in the [Cline repository](https://github.com/cline/cline/blob/main/src/core/Cline.ts).
Cline has access to the following tools for various tasks:
1. **File Operations**
- `write_to_file`: Create or overwrite files
- `read_file`: Read file contents
- `replace_in_file`: Make targeted edits to files
- `search_files`: Search files using regex
- `list_files`: List directory contents
2. **Terminal Operations**
- `execute_command`: Run CLI commands
- `list_code_definition_names`: List code definitions
3. **MCP Tools**
- `use_mcp_tool`: Use tools from MCP servers
- `access_mcp_resource`: Access MCP server resources
- Users can create custom MCP tools that Cline can then access
- Example: Create a weather API tool that Cline can use to fetch forecasts
4. **Interaction Tools**
- `ask_followup_question`: Ask user for clarification
- `attempt_completion`: Present final results
Each tool has specific parameters and usage patterns. Here are some examples:
- Create a new file (write_to_file):
```xml
<write_to_file>
<path>src/components/Header.tsx</path>
<content>
// Header component code
</content>
</write_to_file>
```
- Search for a pattern (search_files):
```xml
<search_files>
<path>src</path>
<regex>function\s+\w+\(</regex>
<file_pattern>*.ts</file_pattern>
</search_files>
```
- Run a command (execute_command):
```xml
<execute_command>
<command>npm install axios</command>
<requires_approval>false</requires_approval>
</execute_command>
```
## Common Tasks
1. **Create a New Component**
- "Create a new React component called Footer"
2. **Fix a Bug**
- "Fix the error in src/utils/format.ts"
3. **Refactor Code**
- "Refactor the Button component to use TypeScript"
4. **Run Commands**
- "Run npm install to add axios"
## Getting Help
- [Join the Discord community](https://discord.gg/cline)
- Check the documentation
- Provide feedback to improve Cline
@@ -0,0 +1,381 @@
---
title: "New Task Tool"
---
### The `new_task` Tool & Context Management Strategies
#### Overview
Cline includes a powerful internal tool, `new_task`, designed to help manage workflow continuity and context preservation, especially during complex or long-running tasks. This tool, combined with Cline's awareness of its own context window usage and the flexibility of `.clinerules`, enables sophisticated strategies for breaking down work and ensuring seamless transitions between task sessions.
Understanding the core capabilities and how they interact with custom rules is key to leveraging this feature effectively.
#### Core Capabilities
Two fundamental capabilities enable advanced context management:
1. **The `new_task` Tool:**
- **Function:** Allows Cline, upon user approval, to end the current task session and immediately start a new one.
- **Context Preloading:** Crucially, Cline can **preload** this new task session with specific context provided within the tool's `<context>` block. This context can be anything Cline or a `.clinerules` file defines summaries, code snippets, next steps, project state, etc.
2. **Context Window Awareness:**
- **Tracking:** Cline internally tracks the percentage of its available context window currently being used during a task.
- **Visibility:** This information is visible in the `environment_details` provided to Cline in its prompt.
#### Using the `/newtask` Slash Command
As a quick alternative to Cline suggesting the `newtask` tool or defining complex rules, you can directly initiate the process using a Slash Command.
- **How:** Simply type `/newtask` in the chat input field.
- **Action:** Cline will propose creating a new task, typically suggesting context based on the current session (similar to its default behavior when using the tool). You will still get the `ask_followup_question` prompt to confirm and potentially modify the context before the new task is created.
- **Benefit:** Provides a fast, user-initiated way to leverage the `new_task` functionality for branching explorations or managing long sessions without waiting for Cline to suggest it.
#### Default Behavior (Without `.clinerules`)
By default, without specific `.clinerules` dictating its behavior:
- **Tool Availability:** The `new_task` tool exists, and Cline _can_ choose to use it.
- **Context Awareness:** Cline _is_ aware of its context usage percentage.
- **No Automatic Trigger:** Cline **will not** automatically initiate a task handoff _solely_ based on context usage reaching a specific percentage (like 50%). The decision to suggest using `new_task` comes from the AI model's reasoning based on the overall task progress and prompt instructions.
- **Basic Context Preloading:** If `new_task` is used without specific rules defining the `<context>` block structure, Cline will attempt to preload relevant information based on its current understanding (e.g., a basic summary of progress and next steps), but this may be less comprehensive than a rule-driven approach.
#### The Power of `.clinerules`: Enabling Custom Workflows
While the core capabilities exist by default, the true power, automation, and customization emerge when you combine `new_task` and context awareness with custom workflows defined in `.clinerules`. This allows you to precisely control _when_ and _how_ Cline manages context and task continuity.
Key benefits of using `.clinerules` with `new_task`:
- **Automated Context Management:** Define rules to automatically trigger handoffs at specific context percentages (e.g., >50%, >70%) or token counts, ensuring optimal performance and preventing context loss.
- **Model-Specific Optimization:** Tailor handoff triggers based on known thresholds for different LLMs (e.g., trigger earlier for models known to degrade past a certain token count).
- **Intelligent Breakpoints:** Instruct Cline via rules to find logical stopping points (e.g., after completing a function or test) _after_ a context threshold is passed, ensuring cleaner handoffs.
- **Structured Task Decomposition:** Use Plan Mode to define subtasks, then use `.clinerules` to have Cline automatically create a new task via `new_task` upon completing each subtask, preloading the context for the _next_ subtask.
- **Custom Context Packaging:** Mandate the exact structure and content of the `<context>` block in `.clinerules` for highly detailed and consistent handoffs (see example below).
- **Improved Memory Persistence:** Use `new_task` context blocks as a primary, integrated way to persist information across sessions, potentially replacing or supplementing file-based memory systems.
- **Workflow Automation:** Define rules for specific scenarios, like always preloading certain setup instructions or project boilerplate when starting tasks of a particular type.
#### Example Rule-Driven Workflow: Task Handoff Process
A common workflow, **driven by specific `.clinerules` like the example below**, involves these steps:
1. **Trigger Identification (Rule-Based):** Cline monitors for handoff points defined in the rules (e.g., context usage > 50%, task completion).
2. **User Confirmation:** Cline uses `ask_followup_question` to propose creating a new task, often showing the intended context defined by the rules.
```xml
<ask_followup_question>
<question>I've completed [specific accomplishment] and context usage is high (XX%). Would you like me to create a new task to continue with [remaining work], preloading the following context?</question>
<options>["Yes, create new task", "Modify context first", "No, continue this session"]</options>
</ask_followup_question>
```
3. **User Control:** You can approve, deny, or ask Cline to modify the context before the new task is created.
4. **Context Packaging (`new_task` Tool):** If approved, Cline uses `new_task`, packaging the context according to the structure mandated by the `.clinerules`.
5. **New Task Creation:** The current task ends, and a new session begins immediately, preloaded with the specified context.
#### The Handoff Context Block (Rule-Defined Structure)
The effectiveness of rule-driven handoffs depends heavily on how `.clinerules` define the `<context>` block. A comprehensive structure often includes:
- **`## Completed Work`**: Detailed list of accomplishments, files modified/created, key decisions.
- **`## Current State`**: Project status, running processes, key file states.
- **`## Next Steps`**: Clear, prioritized list of remaining tasks, implementation details, known challenges.
- **`## Reference Information`**: Links, code snippets, patterns, user preferences.
- **Actionable Start:** A clear instruction for the immediate next action.
#### Potential Use Cases & Workflows
The flexibility of `new_task` combined with `.clinerules` opens up many possibilities:
- **Proactive Context Window Management:** Automatically trigger handoffs at specific percentages (e.g., 50%, 70%) or token counts to maintain optimal performance.
- **Intelligent Breakpoints:** Instruct Cline to find logical stopping points (e.g., after completing a function or test) _after_ a context threshold is passed, ensuring cleaner handoffs.
- **Structured Task Decomposition:** Use Plan Mode to define subtasks, then use `.clinerules` to have Cline automatically create a new task via `new_task` upon completing each subtask.
- **Automated Session Summaries:** Configure the `<context>` block to always include a summary of the previous session's key discussion points.
- **Preloading Boilerplate/Setup:** Start new tasks related to specific projects preloaded with standard setup instructions or file templates.
- **"Memory Bank" Alternative:** Use `new_task` context blocks as the primary way to persist information across sessions, potentially replacing file-based memory systems.
Experimenting with `.clinerules` is encouraged to discover workflows that best suit your needs!
#### Example `.clinerules`: Task Handoff Strategy Guide
Below is an example `.clinerules` file focused specifically on using `new_task` for context window management. **Remember, this is just one specific strategy; the core `new_task` tool can be used differently with other custom rules.**
````markdown
# You MUST use the `new_task` tool: Task Handoff Strategy Guide
**⚠️ CRITICAL INSTRUCTIONS - YOU MUST FOLLOW THESE GUIDELINES ⚠️**
This guide provides **MANDATORY** instructions for effectively breaking down complex tasks and implementing a smooth handoff process between tasks. You **MUST** follow these guidelines to ensure continuity, context preservation, and efficient task completion.
## ⚠️ CONTEXT WINDOW MONITORING - MANDATORY ACTION REQUIRED ⚠️
You **MUST** monitor the context window usage displayed in the environment details. When usage exceeds 50% of the available context window, you **MUST** initiate a task handoff using the `new_task` tool.
Example of context window usage over 50% with a 200K context window:
\`\`\`text
# Context Window Usage
105,000 / 200,000 tokens (53%)
Model: anthropic/claude-3.7-sonnet (200K context window)
\`\`\`
**IMPORTANT**: When you see context window usage at or above 50%, you MUST:
1. Complete your current logical step
2. Use the `ask_followup_question` tool to offer creating a new task
3. If approved, use the `new_task` tool with comprehensive handoff instructions
## Task Breakdown in Plan Mode - REQUIRED PROCESS
Plan Mode is specifically designed for analyzing complex tasks and breaking them into manageable subtasks. When in Plan Mode, you **MUST**:
### 1. Initial Task Analysis - REQUIRED
- **MUST** begin by thoroughly understanding the full scope of the user's request
- **MUST** identify all major components and dependencies of the task
- **MUST** consider potential challenges, edge cases, and prerequisites
### 2. Strategic Task Decomposition - REQUIRED
- **MUST** break the overall task into logical, discrete subtasks
- **MUST** prioritize subtasks based on dependencies (what must be completed first)
- **MUST** aim for subtasks that can be completed within a single session (15-30 minutes of work)
- **MUST** consider natural breaking points where context switching makes sense
### 3. Creating a Task Roadmap - REQUIRED
- **MUST** present a clear, numbered list of subtasks to the user
- **MUST** explain dependencies between subtasks
- **MUST** provide time estimates for each subtask when possible
- **MUST** use Mermaid diagrams to visualize task flow and dependencies when helpful
\`\`\`mermaid
graph TD
A[Main Task] --> B[Subtask 1: Setup]
A --> C[Subtask 2: Core Implementation]
A --> D[Subtask 3: Testing]
A --> E[Subtask 4: Documentation]
B --> C
C --> D
\`\`\`
### 4. Getting User Approval - REQUIRED
- **MUST** ask for user feedback on the proposed task breakdown
- **MUST** adjust the plan based on user priorities or additional requirements
- **MUST** confirm which subtask to begin with
- **MUST** request the user to toggle to Act Mode when ready to implement
## Task Implementation and Handoff Process - MANDATORY PROCEDURES
When implementing tasks in Act Mode, you **MUST** follow these guidelines for effective task handoff:
### 1. Focused Implementation - REQUIRED
- **MUST** focus on completing the current subtask fully
- **MUST** document progress clearly through comments and commit messages
- **MUST** create checkpoints at logical completion points
### 2. Recognizing Completion Points - CRITICAL
You **MUST** identify natural handoff points when:
- The current subtask is fully completed
- You've reached a logical stopping point in a larger subtask
- The implementation is taking longer than expected and can be continued later
- The task scope has expanded beyond the original plan
- **CRITICAL**: The context window usage exceeds 50% (e.g., 100,000+ tokens for a 200K context window)
### 3. Initiating the Handoff Process - MANDATORY ACTION
When you've reached a completion point, you **MUST**:
1. Summarize what has been accomplished so far
2. Clearly state what remains to be done
3. **MANDATORY**: Use the `ask_followup_question` tool to offer creating a new task:
\`\`\`xml
<ask_followup_question>
<question>I've completed [specific accomplishment]. Would you like me to create a new task to continue with [remaining work]?</question>
<options>["Yes, create a new task", "No, continue in this session", "Let me think about it"]</options>
</ask_followup_question>
\`\`\`
### 4. Creating a New Task with Context - REQUIRED ACTION
If the user agrees to create a new task, you **MUST** use the `new_task` tool with comprehensive handoff instructions:
\`\`\`xml
<new_task>
<context>
# Task Continuation: [Brief Task Title]
## Completed Work
- [Detailed list of completed items]
- [Include specific files modified/created]
- [Note any important decisions made]
## Current State
- [Description of the current state of the project]
- [Any running processes or environment setup]
- [Key files and their current state]
## Next Steps
- [Detailed list of remaining tasks]
- [Specific implementation details to address]
- [Any known challenges to be aware of]
## Reference Information
- [Links to relevant documentation]
- [Important code snippets or patterns to follow]
- [Any user preferences noted during the current session]
Please continue the implementation by [specific next action].
</context>
</new_task>
\`\`\`
### 5. Detailed Context Transfer - MANDATORY COMPONENTS
When creating a new task, you **MUST** always include:
#### Project Context - REQUIRED
- **MUST** include the overall goal and purpose of the project
- **MUST** include key architectural decisions and patterns
- **MUST** include technology stack and dependencies
#### Implementation Details - REQUIRED
- **MUST** list files created or modified in the current session
- **MUST** describe specific functions, classes, or components implemented
- **MUST** explain design patterns being followed
- **MUST** outline testing approach
#### Progress Tracking - REQUIRED
- **MUST** provide checklist of completed items
- **MUST** provide checklist of remaining items
- **MUST** note any blockers or challenges encountered
#### User Preferences - REQUIRED
- **MUST** note coding style preferences mentioned by the user
- **MUST** document specific approaches requested by the user
- **MUST** highlight priority areas identified by the user
## Best Practices for Effective Handoffs - MANDATORY GUIDELINES
### 1. Maintain Continuity - REQUIRED
- **MUST** use consistent terminology between tasks
- **MUST** reference previous decisions and their rationale
- **MUST** maintain the same architectural approach unless explicitly changing direction
### 2. Preserve Context - REQUIRED
- **MUST** include relevant code snippets in the handoff
- **MUST** summarize key discussions from the previous session
- **MUST** reference specific files and line numbers when applicable
### 3. Set Clear Next Actions - REQUIRED
- **MUST** begin the handoff with a clear, actionable next step
- **MUST** prioritize remaining tasks
- **MUST** highlight any decisions that need to be made
### 4. Document Assumptions - REQUIRED
- **MUST** clearly state any assumptions made during implementation
- **MUST** note areas where user input might be needed
- **MUST** identify potential alternative approaches
### 5. Optimize for Resumability - REQUIRED
- **MUST** structure the handoff so the next session can begin working immediately
- **MUST** include setup instructions if environment configuration is needed
- **MUST** provide a quick summary at the top for rapid context restoration
## Example Task Handoff
### Example #1 of an effective task handoff:
\`\`\`xml
<new_task>
<context>
# Task Continuation: Implement User Authentication System
## Completed Work
- Created basic Express.js server structure
- Implemented MongoDB connection and user schema
- Completed user registration endpoint with password hashing
- Added input validation using Joi
- Created initial test suite for registration endpoint
## Current State
- Server runs successfully on port 3000
- MongoDB connection is established
- Registration endpoint (/api/users/register) is fully functional
- Test suite passes for all registration scenarios
## Next Steps
1. Implement login endpoint (/api/users/login)
- Use bcrypt to compare passwords
- Generate JWT token upon successful login
- Add proper error handling for invalid credentials
2. Create authentication middleware
- Verify JWT tokens
- Extract user information
- Handle expired tokens
3. Add protected routes that require authentication
4. Implement password reset functionality
## Reference Information
- JWT secret should be stored in .env file
- Follow the existing error handling pattern in routes/users.js
- User schema is defined in models/User.js
- Test patterns are established in tests/auth.test.js
Please continue by implementing the login endpoint following the same patterns established in the registration endpoint.
</context>
</new_task>
\`\`\`
### Example #2 of an ineffective task handoff:
_(Note: The example provided in the original rules showing "YOLO MODE Implementation" seems less like a direct handoff context block and more like a general status update with future considerations. A true ineffective handoff might lack detail in 'Current State' or 'Next Steps')._
## When to Use Task Handoffs - MANDATORY TRIGGERS
You **MUST** initiate task handoffs in these scenarios:
1. **CRITICAL**: When context window usage exceeds 50% (e.g., 100,000+ tokens for a 200K context window)
2. **Long-running projects** that exceed a single session
3. **Complex implementations** with multiple distinct phases
4. **When context window limitations** are approaching
5. **When switching focus areas** within a larger project
6. **When different expertise** might be beneficial for different parts of the task
**⚠️ FINAL REMINDER - CRITICAL INSTRUCTION ⚠️**
You **MUST** monitor the context window usage in the environment details section. When it exceeds 50% (e.g., "105,000 / 200,000 tokens (53%)"), you **MUST** proactively initiate the task handoff process using the `ask_followup_question` tool followed by the `new_task` tool. You MUST use the `new_task` tool.
By strictly following these guidelines, you'll ensure smooth transitions between tasks, maintain project momentum, and provide the best possible experience for users working on complex, multi-session projects.
```markdown
## User Interaction & Workflow Considerations
- **Linear Flow:** Currently, using `new_task` creates a linear sequence. The old task ends, and the new one begins. The old task history remains accessible for backtracking.
- **User Approval:** You always have control, approving the handoff and having the chance to modify the context Cline proposes to carry forward.
- **Flexibility:** The core `new_task` tool is a flexible building block. Experiment with `.clinerules` to create workflows that best suit your needs, whether for strict context management, task decomposition, or other creative uses.
```
````
@@ -0,0 +1,136 @@
---
title: "Plan & Act Modes: A Guide to Effective AI Development"
---
## Overview
Plan & Act modes represent Cline's approach to structured AI development, emphasizing thoughtful planning before implementation. This dual-mode system helps developers create more maintainable, accurate code while reducing iteration time.
<Frame>
<img src="/assets/robot_panel_dark.png" alt="Use Plan to gather context before using Act to implement the plan" />
</Frame>
### Understanding the Modes
#### Plan Mode
- Optimized for context gathering and strategy
- Cannot make changes to your codebase
- Focused on understanding requirements and creating implementation plans
- Enables full file reading for comprehensive project understanding
#### Act Mode
- Streamlined for implementation based on established plans
- Has access to all of Cline's building capabilities
- Maintains context from the planning phase
- Can execute changes to your codebase
<Frame>
<img src="/assets/robot_panel_dark.png" alt="Act mode capabilities" />
</Frame>
### Workflow Guide
#### 1. Start with Plan Mode
Begin every significant development task in Plan mode:
In this mode:
<Frame>
<img src="/assets/robot_panel_dark.png" alt="Plan mode workflow" />
</Frame>
- Share your requirements
- Let Cline analyze relevant files
- Engage in dialogue to clarify objectives
- Develop implementation strategy
<Frame>
<img src="/assets/robot_panel_dark.png" alt="Planning phase" />
</Frame>
#### 2. Switch to Act Mode
Once you have a clear plan, switch to Act mode:
<Frame>
<img src="/assets/robot_panel_dark.png" alt="Switching to Act mode" />
</Frame>
Act mode allows Cline to:
- Execute against the agreed plan
- Make changes to your codebase
- Maintain context from planning phase
#### 3. Iterate as Needed
Complex projects often require multiple plan-act cycles:
- Return to Plan mode when encountering unexpected complexity
- Use Act mode for implementing solutions
- Maintain development momentum while ensuring quality
### Best Practices
#### Planning Phase
1. Be comprehensive with requirements
2. Share relevant context upfront
3. Point Cline to relevant files if he hasn't read them
4. Validate approach before implementation
#### Implementation Phase
1. Follow the established plan
2. Monitor progress against objectives
3. Track changes and their impact
4. Document significant decisions
<Frame>
<img src="/assets/robot_panel_dark.png" alt="Implementation best practices" />
</Frame>
### Power User Tips
#### Enhancing Planning
- Use Plan mode to explore edge cases before implementation
- Switch back to Plan when encountering unexpected complexity
- Leverage file reading to validate assumptions early
- Have Cline write markdown files of the plan for future reference
### Common Patterns
#### When to Use Plan Mode
- Starting new features
- Debugging complex issues
- Architectural decisions
- Requirements analysis
#### When to Use Act Mode
- Implementing agreed solutions
- Making routine changes
- Following established patterns
- Executing test cases
<Frame>
<img src="/assets/robot_panel_dark.png" alt="Mode usage patterns" />
</Frame>
### Contributing
Share your experiences and improvements:
- Join our [Discord community](https://discord.gg/cline)
- Participate in discussions
- Submit feature requests
- Report issues
---
Remember: The time invested in planning pays dividends in implementation quality and maintenance efficiency
@@ -0,0 +1,114 @@
---
title: "Remote Browser Support"
description: "Remote browser support allows Cline to utilize a remote Chrome instance, leveraging authentication tokens and session cookies relevant to certain web development test cases."
icon: globe-pointer
---
The Remote Browser feature in Cline allows the AI assistant to interact with web content directly through a controlled browser instance. This enables several powerful capabilities:
- Viewing and interacting with websites
- Testing locally running web applications
- Monitoring console logs and errors
- Performing browser actions like clicking, typing, and scrolling
## Remote Browser in Cline
### What is Remote Browser?
Remote Browser allows Cline to view and interact with websites directly. This feature enables Cline to:
- Visit websites and view their content
- Test your locally running web applications
- Fill out forms and click on elements
- Capture screenshots of what it sees
- Scroll through pages to see more content
### How to Use Remote Browser
#### Basic Commands
You can ask Cline to use the browser with simple instructions:
- **Open a website**: "Use the browser to check the website at [https://example.com](https://example.com/)"
- **Click on elements**: "Click the login button"
- **Type text**: "Type 'Hello world' in the search box"
- **Scroll the page**: "Scroll down to see more content"
- **Close the browser**: "Close the browser now"
#### Example Workflows
**Testing a Web Application:**
```javascript
Can you start my React app with "npm start" and then check if it's working properly at http://localhost:3000?
```
**Analyzing a Website:**
```javascript
Can you visit https://example.com and tell me what you think about its design and layout?
```
**Filling Out a Form:**
```javascript
Please go to https://example.com/contact, fill out the contact form with some test data, and submit it.
```
### Important Things to Know
#### One Browser at a Time
Cline can only use one browser at a time. If you want to visit a different website, you can either:
- Ask Cline to navigate to a new URL within the same browser session
- Ask Cline to close the current browser and open a new one
#### Browser Must Be Closed Before Using Other Tools
If you want Cline to edit files or run commands after using the browser, you must first ask it to close the browser:
```javascript
Close the browser and then update the CSS file to fix the alignment issue we saw.
```
#### What Cline Sees
The browser has a fixed viewport size (900x600 pixels by default), similar to a small laptop screen. Cline will share screenshots after each action so you can see exactly what it sees.
#### Console Logs
Cline captures browser console logs, which can be helpful for debugging web applications. These logs are included with each screenshot.
### Common Use Cases
- **Web Development**: Test your websites and web applications
- **UI/UX Review**: Get feedback on website design and usability
- **Content Research**: Have Cline browse websites to gather information
- **Form Testing**: Verify that forms work correctly
- **Responsive Design Testing**: Check how websites look at different screen sizes
### Troubleshooting
- **If a website doesn't load**: Try providing a direct URL with the http:// or https:// prefix
- **If clicking doesn't work**: Try describing the location of the element more precisely
- **If the browser seems stuck**: Ask Cline to close the browser and try again
### Using Remote Browser with VS Code in WSL
When running VS Code in WSL, you'll need to configure Windows to allow WSL to connect to Chrome. Follow these steps:
#### Open PowerShell as Administrator and Run:
```powershell
# Allow WSL to connect to Chrome's debugging port
New-NetFirewallRule -DisplayName "WSL Chrome Debug" -Direction Inbound -LocalPort 9222 -Protocol TCP -Action Allow
```
#### Configure Cline in VS Code:
1. Open VS Code settings
2. Search for "Cline: Chrome Executable Path"
3. Set the value to the path of your Chrome executable (e.g., `C:\Program Files\Google\Chrome\Application\chrome.exe`)
Cline should now be able to use the Remote Browser feature from within WSL.
@@ -0,0 +1,57 @@
---
title: "Slash Commands"
---
#### Overview
Cline provides slash commands as a quick way to invoke specific tools or actions directly from the chat input, offering shortcuts for common operations. This page details the available slash commands and their usage.
#### /newtask
The `/newtask` slash command provides a fast, user-initiated way to leverage the `new_task` tool's functionality for branching explorations or managing long sessions without waiting for Cline to suggest it.
**Functionality:**
1. **Initiation:** Typing `/newtask` in the chat input signals Cline to prepare for starting a new task session.
2. **Context Proposal:** Cline proposes creating a new task and typically suggests context to preload based on the current session (summarizing key aspects like current work, technical concepts, relevant files, problems solved, and next steps).
3. **User Confirmation:** You will receive a confirmation prompt (via the `ask_followup_question` tool) displaying the proposed context. You can approve it directly or modify the context before the new task begins.
4. **New Session:** Upon confirmation, Cline ends the current task session and immediately starts a new one, preloaded with the approved context.
**Benefit:** Allows you to cleanly branch your work or start a new phase while carrying over essential background information ("knowledge transfer") without manual copying or losing the thread of the previous session.
#### /smol (alias /compact)
The `/smol` slash command (with `/compact` as an alias) allows you to condense the chat history **within your current task**. This is useful when a conversation becomes very long, potentially impacting performance or making it harder for the model to maintain focus.
**Functionality:**
1. **Initiation:** Typing `/smol` or `/compact` tells Cline you want to condense the current chat history. You can optionally add instructions after the command to guide the summarization process (e.g., `/smol focus only on the database changes` or `/smol be concise, use bullet points`).
2. **Summarization:** Cline analyzes the conversation history, considering any additional instructions provided, and generates a summary focusing on key elements: recent discussion points, important decisions, technical concepts, relevant files, problems solved, and planned next steps. Cline determines the appropriate length and detail for the summary. It retains the beginning and very recent parts of the chat while summarizing the middle sections.
3. **User Confirmation:** Cline presents this generated summary to you via a confirmation prompt and asks if it accurately reflects the essential context.
4. **Condensing:** If you approve the summary, Cline replaces the summarized middle portion of the chat history in its active context with the generated summary. This reduces the overall token count for subsequent interactions within the _same task_.
5. **Feedback:** If you reject the summary or provide feedback, Cline will retain the original history and incorporate your feedback for future actions.
**Benefit:** Helps maintain focus and manage token usage during very long, continuous tasks (like deep debugging or extended feature development) without needing to start an entirely new task session. Allows user guidance on the summarization focus.
#### When to Use Which?
Choosing between `/newtask` and `/smol` depends on your goal:
- Use `/smol` (or `/compact`) when:
- You want to continue the **same task**, but the chat history has become very long or costly.
- You need to reduce token usage for upcoming interactions within the current workflow.
- Example: Deep debugging session where you want to summarize previous steps before continuing.
- Use `/newtask` when:
- You have finished one phase of work and want to start a **fresh, related task**.
- You want to branch your exploration while preserving key context from the previous session.
- Example: Moving from developing Feature A to starting work on Feature B, carrying over relevant architectural decisions.
#### Why Manage Context?
While Cline supports large context windows, actively managing context using tools and commands like `/newtask` and `/smol` is often beneficial:
- **Performance:** Large language models can sometimes experience performance degradation or lose focus when context windows become extremely full (e.g., over 50-75% capacity, depending on the model). Condensing or resetting context can help maintain optimal performance.
- **Relevance:** Summarizing or starting fresh ensures the most relevant information is prioritized in the context window.
- **Cost:** Reducing the number of tokens sent to the model in each turn can help manage costs, especially with more expensive models.
Using `/newtask` and `/smol` provides you with direct control over the conversation context, allowing for more efficient and effective interaction with Cline.
+68
View File
@@ -0,0 +1,68 @@
---
title: "For New Coders"
description: "Welcome to Cline, your AI-powered coding companion! This guide will help you quickly set up your development environment and begin your coding journey with ease."
---
> 💡 **Tip:** If you're completely new to coding, take your time with each step. There's no rush — Cline is here to guide you!
### 🚀 Getting Started
Before you jump into coding, make sure you have these essentials ready:
#### 1. **VS Code**
A popular, free, and powerful code editor.
- [Download VS Code](https://code.visualstudio.com/)
📺 **Recommended YouTube Tutorial:** [How to Install VS Code](https://www.youtube.com/watch?v=MlIzFUI1QGA)
> ✅ **Pro Tip:** Install VS Code in your Applications folder (macOS) or Program Files (Windows) for easy access from your dock or start menu.
#### 2. **Essential Development Tools**
Basic software required for coding efficiently:
- Homebrew (macOS)
- Node.js
- Git
👉 Follow our detailed guide on Installing Essential Development Tools with step-by-step help from Cline.
📺 **Recommended YouTube Tutorials:**
- **For macOS:**
- [Install Homebrew on Mac](https://www.youtube.com/watch?v=hwGNgVbqasc)
- [Install Git on MacOS 2024](https://www.youtube.com/watch?v=B4qsvQ5IqWk)
- [Install Node.js on Mac (M1 | M2 | M3)](https://www.youtube.com/watch?v=I8H4wolRFBk)
- **For Windows:**
- [Install Git on Windows 10/11 (2024)](https://www.youtube.com/watch?v=yjxv1HuRQy0)
- [Install Node.js in Windows 10/11](https://www.youtube.com/watch?v=uCgAuOYpJd0)
> ⚠️ **Note:** If you run into permission issues during installation, try running your terminal or command prompt as an administrator.
#### 3. **Organize Your Projects**
Create a dedicated folder named `Cline` in your Documents folder for all your coding projects:
- **macOS:** `/Users/[your-username]/Documents/Cline`
- **Windows:** `C:\Users\[your-username]\Documents\Cline`
Inside your `Cline` folder, structure projects clearly:
- `Documents/Cline/workout-app` _(e.g., for a fitness tracking app)_
- `Documents/Cline/portfolio-website` _(e.g., to showcase your work)_
> 💡 **Tip:** Keeping your projects organized from the start will save you time and confusion later!
#### 4. **Install the Cline VS Code Extension**
Enhance your coding workflow by installing the Cline extension directly within VS Code:
- Get Started with Cline Extension Tutorial
📺 **Recommended YouTube Tutorial:** [How To Install Extensions in VS Code](https://www.youtube.com/watch?v=E7trgwZa-mk)
> ✅ **Pro Tip:** After installing, reload VS Code to ensure the extension is activated properly.
🎉 You're all set! Dive in and start coding smarter and faster with **Cline**.
+81
View File
@@ -0,0 +1,81 @@
---
title: "Installing Cline"
description: "Cline is a VS Code extension that brings AI-powered coding assistance directly
to your editor. Install using one of these methods:"
---
### Installation Options
- **VS Code Marketplace (Recommended):** Fastest method for standard VS Code and Cursor users.
- **Open VSX Registry:** For VS Code-compatible editors like VSCodium.
### 🛠️ VS Code Marketplace: Step-by-Step Setup
Follow these steps to get Cline up and running:
1. **Open VS Code:** Launch the VS Code application.
> ⚠️ **Note:** If VS Code shows "Running extensions might...", click "Allow".
2. **Open Your Cline Folder:** In VS Code, open the Cline folder you created in Documents.
3. **Navigate to Extensions:** Click on the Extensions icon in the Activity Bar on the side of VS Code (`Ctrl + Shift + X` or `Cmd + Shift + X`).
4. **Search for 'Cline':** In the Extensions search bar, type `Cline`.
<Frame caption="VS Code marketplace with Cline extension ready to install">
<img src="/assets/robot_panel_dark.png" alt="VS Code marketplace showing Cline extension" />
</Frame>
1. **Install the Extension:** Click the "Install" button next to the Cline extension.
2. **Open Cline:**
- Click the Cline icon in the Activity Bar.
- Or, use the command palette (`Ctrl/Cmd + Shift + P`) and type "Cline: Open In New Tab" for a better view.
3. **Troubleshooting:** If you don't see the Cline icon, try restarting VS Code.
> ✅ **Pro Tip:** You should see the Cline chat window appear in your VS Code editor!
### 🌐 Open VSX Registry
For VS Code-compatible editors without Marketplace access (like VSCodium and Windsurf):
1. Open your editor.
2. Access the Extensions view.
3. Search for "Cline".
4. Select "Cline" by saoudrizwan and click **Install**.
5. Reload if prompted.
### 👤 Creating Your Cline Account
Now that you have Cline installed, let's get you set up with your account:
1. **Sign In to Cline:**
- Click the **Sign In** button in the Cline extension.
- You'll be taken to [app.cline.bot](https://app.cline.bot) to create your account.
2. **Start with Free Credits:**
- No credit card needed!
3. **Available AI Models:**
- Anthropic Claude 3.5-Sonnet (recommended for coding)
- DeepSeek Chat (cost-effective alternative)
- Google Gemini 2.0 Flash
- And more — all through your Cline account.
4. -
### 💻 Your First Interaction with Cline
You're ready to start building! Copy and paste this prompt into the Cline chat window:
```
Hey Cline! Could you help me create a new project folder called "hello-world" in my Cline directory and make a simple webpage that says "Hello World" in big blue text?
```
> ✅ **Pro Tip:** Cline will help you create the project folder and set up your first webpage!
### 🧩 Tips for Working with Cline
- **Ask Questions:** If you're unsure about something, ask Cline!
- **Use Screenshots:** Cline can understand images — show him what you're working on.
- **Copy and Paste Errors:** Share error messages in the chat for solutions.
- **Speak Plainly:** Use your own words — Cline will translate them into code.
### 🫂 Still Struggling?
Join our Discord community and engage with our team and other Cline users directly.
@@ -0,0 +1,111 @@
---
title: "Installing Dev Essentials"
description: >-
When you start coding, you'll need some essential development tools installed
on your computer. Cline can help you install everything you need in a safe,
guided way.
---
### 🧰 The Essential Tools
Here are the core tools you'll need for development:
- **Node.js & npm:** Required for JavaScript and web development
- **Git:** For tracking changes in your code and collaborating with others
- **Package Managers:** Tools that make it easy to install other development tools
- Homebrew for macOS
- Chocolatey for Windows
- apt/yum for Linux
> 💡 **Tip:** These tools are the foundation of your developer toolkit. Installing them properly will set you up for success!
### 🚀 Let Cline Install Everything
Copy one of these prompts based on your operating system and paste it into **Cline**:
#### For macOS
```
Hello Cline! I need help setting up my Mac for software development. Could you please help me install the essential development tools like Homebrew, Node.js, Git, and any other core utilities that are commonly needed for coding? I'd like you to guide me through the process step-by-step.
```
#### For Windows
```
Hello Cline! I need help setting up my Windows PC for software development. Could you please help me install the essential development tools like Node.js, Git, and any other core utilities that are commonly needed for coding? I'd like you to guide me through the process step-by-step.
```
#### For Linux
```
Hello Cline! I need help setting up my Linux system for software development. Could you please help me install the essential development tools like Node.js, Git, and any other core utilities that are commonly needed for coding? I'd like you to guide me through the process step-by-step.
```
> ✅ **Pro Tip:** Cline will show you each command before running it. You stay in control the entire time!
### 🔍 What Will Happen
Cline will guide you through the following steps:
1. Installing the appropriate package manager for your system
2. Using the package manager to install Node.js and Git
3. Showing you the exact command before it runs (you approve each step!)
4. Verifying each installation is successful
> ⚠️ **Note:** You might need to enter your computer's password for some installations. This is normal!
### 💡 Why These Tools Are Important
- **Node.js & npm:**
- Build websites with frameworks like React or Next.js
- Run JavaScript code
- Install JavaScript packages
- **Git:**
- Save different versions of your code
- Collaborate with other developers
- Back up your work
- **Package Managers:**
- Quickly install and update development tools
- Keep your environment organized and up to date
### 🧩 Notes
> 💡 **Tip:** The installation process is interactive — Cline will guide you step by step!
- All commands are shown to you for approval before they run.
- If you run into any issues, Cline will help troubleshoot them.
- You may need to enter your computer's password for certain steps.
### 🧑‍💻 Additional Tips for New Coders
#### Understanding the Terminal
The Terminal is an application where you can type commands to interact with your computer.
- **macOS:** Open it by searching for "Terminal" in Spotlight.
- **Example:**
```
$ open -a Terminal
```
#### Understanding VS Code Features
- **Terminal in VS Code:** Run commands directly from within VS Code!
- Go to **View > Terminal** or press \`Ctrl + \`\`.
- Example:
```
$ node -v
v16.14.0
```
- **Document View:** Where you edit your code files.
- Open files from the Explorer panel on the left.
- **Problems Section:** View errors or warnings in your code.
- Access it by clicking the lightbulb icon or **View > Problems**.
#### Common Features
- **Command Line Interface (CLI):** A powerful tool for running commands.
- **Permissions:** You might need to grant permissions to certain commands — this keeps your system secure.
@@ -0,0 +1,123 @@
---
title: "Model Selection Guide"
description: "Last updated: Feb 5, 2025."
---
## Understanding Context Windows
Think of a context window as your AI assistant's working memory - similar to RAM in a computer. It determines how much information the model can "remember" and process at once during your conversation. This includes:
- Your code files and conversations
- The assistant's responses
- Any documentation or additional context provided
Context windows are measured in tokens (roughly 3/4 of a word in English). Different models have different context window sizes:
- Claude 3.5 Sonnet: 200K tokens
- DeepSeek Models: 128K tokens
- Gemini Flash 2.0: 1M tokens
- Gemini 1.5 Pro: 2M tokens
When you reach the limit of your context window, older information needs to be removed to make room for new information - just like clearing RAM to run new programs. This is why sometimes AI assistants might seem to "forget" earlier parts of your conversation.
Cline helps you manage this limitation with its Context Window Progress Bar, which shows:
- Input tokens (what you've sent to the model)
- Output tokens (what the model has generated)
- A visual representation of how much of your context window you've used
- The total capacity for your chosen model
<Frame caption="Visual representation of the context window usage in Cline">
<img src="/assets/robot_panel_light.png" alt="Context window progress bar example" />
</Frame>
This visibility helps you work more effectively with Cline by letting you know when you might need to start fresh or break tasks into smaller chunks.
### Model Comparison
## LLM Model Comparison for Cline (Feb 2025)
| Model | Input Cost\* | Output Cost\* | Context Window | Best For |
| ----------------- | ------------ | ------------- | -------------- | ----------------------------------- |
| Claude 3.5 Sonnet | $3.00 | $15.00 | 200K | Best code implementation & tool use |
| DeepSeek R1 | $0.55 | $2.19 | 128K | Planning & reasoning champion |
| DeepSeek V3 | $0.14 | $0.28 | 128K | Value code implementation |
| o3-mini | $1.10 | $4.40 | 200K | Flexible use, strong planning |
| Gemini Flash 2.0 | $0.00 | $0.00 | 1M | Strong all-rounder |
| Gemini 1.5 Pro | $0.00 | $0.00 | 2M | Large context processing |
\*Costs per million tokens
### Top Picks for 2025
1. **Claude 3.5 Sonnet**
- Best overall code implementation
- Most reliable tool usage
- Expensive but worth it for critical code
2. **DeepSeek R1**
- Exceptional planning & reasoning
- Great value pricing
3. **o3-mini**
- Strong for planning with adjustable reasoning
- Three reasoning modes for different needs
- Requires OpenAI Tier 3 API access
- 200K context window
4. **DeepSeek V3**
- Reliable code implementation
- Great for daily coding
- Cost-effective for implementation
5. **Gemini Flash 2.0**
- Massive 1M context window
- Improved speed and performance
- Good all-around capabilities
### Best Models by Mode (Plan or Act)
#### Planning
1. **DeepSeek R1**
- Best reasoning capabilities in class
- Excellent at breaking down complex tasks
- Strong math/algorithm planning
- MoE architecture helps with reasoning
2. **o3-mini (high reasoning)**
- Three reasoning levels:
- High: Complex planning
- Medium: Daily tasks
- Low: Quick ideas
- 200K context helps with large projects
3. **Gemini Flash 2.0**
- Massive context window for complex planning
- Strong reasoning capabilities
- Good with multi-step tasks
#### Acting (coding)
1. **Claude 3.5 Sonnet**
- Best code quality
- Most reliable with Cline tools
- Worth the premium for critical code
2. **DeepSeek V3**
- Nearly Sonnet-level code quality
- Better API stability than R1
- Great for daily coding
- Strong tool usage
3. **Gemini 1.5 Pro**
- 2M context window
- Good with complex codebases
- Reliable API
- Strong multi-file understanding
### A Note on Local Models
While running models locally might seem appealing for cost savings, we currently don't recommend any local models for use with Cline. [Local models are significantly less reliable](https://docs.cline.bot/running-models-locally/read-me-first) at using Cline's essential tools and typically retain only 1-26% of the original model's capabilities. The full cloud version of DeepSeek-R1, for example, is 671B parameters - local versions are drastically simplified copies that struggle with complex tasks and tool usage. Even with high-end hardware (RTX 3070+, 32GB+ RAM), you'll experience slower responses, less reliable tool execution, and reduced capabilities. For the best development experience, we recommend sticking with the cloud models listed above.
### Key Takeaways
1. **Plan vs Act Matters**: Choose models based on task type
2. **Real Performance > Benchmarks**: Focus on actual Cline performance
3. **Mix & Match**: Use different models for planning and implementation
4. **Cost vs Quality**: Premium models worth it for critical code
5. **Keep Backups**: Have alternatives ready for API issues
_\*Note: Based on real usage patterns and community feedback rather than just benchmarks. Your experience may vary. This is not an exhaustive list of all the models available for use within Cline._
@@ -0,0 +1,238 @@
---
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/getting-started-new-coders/installing-dev-essentials)
2. Set up Cline's Memory Bank:
- Follow the [Memory Bank setup instructions](https://docs.cline.bot/improving-your-prompting-skills/custom-instructions-library/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
bashCopygit pull origin main # Download latest code
```
2. **During development**: Save work regularly
```bash
bashCopygit add .
git commit -m "Clear message about changes"
```
3. **End of day**: Share your progress
```bash
bashCopygit 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!
@@ -0,0 +1,156 @@
---
title: "Context Management"
description: "Context is key to getting the most out of Cline"
---
> 💡 **Quick Reference**
>
> - Context = The information Cline knows about your project
> - Context Window = How much information Cline can hold at once
> - Use context files to maintain project knowledge
> - Reset when the context window gets full
## Understanding Context & Context Windows
<Frame caption="In a world of infinite context, the context window is what Cline currently has available">
<img
src="/assets/robot_panel_dark.png"
alt="In a world of infinite context, the context window is what Cline currently has available"
/>
</Frame>
Think of working with Cline like collaborating with a thorough, proactive teammate:
### How Context is Built
Cline actively builds context in two ways:
1. **Automatic Context Gathering (i.e. Cline-driven)**
- Proactively reads related files
- Explores project structure
- Analyzes patterns and relationships
- Maps dependencies and imports
- Asks clarifying questions
2. **User-Guided Context**
- Share specific files
- Provide documentation
- Answer Cline's questions
- Guide focus areas
- Share design thoughts and requirements
💡 **Key Point**: Cline isn't passive - it actively seeks to understand your project. You can either let it explore or guide its focus, especially in [Plan](https://docs.cline.bot/exploring-clines-tools/plan-and-act-modes-a-guide-to-effective-ai-development) mode.
### Context & Context Windows
Think of context like a whiteboard you and Cline share:
- **Context** is all the information available:
- What Cline has discovered
- What you've shared
- Your conversation history
- Project requirements
- Previous decisions
- **Context Window** is the size of the whiteboard itself:
- Measured in tokens (1 token ≈ 3/4 of an English word)
- Each model has a fixed size:
- Claude 3.5 Sonnet: 200,000 tokens
- DeepSeek: 64,000 tokens
- When the whiteboard is full, you need to erase (clear context) to write more
- [How Cline manages context under the hood](https://cline.bot/blog/understanding-the-new-context-window-progress-bar-in-cline)
⚠️ **Important**: Having a large context window (like Claude's 200k tokens) doesn't mean you should fill it completely. Just like a cluttered whiteboard, too much information can make it harder to focus on what's important.
## Understanding the Context Window Progress Bar
Cline provides a visual way to monitor your context window usage through a progress bar:
<Frame caption="Visual representation of the context window usage">
<img src="/assets/robot_panel_light.png" alt="Context window progress bar" />
</Frame>
### Reading the Bar
- ↑ shows input tokens (what you've sent to the LLM)
- ↓ shows output tokens (what the LLM has generated)
- The progress bar visualizes how much of your context window you've used
- The total shows your model's maximum capacity (e.g., 200k for Claude 3.5-Sonnet)
### When to Watch the Bar
- During long coding sessions
- When working with multiple files
- Before starting complex tasks
- When Cline seems to lose context
💡 **Tip**: Consider starting a fresh session when usage reaches 70-80% to maintain optimal performance.
## Working with Context Files
Context files help maintain understanding across sessions. They serve as documentation specifically designed to help AI assistants understand your project.
#### Approaches to Context Files
1. **Evergreen Project Context (i.e.** [**Memory Bank**](https://docs.cline.bot/improving-your-prompting-skills/custom-instructions-library/cline-memory-bank)**)**
- Living documentation that evolves with your project
- Updated as architecture and patterns emerge
- Example: The Memory Bank pattern maintains files like `techContext.md` and `systemPatterns.md`
- Useful for long-running projects and teams
2. **Task-Specific Context (i.e.** [**Structured Approach**](https://cline.bot/blog/building-advanced-software-with-cline-a-structured-approach)**)**
- Created for specific implementation tasks
- Document requirements, constraints, and decisions
- Example:
```markdown
# auth-system-implementation.md
## Requirements
- OAuth2 implementation
- Support for Google and GitHub
- Rate limiting on auth endpoints
## Technical Decisions
- Using Passport.js for provider integration
- JWT for session management
- Redis for rate limiting
```
3. **Knowledge Transfer Docs**
- Switch to plan mode and ask Cline to document everything you've accomplished so far, along with the remaining steps, in a markdown file.
- Copy the contents of the markdown file.
- Start a new task using that content as context.
#### Using Context Files Effectively
1. **Structure and Format**
- Use clear, consistent organization
- Include relevant examples
- Link related concepts
- Keep information focused
2. **Maintenance**
- Update after significant changes
- Version control your context files
- Remove outdated information
- Document key decisions
## Practical Tips
1. **Starting New Projects**
- Let Cline explore the codebase
- Answer its questions about structure and patterns
- Consider setting up basic context files
- Document key design decisions
2. **Ongoing Development**
- Update context files with significant changes
- Share relevant documentation
- Use Plan mode for complex discussions
- Start fresh sessions when needed
3. **Team Projects**
- Share common context files (consider using [.clinerules](https://docs.cline.bot/improving-your-prompting-skills/prompting) files in project roots)
- Document architectural decisions
- Maintain consistent patterns
- Keep documentation current
Remember: The goal is to help Cline maintain consistent understanding of your project across sessions.
+8
View File
@@ -0,0 +1,8 @@
---
title: "What is Cline?"
description: "An introduction to Cline, your AI-powered development assistant in VS Code."
---
Cline is an AI development assistant which integrates with Microsoft Visual Studio Code. It provides an interface between your IDE and LLMs facilitating code development, increasing productivity and lowering the barrier to entry for new coders. Depending on permissions, Cline can read/write files, execute commands, use your web browser, and expand its capabilities with Model Context Protocol servers.
What makes Cline distinctive is its thoughtful approach to code generation and its extensive integration capabilities. Rather than simply generating code snippets, Cline collaborates with developers by planning solutions step-by-step, maintaining awareness of the entire development environment, and requiring explicit approval for all changes. It can understand large codebases, accelerate onboarding for new engineers, and connect with hundreds of tools through its Model Context Protocol Marketplace, enabling everything from streamlined project deployments to automated incident response—all through natural language commands.
+2
View File
@@ -19,6 +19,7 @@ const aliasResolverPlugin = {
"@services": path.resolve(__dirname, "src/services"),
"@shared": path.resolve(__dirname, "src/shared"),
"@utils": path.resolve(__dirname, "src/utils"),
"@packages": path.resolve(__dirname, "src/packages"),
}
// For each alias entry, create a resolver
@@ -124,6 +125,7 @@ const extensionConfig = {
define: {
"process.env.IS_DEV": JSON.stringify(!production),
},
tsconfig: path.resolve(__dirname, "tsconfig.json"),
plugins: [
copyWasmFiles,
aliasResolverPlugin,
+6 -2
View File
@@ -167,8 +167,12 @@ export class ExercismAdapter implements BenchmarkAdapter {
output += stdout + "\n"
} catch (error: any) {
success = false
if (error.stdout) output += error.stdout + "\n"
if (error.stderr) output += error.stderr + "\n"
if (error.stdout) {
output += error.stdout + "\n"
}
if (error.stderr) {
output += error.stderr + "\n"
}
}
}
-1
View File
@@ -3,7 +3,6 @@ import * as path from "path"
import * as fs from "fs"
import fetch from "node-fetch"
import * as os from "os"
import * as child_process from "child_process"
import { installRequiredExtensions, configureExtensionSettings } from "./extensions"
// Store temporary directories for cleanup
+25588 -405
View File
File diff suppressed because it is too large Load Diff
+7 -3
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.13.1",
"version": "3.14.0",
"icon": "assets/icons/icon.png",
"engines": {
"vscode": "^1.84.0"
@@ -292,7 +292,7 @@
"watch:tsc": "tsc --noEmit --watch --project tsconfig.json",
"package": "npm run build:webview && npm run check-types && npm run lint && node esbuild.js --production",
"protos": "node proto/build-proto.js && prettier src/shared/proto --write && prettier src/core/controller --write",
"compile-tests": "tsc -p ./tsconfig.test.json --outDir out",
"compile-tests": "node ./scripts/build-tests.js",
"watch-tests": "tsc -p . -w --outDir out",
"pretest": "npm run compile-tests && npm run compile && npm run lint",
"check-types": "tsc --noEmit",
@@ -312,7 +312,8 @@
"publish:marketplace:prerelease": "vsce publish --pre-release && ovsx publish --pre-release",
"prepare": "husky",
"changeset": "changeset",
"version-packages": "changeset version"
"version-packages": "changeset version",
"docs:preview": "cd docs && mintlify dev"
},
"devDependencies": {
"@changesets/cli": "^2.27.12",
@@ -336,7 +337,9 @@
"chalk": "^5.3.0",
"esbuild": "^0.25.0",
"eslint": "^8.57.0",
"grpc-tools": "^1.13.0",
"husky": "^9.1.7",
"mintlify": "^4.0.515",
"npm-run-all": "^4.1.5",
"prettier": "^3.3.3",
"protoc-gen-ts": "^0.8.7",
@@ -386,6 +389,7 @@
"jschardet": "^3.1.4",
"mammoth": "^1.8.0",
"monaco-vscode-textmate-theme-converter": "^0.1.7",
"node-cache": "^5.1.2",
"ollama": "^0.5.13",
"open-graph-scraper": "^6.9.0",
"openai": "^4.83.0",
+15
View File
@@ -0,0 +1,15 @@
syntax = "proto3";
package cline;
option java_package = "bot.cline.proto";
option java_multiple_files = true;
import "common.proto";
// Service for account-related operations
service AccountService {
// Handles the user clicking the login link in the UI.
// Generates a secure nonce for state validation, stores it in secrets,
// and opens the authentication URL in the external browser.
rpc accountLoginClicked(EmptyRequest) returns (String);
}
+27
View File
@@ -1,6 +1,8 @@
syntax = "proto3";
package cline;
option java_package = "bot.cline.proto";
option java_multiple_files = true;
import "common.proto";
@@ -8,6 +10,8 @@ service BrowserService {
rpc getBrowserConnectionInfo(EmptyRequest) returns (BrowserConnectionInfo);
rpc testBrowserConnection(StringRequest) returns (BrowserConnection);
rpc discoverBrowser(EmptyRequest) returns (BrowserConnection);
rpc getDetectedChromePath(EmptyRequest) returns (ChromePath);
rpc updateBrowserSettings(UpdateBrowserSettingsRequest) returns (Boolean);
}
message BrowserConnectionInfo {
@@ -21,3 +25,26 @@ message BrowserConnection {
string message = 2;
optional string endpoint = 3;
}
message ChromePath {
string path = 1;
bool is_bundled = 2;
}
message Viewport {
int32 width = 1;
int32 height = 2;
}
message BrowserSettings {
Viewport viewport = 1;
optional string remote_browser_host = 2;
optional bool remote_browser_enabled = 3;
}
message UpdateBrowserSettingsRequest {
Metadata metadata = 1;
Viewport viewport = 2;
optional string remote_browser_host = 3;
optional bool remote_browser_enabled = 4;
}
+16 -47
View File
@@ -2,59 +2,24 @@
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 { createRequire } from "module"
const require = createRequire(import.meta.url)
const protoc = path.join(require.resolve("grpc-tools"), "../bin/protoc")
const tsProtoPlugin = require.resolve("ts-proto/protoc-gen-ts_proto")
// Get script directory and root directory
const SCRIPT_DIR = path.dirname(new URL(import.meta.url).pathname)
const __filename = fileURLToPath(import.meta.url)
const SCRIPT_DIR = path.dirname(__filename)
const ROOT_DIR = path.resolve(SCRIPT_DIR, "..")
async function main() {
console.log(chalk.bold.blue("Starting Protocol Buffer code generation..."))
// Check if protoc is installed and has the correct version
try {
const protocOutput = execSync("protoc --version", { encoding: "utf8" }).trim()
console.log(chalk.cyan(`Found ${protocOutput}`))
const versionMatch = protocOutput.match(/libprotoc\s+(\d+\.\d+)/)
if (!versionMatch) {
console.warn(chalk.yellow("Warning: Could not determine protoc version. Continuing anyway..."))
} else {
const version = versionMatch[1]
const requiredVersion = "30.1"
if (version !== requiredVersion) {
console.warn(
chalk.yellow(`Warning: protoc version ${version} found, but version ${requiredVersion} is required.`),
)
console.warn(
chalk.yellow(
`To install the correct version, visit: https://github.com/protocolbuffers/protobuf/releases/tag/v${requiredVersion}`,
),
)
process.exit(0) // Exit with success as requested
}
}
} catch (error) {
console.warn(chalk.yellow("Warning: protoc is not installed. Skipping proto generation."))
console.warn(
chalk.yellow(
"To install Protocol Buffers compiler, visit: https://github.com/protocolbuffers/protobuf/releases/tag/v30.1",
),
)
process.exit(0) // Exit with success as requested
}
// Check if ts-proto plugin is available
const TS_PROTO_PLUGIN = path.join(ROOT_DIR, "node_modules", ".bin", "protoc-gen-ts_proto")
try {
await fs.access(TS_PROTO_PLUGIN)
} catch (error) {
console.error(chalk.red("Error: ts-proto plugin not found at"), TS_PROTO_PLUGIN)
console.error(chalk.red('Please run "npm install" to install the required dependencies.'))
process.exit(1)
}
// Define output directories
const TS_OUT_DIR = path.join(ROOT_DIR, "src", "shared", "proto")
@@ -70,15 +35,15 @@ async function main() {
// Process all proto files
console.log(chalk.cyan("Processing proto files from"), SCRIPT_DIR)
const protoFiles = await globby("**/*.proto", { cwd: SCRIPT_DIR })
const protoFiles = await globby("*.proto", { cwd: SCRIPT_DIR })
for (const protoFile of protoFiles) {
console.log(chalk.cyan(`Generating TypeScript code for ${protoFile}...`))
// Build the protoc command with proper path handling for cross-platform
const protocCommand = [
"protoc",
`--plugin=protoc-gen-ts_proto="${TS_PROTO_PLUGIN}"`,
protoc,
`--plugin=protoc-gen-ts_proto="${tsProtoPlugin}"`,
`--ts_proto_out="${TS_OUT_DIR}"`,
"--ts_proto_opt=outputServices=generic-definitions,env=node,esModuleInterop=true,useDate=false,useOptionals=messages",
`--proto_path="${SCRIPT_DIR}"`,
@@ -114,9 +79,13 @@ async function generateMethodRegistrations() {
console.log(chalk.cyan("Generating method registration files..."))
const serviceDirs = [
path.join(ROOT_DIR, "src", "core", "controller", "mcp"),
path.join(ROOT_DIR, "src", "core", "controller", "account"),
path.join(ROOT_DIR, "src", "core", "controller", "browser"),
path.join(ROOT_DIR, "src", "core", "controller", "checkpoints"),
path.join(ROOT_DIR, "src", "core", "controller", "file"),
path.join(ROOT_DIR, "src", "core", "controller", "mcp"),
path.join(ROOT_DIR, "src", "core", "controller", "task"),
path.join(ROOT_DIR, "src", "core", "controller", "web-content"),
// Add more service directories here as needed
]
+9
View File
@@ -1,10 +1,19 @@
syntax = "proto3";
package cline;
option java_package = "bot.cline.proto";
option java_multiple_files = true;
import "common.proto";
service CheckpointsService {
rpc checkpointDiff(Int64Request) returns (Empty);
rpc checkpointRestore(CheckpointRestoreRequest) returns (Empty);
}
message CheckpointRestoreRequest {
Metadata metadata = 1;
int64 number = 2;
string restore_type = 3;
optional int64 offset = 4;
}
+11
View File
@@ -1,6 +1,8 @@
syntax = "proto3";
package cline;
option java_package = "bot.cline.proto";
option java_multiple_files = true;
message Metadata {
}
@@ -38,3 +40,12 @@ message BytesRequest {
message Bytes {
bytes value = 1;
}
message BooleanRequest {
Metadata metadata = 1;
bool value = 2;
}
message Boolean {
bool value = 1;
}
+55
View File
@@ -0,0 +1,55 @@
syntax = "proto3";
package cline;
option java_package = "bot.cline.proto";
option java_multiple_files = true;
import "common.proto";
// Service for file-related operations
service FileService {
// Opens a file in the editor
rpc openFile(StringRequest) returns (Empty);
// Opens an image in the system viewer
rpc openImage(StringRequest) returns (Empty);
// Deletes a rule file from either global or workspace rules directory
rpc deleteRuleFile(RuleFileRequest) returns (RuleFile);
// Creates a rule file from either global or workspace rules directory
rpc createRuleFile(RuleFileRequest) returns (RuleFile);
// Search git commits in the workspace
rpc searchCommits(StringRequest) returns (GitCommits);
}
// Response for searchCommits
message GitCommits {
repeated GitCommit commits = 1;
}
// Represents a Git commit
message GitCommit {
string hash = 1;
string short_hash = 2;
string subject = 3;
string author = 4;
string date = 5;
}
// Unified request for all rule file operations
message RuleFileRequest {
Metadata metadata = 1;
bool is_global = 2; // Common field for all operations
optional string rule_path = 3; // Path field for deleteRuleFile (optional)
optional string filename = 4; // Filename field for createRuleFile (optional)
}
// Result for rule file operations with meaningful data only
message RuleFile {
string file_path = 1; // Path to the rule file
string display_name = 2; // Filename for display purposes
bool already_exists = 3; // For createRuleFile, indicates if file already existed
}
+22 -6
View File
@@ -1,11 +1,33 @@
syntax = "proto3";
package cline;
option java_package = "bot.cline.proto";
option java_multiple_files = true;
import "common.proto";
service McpService {
rpc toggleMcpServer(ToggleMcpServerRequest) returns (McpServers);
rpc updateMcpTimeout(UpdateMcpTimeoutRequest) returns (McpServers);
rpc addRemoteMcpServer(AddRemoteMcpServerRequest) returns (McpServers);
}
message ToggleMcpServerRequest {
Metadata metadata = 1;
string server_name = 2;
bool disabled = 3;
}
message UpdateMcpTimeoutRequest {
Metadata metadata = 1;
string server_name = 2;
int32 timeout = 3;
}
message AddRemoteMcpServerRequest {
Metadata metadata = 1;
string server_name = 2;
string server_url = 3;
}
message McpTool {
@@ -49,12 +71,6 @@ message McpServer {
optional int32 timeout = 9;
}
message ToggleMcpServerRequest {
Metadata metadata = 1;
string server_name = 2;
bool disabled = 3;
}
message McpServers {
repeated McpServer mcp_servers = 1;
}
+23
View File
@@ -0,0 +1,23 @@
syntax = "proto3";
package cline;
option java_package = "bot.cline.proto";
option java_multiple_files = true;
import "common.proto";
service TaskService {
// Cancels the currently running task
rpc cancelTask(EmptyRequest) returns (Empty);
// Clears the current task
rpc clearTask(EmptyRequest) returns (Empty);
// Creates a new task with the given text and optional images
rpc newTask(NewTaskRequest) returns (Empty);
}
// Request message for creating a new task
message NewTaskRequest {
Metadata metadata = 1;
string text = 2;
repeated string images = 3;
}
+16
View File
@@ -0,0 +1,16 @@
syntax = "proto3";
package cline;
option java_package = "bot.cline.proto";
option java_multiple_files = true;
import "common.proto";
service WebContentService {
rpc checkIsImageUrl(StringRequest) returns (IsImageUrl);
}
message IsImageUrl {
bool is_image = 1;
string url = 2;
}
+61
View File
@@ -0,0 +1,61 @@
const { execSync } = require("child_process")
const esbuild = require("esbuild")
const watch = process.argv.includes("--watch")
/**
* @type {import('esbuild').Plugin}
*/
const esbuildProblemMatcherPlugin = {
name: "esbuild-problem-matcher",
setup(build) {
build.onStart(() => {
console.log("[watch] build started")
})
build.onEnd((result) => {
result.errors.forEach(({ text, location }) => {
console.error(`✘ [ERROR] ${text}`)
console.error(` ${location.file}:${location.line}:${location.column}:`)
})
console.log("[watch] build finished")
})
},
}
const srcConfig = {
bundle: true,
minify: false,
sourcemap: true,
sourcesContent: true,
logLevel: "silent",
entryPoints: ["src/packages/**/*.ts"],
outdir: "out/packages",
format: "cjs",
platform: "node",
define: {
"process.env.IS_DEV": "true",
"process.env.IS_TEST": "true",
},
external: ["vscode"],
plugins: [esbuildProblemMatcherPlugin],
}
async function main() {
const srcCtx = await esbuild.context(srcConfig)
if (watch) {
await srcCtx.watch()
} else {
await srcCtx.rebuild()
await srcCtx.dispose()
}
}
execSync("tsc -p ./tsconfig.test.json --outDir out", { encoding: "utf-8" })
main().catch((e) => {
console.error(e)
process.exit(1)
})
+24 -7
View File
@@ -28,20 +28,26 @@ export class AwsBedrockHandler implements ApiHandler {
const modelId = await this.getModelId()
const model = this.getModel()
// This baseModelId is used to indicate the capabilities of the model.
// If the user selects a custom model, baseModelId will be set to the base model ID of the custom model.
// Otherwise, baseModelId will be the same as modelId.
const baseModelId =
(this.options.awsBedrockCustomSelected ? this.options.awsBedrockCustomModelBaseId : modelId) || modelId
// Check if this is an Amazon Nova model
if (modelId.includes("amazon.nova")) {
if (baseModelId.includes("amazon.nova")) {
yield* this.createNovaMessage(systemPrompt, messages, modelId, model)
return
}
// Check if this is a Deepseek model
if (modelId.includes("deepseek")) {
if (baseModelId.includes("deepseek")) {
yield* this.createDeepseekMessage(systemPrompt, messages, modelId, model)
return
}
const budget_tokens = this.options.thinkingBudgetTokens || 0
const reasoningOn = modelId.includes("3-7") && budget_tokens !== 0 ? true : false
const reasoningOn = baseModelId.includes("3-7") && budget_tokens !== 0 ? true : false
// Get model info and message indices for caching
const userMsgIndices = messages.reduce((acc, msg, index) => (msg.role === "user" ? [...acc, index] : acc), [] as number[])
@@ -167,12 +173,23 @@ export class AwsBedrockHandler implements ApiHandler {
}
}
getModel(): { id: BedrockModelId; info: ModelInfo } {
getModel(): { id: string; info: ModelInfo } {
const modelId = this.options.apiModelId
if (modelId && modelId in bedrockModels) {
const id = modelId as BedrockModelId
return { id, info: bedrockModels[id] }
}
const customSelected = this.options.awsBedrockCustomSelected
const baseModel = this.options.awsBedrockCustomModelBaseId
if (customSelected && modelId && baseModel && baseModel in bedrockModels) {
// Use the user-input model ID but inherit capabilities from the base model
return {
id: modelId,
info: bedrockModels[baseModel],
}
}
return {
id: bedrockDefaultModelId,
info: bedrockModels[bedrockDefaultModelId],
@@ -290,7 +307,7 @@ export class AwsBedrockHandler implements ApiHandler {
systemPrompt: string,
messages: Anthropic.Messages.MessageParam[],
modelId: string,
model: { id: BedrockModelId; info: ModelInfo },
model: { id: string; info: ModelInfo },
): ApiStream {
// Get Bedrock client with proper credentials
const client = await this.getBedrockClient()
@@ -476,13 +493,13 @@ export class AwsBedrockHandler implements ApiHandler {
/**
* Creates a message using Amazon Nova models through AWS Bedrock
* Implements support for Nova Micro, Nova Lite, and Nova Pro models
* Implements support for Amazon Nova models
*/
private async *createNovaMessage(
systemPrompt: string,
messages: Anthropic.Messages.MessageParam[],
modelId: string,
model: { id: BedrockModelId; info: ModelInfo },
model: { id: string; info: ModelInfo },
): ApiStream {
// Get Bedrock client with proper credentials
const client = await this.getBedrockClient()
+5
View File
@@ -74,6 +74,8 @@ export class ClineHandler implements ApiHandler {
if (!didOutputUsage && chunk.usage) {
yield {
type: "usage",
cacheWriteTokens: 0,
cacheReadTokens: chunk.usage.prompt_tokens_details?.cached_tokens || 0,
inputTokens: chunk.usage.prompt_tokens || 0,
outputTokens: chunk.usage.completion_tokens || 0,
// @ts-ignore-next-line
@@ -105,6 +107,9 @@ export class ClineHandler implements ApiHandler {
const generation = response.data
return {
type: "usage",
// at this time there's no support for gatting cached_tokens from generation endpoint
cacheWriteTokens: 0,
cacheReadTokens: 0,
inputTokens: generation?.native_tokens_prompt || 0,
outputTokens: generation?.native_tokens_completion || 0,
totalCost: generation?.total_cost || 0,
+532 -41
View File
@@ -1,76 +1,193 @@
import type { Anthropic } from "@anthropic-ai/sdk"
// Restore GenerateContentConfig import and add GenerateContentResponseUsageMetadata
import {
GoogleGenAI,
type GenerationConfig,
type Content,
type GenerateContentConfig,
type GenerateContentResponseUsageMetadata,
} from "@google/genai"
import { GoogleGenAI, type Content, type GenerateContentConfig, type GenerateContentResponseUsageMetadata } from "@google/genai"
import NodeCache from "node-cache"
import { withRetry } from "../retry"
import { ApiHandler } from "../"
import { ApiHandlerOptions, geminiDefaultModelId, GeminiModelId, geminiModels, ModelInfo } from "@shared/api"
import { convertAnthropicMessageToGemini } from "../transform/gemini-format"
import { ApiStream } from "../transform/stream"
// Define a default TTL for the cache (e.g., 15 minutes in seconds)
const DEFAULT_CACHE_TTL_SECONDS = 900
interface GeminiHandlerOptions extends ApiHandlerOptions {
isVertex?: boolean
}
/**
* Handler for Google's Gemini API with optimized caching strategy and accurate cost accounting.
*
* Key features:
* - One cache per task: Creates a single cache per task and reuses it for subsequent turns
* - Stable cache keys: Uses taskId as a stable identifier for caches
* - Efficient cache updates: Only updates caches when there's new content to add
* - Split cost accounting: Separates immediate costs from ongoing cache storage costs
*
* Cost accounting approach:
* - Immediate costs (per message): Input tokens, output tokens, and cache read costs
* - Ongoing costs (per task): Cache storage costs for the TTL period
*
* Gemini's caching system is unique in that it charges for holding tokens in cache by the hour.
* This implementation optimizes for both performance and cost by:
* 1. Minimizing redundant cache creations
* 2. Properly accounting for cache costs in the billing calculations
* 3. Using a stable cache key to ensure cache reuse across turns
* 4. Separating immediate costs from ongoing costs to avoid double-counting
*/
export class GeminiHandler implements ApiHandler {
private options: ApiHandlerOptions
private client: GoogleGenAI // Updated client type
private client: GoogleGenAI
constructor(options: ApiHandlerOptions) {
if (!options.geminiApiKey) {
throw new Error("API key is required for Google Gemini")
}
// Enhanced caching system
private contentCaches: NodeCache // Stores cache details (key, count, etc.)
private isCacheBusy = false
private taskCacheNames: Map<string, string> = new Map() // Maps taskId to cache name for stable lookup
private taskCacheTokens: Map<string, number> = new Map() // Maps taskId to total tokens in cache
constructor(options: GeminiHandlerOptions) {
// Store the options
this.options = options
// Updated client initialization
this.client = new GoogleGenAI({ apiKey: options.geminiApiKey })
if (options.isVertex) {
// Initialize with Vertex AI configuration
const project = this.options.vertexProjectId ?? "not-provided"
const location = this.options.vertexRegion ?? "not-provided"
this.client = new GoogleGenAI({
vertexai: true,
project,
location,
})
} else {
// Initialize with standard API key
if (!options.geminiApiKey) {
throw new Error("API key is required for Google Gemini when not using Vertex AI")
}
this.client = new GoogleGenAI({ apiKey: options.geminiApiKey })
}
// Initialize cache with TTL and check period
this.contentCaches = new NodeCache({
stdTTL: DEFAULT_CACHE_TTL_SECONDS,
checkperiod: DEFAULT_CACHE_TTL_SECONDS,
})
}
/**
* Creates a message using the Gemini API with optimized caching and split cost accounting.
*
* This method implements a task-based caching strategy:
* 1. Each task gets its own cache, identified by taskId
* 2. On first call for a task, a new cache is created
* 3. On subsequent calls, the existing cache is reused and only new messages are sent
* 4. Cache operations are tracked for accurate cost accounting
*
* Cost accounting:
* - Immediate costs (returned in the usage object): Input tokens, output tokens, cache read costs
* - Ongoing costs (tracked at task level): Cache storage costs for the TTL period
*
* @param systemPrompt The system prompt to use for the message
* @param messages The conversation history to include in the message
* @returns An async generator that yields chunks of the response with accurate immediate costs
*/
@withRetry()
async *createMessage(systemPrompt: string, messages: Anthropic.Messages.MessageParam[]): ApiStream {
const { id: modelId, info: modelInfo } = this.getModel()
const { id: model, info } = this.getModel()
const contents = messages.map(convertAnthropicMessageToGemini)
// Re-implement thinking budget logic based on new SDK structure
const thinkingBudget = this.options.thinkingBudgetTokens ?? 0
const maxBudget = modelInfo.thinkingConfig?.maxBudget ?? 0
// port add baseUrl configuration for gemini api requests (#2843)
const httpOptions = this.options.geminiBaseUrl ? { baseUrl: this.options.geminiBaseUrl } : undefined
// Base generation config - Restore type and systemInstruction
const generationConfig: GenerateContentConfig = {
httpOptions,
temperature: 0, // Default temperature
systemInstruction: systemPrompt, // System prompt belongs here
// Ensure we have a stable cache key (taskId)
if (!this.options.taskId) {
console.warn("[GeminiHandler] No taskId provided, caching will be disabled")
}
// Convert messages to the format expected by @google/genai
// Note: convertAnthropicMessageToGemini might need adjustments
const contents: Content[] = messages.map(convertAnthropicMessageToGemini)
const taskId = this.options.taskId
// Construct the main request config - Type as GenerateContentConfig
// Calculate total content length for cache eligibility check
const contentsLength = systemPrompt.length + this.getMessagesLength(contents)
// Minimum token threshold for caching (approx 4096 tokens)
const CONTEXT_CACHE_TOKEN_MINIMUM = 4096
let uncachedContent: Content[] | undefined = undefined
let cachedContent: string | undefined = undefined
// Check if caching is available and content is large enough to benefit from caching
// We only enable caching for conversations above a certain size to avoid overhead for small requests
const isCacheAvailable = info.supportsPromptCache && contentsLength > 4 * CONTEXT_CACHE_TOKEN_MINIMUM && taskId
// This flag tracks whether this operation involves a cache write/update
// It's used to track task-level ongoing costs, not immediate costs
let cacheWrite = false
if (isCacheAvailable) {
// Check if we already have a cache for this task
const existingCacheName = this.taskCacheNames.get(taskId)
const cacheEntry = existingCacheName ? this.contentCaches.get<{ key: string; count: number }>(taskId) : undefined
if (cacheEntry) {
// Use existing cache
uncachedContent = contents.slice(cacheEntry.count, contents.length)
cachedContent = cacheEntry.key
console.log(
`[GeminiHandler] using existing cache for task ${taskId}: ${cacheEntry.count} cached messages (${cacheEntry.key}) and ${uncachedContent.length} uncached messages`,
)
}
// Create or update cache only if there's new content to add
const shouldUpdateCache = !existingCacheName || (cacheEntry && uncachedContent && uncachedContent.length > 0)
if (shouldUpdateCache) {
// If we should update the cache, then there will be a cache write
cacheWrite = true
}
}
const isCacheUsed = !!cachedContent
// Configure thinking budget if supported
const thinkingBudget = this.options.thinkingBudgetTokens ?? 0
const maxBudget = info.thinkingConfig?.maxBudget ?? 0
// Set up base generation config
const requestConfig: GenerateContentConfig = {
...generationConfig,
// Add base URL if configured
httpOptions: this.options.geminiBaseUrl ? { baseUrl: this.options.geminiBaseUrl } : undefined,
// Only include systemInstruction if NOT using the cache
...(isCacheUsed ? {} : { systemInstruction: systemPrompt }),
// Set temperature (default to 0)
temperature: 0,
}
// Add thinking config if the model supports it
if (modelInfo.thinkingConfig?.outputPrice !== undefined && maxBudget > 0) {
if (info.thinkingConfig?.outputPrice !== undefined && maxBudget > 0) {
requestConfig.thinkingConfig = {
thinkingBudget: thinkingBudget,
}
}
// Generate content using the new SDK structure via client.models
// Generate content using the configured parameters
const result = await this.client.models.generateContentStream({
model: modelId, // Pass model ID directly
contents,
config: requestConfig, // Pass the combined config (which includes systemInstruction)
model,
contents: uncachedContent ?? contents,
config: {
...requestConfig,
...(isCacheUsed ? { cachedContent } : {}),
},
})
// Declare variable to hold the last usage metadata found
// Update the cache after the LLM request is already sent to avoid blocking
// We only update the cache if we have a taskId and the cache write flag is set
// This is a non-blocking operation and will not affect the response time
if (cacheWrite && taskId) {
this.updateCacheContent(taskId, model, contents, systemPrompt)
}
// Track usage metadata
let lastUsageMetadata: GenerateContentResponseUsageMetadata | undefined
// Iterate directly over the stream
// Process the stream
for await (const chunk of result) {
if (chunk.text) {
yield {
@@ -78,20 +195,337 @@ export class GeminiHandler implements ApiHandler {
text: chunk.text,
}
}
if (chunk.usageMetadata) {
lastUsageMetadata = chunk.usageMetadata
}
}
// Yield usage information at the end
if (lastUsageMetadata) {
const inputTokens = lastUsageMetadata.promptTokenCount ?? 0
const outputTokens = lastUsageMetadata.candidatesTokenCount ?? 0
const cacheReadTokens = lastUsageMetadata.cachedContentTokenCount
// Calculate immediate costs only (excluding cache write/storage costs)
const totalCost = this.calculateCost({
info,
inputTokens,
outputTokens,
cacheReadTokens,
})
// Store the token count for task-level ongoing cost tracking
// This is not included in the immediate costs returned to the user
const cacheWriteTokens = cacheWrite ? inputTokens : undefined
// If this is a cache write operation, update the task's ongoing costs
if (cacheWrite && this.options.taskId && inputTokens > 0) {
// Log the ongoing costs for debugging
const ongoingCosts = this.getTaskOngoingCosts(this.options.taskId)
console.log(
`[GeminiHandler] Task ${this.options.taskId} ongoing costs: $${ongoingCosts?.toFixed(6) ?? "unknown"}`,
)
}
yield {
type: "usage",
inputTokens: lastUsageMetadata.promptTokenCount ?? 0,
outputTokens: lastUsageMetadata.candidatesTokenCount ?? 0,
inputTokens,
outputTokens,
cacheReadTokens,
cacheWriteTokens,
totalCost,
}
}
}
/**
* Lists all caches for the current API key.
*
* According to the Gemini API documentation, you can retrieve metadata for all uploaded caches
* using the caches.list() method. This is useful for monitoring cache usage and cleanup.
*
* @param pageSize Optional number of caches to return per page (default: 10)
* @returns A promise that resolves to an array of cache metadata objects
*/
public async listCaches(pageSize: number = 10): Promise<any[]> {
try {
const caches: any[] = []
const pager = await this.client.caches.list({ config: { pageSize } })
let page = pager.page
while (true) {
for (const cache of page) {
caches.push(cache)
}
if (!pager.hasNextPage()) {
break
}
page = await pager.nextPage()
}
return caches
} catch (error) {
console.error(`[GeminiHandler] Failed to list caches:`, error)
return []
}
}
/**
* Updates the content of a cache for a specific task.
*
* Since the Gemini API doesn't support incremental updates to cache content,
* this method:
* 1. Creates a new cache with the full content (old + new)
* 2. Deletes the old cache if it exists
* 3. Updates our local tracking to point to the new cache
*
* @param taskId The ID of the task whose cache should be updated
* @param model The model to use for the cache
* @param contents The full content to cache (including both old and new messages)
* @param systemInstruction The system instruction to include in the cache
*/
private async updateCacheContent(
taskId: string,
model: string,
contents: Content[],
systemInstruction: string,
): Promise<void> {
if (this.isCacheBusy) {
console.log(`[GeminiHandler] Cache is busy, skipping update for task ${taskId}`)
return
}
this.isCacheBusy = true
const timestamp = Date.now()
const existingCacheName = this.taskCacheNames.get(taskId)
try {
// 1. Create a new cache with the full content
const result = await this.client.caches.create({
model,
config: {
contents,
systemInstruction,
ttl: `${DEFAULT_CACHE_TTL_SECONDS}s`,
httpOptions: { timeout: 120_000 },
},
})
const { name, usageMetadata } = result
if (name) {
// 2. Delete the old cache if it exists (non-blocking)
// We don't await this operation to avoid blocking the main flow if deletion fails
if (existingCacheName) {
// Schedule cache deletion in the background
setTimeout(() => {
this.client.caches
.delete({ name: existingCacheName })
.then(() => {
console.log(`[GeminiHandler] Deleted old cache ${existingCacheName} for task ${taskId}`)
})
.catch((error) => {
console.error(`[GeminiHandler] Failed to delete old cache ${existingCacheName}:`, error)
console.log(`[GeminiHandler] Continuing without deleting old cache. It will expire after TTL.`)
})
}, 1000)
}
// 3. Update our local tracking
this.contentCaches.set<{ key: string; count: number }>(taskId, {
key: name,
count: contents.length,
})
this.taskCacheNames.set(taskId, name)
// Track total tokens in cache for ongoing cost calculation
const totalTokens = usageMetadata?.totalTokenCount ?? 0
this.taskCacheTokens.set(taskId, totalTokens)
const operation = existingCacheName ? "Updated" : "Created new"
console.log(
`[GeminiHandler] ${operation} cache for task ${taskId}: ${contents.length} messages (${totalTokens} tokens) in ${Date.now() - timestamp}ms`,
)
return // Indicate that a cache write occurred
}
return
} catch (error) {
console.error(`[GeminiHandler] Failed to update cache for task ${taskId}:`, error)
return
} finally {
this.isCacheBusy = false
}
}
/**
* Updates the TTL of an existing cache.
*
* According to the Gemini API documentation, you can update the TTL of a cache
* using the caches.update() method. This is useful for extending the lifetime
* of a cache that's still being used.
*
* @param taskId The ID of the task whose cache TTL should be updated
* @param ttlSeconds The new TTL in seconds
* @returns A promise that resolves to the updated cache, or undefined if the update fails
*/
public async updateCacheTTL(taskId: string, ttlSeconds: number = DEFAULT_CACHE_TTL_SECONDS): Promise<any> {
const cacheName = this.taskCacheNames.get(taskId)
if (!cacheName) {
console.warn(`[GeminiHandler] No cache found for task ${taskId}, cannot update TTL`)
return
}
try {
const updatedCache = await this.client.caches.update({
name: cacheName,
config: { ttl: `${ttlSeconds}s` },
})
console.log(`[GeminiHandler] Updated TTL for cache ${cacheName} to ${ttlSeconds}s`)
return updatedCache
} catch (error) {
console.error(`[GeminiHandler] Failed to update TTL for cache ${cacheName}:`, error)
}
}
/**
* Calculate the ongoing costs for a task based on cache storage.
*
* This method calculates the cost of holding tokens in cache for the TTL period.
* These costs are separate from the immediate costs of API calls and should be
* tracked at the task level rather than the message level.
*
* TODO: Surface these ongoing costs to the user in the UI, possibly in:
* - The task header/summary
* - A dedicated "costs" panel or tooltip
* - As part of the total cost calculation for the task
*
* @param taskId The ID of the task to calculate ongoing costs for
* @returns The ongoing cost in dollars, or undefined if no cache exists for the task
*/
public getTaskOngoingCosts(taskId: string): number | undefined {
const tokens = this.taskCacheTokens.get(taskId)
if (!tokens) {
return undefined
}
const { info } = this.getModel()
if (!info.cacheWritesPrice) {
return undefined
}
// Calculate the cost of holding tokens in cache for the TTL period
// (tokens / 1M) * (price per 1M tokens) * (cache TTL in hours)
return info.cacheWritesPrice * (tokens / 1_000_000) * (DEFAULT_CACHE_TTL_SECONDS / 3600)
}
/**
* Calculate the immediate dollar cost of the API call based on token usage and model pricing.
*
* This method accounts for the immediate costs of the API call:
* - Input token costs (for uncached tokens)
* - Output token costs
* - Cache read costs
*
* It does NOT include ongoing costs like cache storage, which are tracked separately
* at the task level through getTaskOngoingCosts().
*/
public calculateCost({
info,
inputTokens,
outputTokens,
cacheWriteTokens = 0,
cacheReadTokens = 0,
}: {
info: ModelInfo
inputTokens: number
outputTokens: number
cacheWriteTokens?: number
cacheReadTokens?: number
}) {
// Exit early if any required pricing information is missing
if (!info.inputPrice || !info.outputPrice) {
return undefined
}
let inputPrice = info.inputPrice
let outputPrice = info.outputPrice
let cacheWritesPrice = info.cacheWritesPrice ?? 0
// Right now, we only show the immediate costs of caching and not the ongoing costs of storing the cache
cacheWritesPrice = 0
let cacheReadsPrice = info.cacheReadsPrice ?? 0
// If there's tiered pricing then adjust prices based on the input tokens used
if (info.tiers) {
const tier = info.tiers.find((tier) => inputTokens <= tier.contextWindow)
if (tier) {
inputPrice = tier.inputPrice ?? inputPrice
outputPrice = tier.outputPrice ?? outputPrice
cacheWritesPrice = tier.cacheWritesPrice ?? cacheWritesPrice
cacheReadsPrice = tier.cacheReadsPrice ?? cacheReadsPrice
}
}
// Subtract the cached input tokens from the total input tokens
const uncachedInputTokens = inputTokens - (cacheReadTokens ?? 0)
// Calculate immediate costs only
// 1. Input token costs (for uncached tokens)
const inputTokensCost = inputPrice * (uncachedInputTokens / 1_000_000)
// 2. Output token costs
const outputTokensCost = outputPrice * (outputTokens / 1_000_000)
// 3. Cache read costs (immediate)
const cacheReadCost = (cacheReadTokens ?? 0) > 0 ? cacheReadsPrice * ((cacheReadTokens ?? 0) / 1_000_000) : 0
// Calculate total immediate cost (excluding cache write/storage costs)
const totalCost = inputTokensCost + outputTokensCost + cacheReadCost
// Create the trace object for debugging
const trace: Record<string, { price: number; tokens: number; cost: number }> = {
input: { price: inputPrice, tokens: uncachedInputTokens, cost: inputTokensCost },
output: { price: outputPrice, tokens: outputTokens, cost: outputTokensCost },
}
// Only include cache read costs in the trace (cache write costs are tracked separately)
if ((cacheReadTokens ?? 0) > 0) {
trace.cacheRead = { price: cacheReadsPrice, tokens: cacheReadTokens ?? 0, cost: cacheReadCost }
}
// console.log(`[GeminiHandler] calculateCost -> ${totalCost}`, trace)
return totalCost
}
/**
* Calculate the total length of all messages for cache eligibility check
*/
private getMessagesLength(contents: Content[]): number {
return contents.reduce((total, content) => {
if (!content.parts) {
return total
}
return (
total +
content.parts.reduce((partTotal, part) => {
if (typeof part.text === "string") {
return partTotal + part.text.length
}
return partTotal
}, 0)
)
}, 0)
}
/**
* Get the model ID and info for the current configuration
*/
getModel(): { id: GeminiModelId; info: ModelInfo } {
const modelId = this.options.apiModelId
if (modelId && modelId in geminiModels) {
@@ -103,4 +537,61 @@ export class GeminiHandler implements ApiHandler {
info: geminiModels[geminiDefaultModelId],
}
}
/**
* Count tokens in content using the Gemini API
*/
async countTokens(content: Array<any>): Promise<number> {
try {
const { id: model } = this.getModel()
// Convert content to Gemini format
const geminiContent = content.map((block) => {
if (typeof block === "string") {
return { text: block }
}
return { text: JSON.stringify(block) }
})
// Use Gemini's token counting API
const response = await this.client.models.countTokens({
model,
contents: [{ parts: geminiContent }],
})
if (response.totalTokens === undefined) {
console.warn("Gemini token counting returned undefined, using fallback")
return this.estimateTokens(content)
}
return response.totalTokens
} catch (error) {
console.warn("Gemini token counting failed, using fallback", error)
return this.estimateTokens(content)
}
}
/**
* Fallback token estimation method
*/
private estimateTokens(content: Array<any>): number {
// Simple estimation: ~4 characters per token
const totalChars = content.reduce((total, block) => {
if (typeof block === "string") {
return total + block.length
} else if (block && typeof block === "object") {
// Safely stringify the object
try {
const jsonStr = JSON.stringify(block)
return total + jsonStr.length
} catch (e) {
console.warn("Failed to stringify block for token estimation", e)
return total
}
}
return total
}, 0)
return Math.ceil(totalChars / 4)
}
}
+4 -2
View File
@@ -21,8 +21,9 @@ export class OllamaHandler implements ApiHandler {
try {
// Create a promise that rejects after timeout
const timeoutMs = this.options.requestTimeoutMs || 30000
const timeoutPromise = new Promise<never>((_, reject) => {
setTimeout(() => reject(new Error("Ollama request timed out after 120 seconds")), 120000)
setTimeout(() => reject(new Error(`Ollama request timed out after ${timeoutMs / 1000} seconds`)), timeoutMs)
})
// Create the actual API request promise
@@ -63,7 +64,8 @@ export class OllamaHandler implements ApiHandler {
} catch (error: any) {
// Check if it's a timeout error
if (error.message && error.message.includes("timed out")) {
throw new Error("Ollama request timed out after 120 seconds")
const timeoutMs = this.options.requestTimeoutMs || 30000
throw new Error(`Ollama request timed out after ${timeoutMs / 1000} seconds`)
}
// Enhance error reporting
+5 -2
View File
@@ -76,6 +76,8 @@ export class OpenRouterHandler implements ApiHandler {
if (!didOutputUsage && chunk.usage) {
yield {
type: "usage",
cacheWriteTokens: 0,
cacheReadTokens: chunk.usage.prompt_tokens_details?.cached_tokens || 0,
inputTokens: chunk.usage.prompt_tokens || 0,
outputTokens: chunk.usage.completion_tokens || 0,
// @ts-ignore-next-line
@@ -103,8 +105,9 @@ export class OpenRouterHandler implements ApiHandler {
// console.log("OpenRouter generation details:", generation)
return {
type: "usage",
// cacheWriteTokens: 0,
// cacheReadTokens: 0,
// at this time there's no support for gatting cached_tokens from generation endpoint
cacheWriteTokens: 0,
cacheReadTokens: 0,
// openrouter generation endpoint fails often
inputTokens: generation?.native_tokens_prompt || 0,
outputTokens: generation?.native_tokens_completion || 0,
+174 -234
View File
@@ -4,26 +4,28 @@ import { withRetry } from "../retry"
import { ApiHandler } from "../"
import { ApiHandlerOptions, ModelInfo, vertexDefaultModelId, VertexModelId, vertexModels } from "@shared/api"
import { ApiStream } from "@api/transform/stream"
import { VertexAI } from "@google-cloud/vertexai"
import { calculateApiCostOpenAI } from "@utils/cost"
import { GeminiHandler } from "./gemini"
// https://docs.anthropic.com/en/api/claude-on-vertex-ai
export class VertexHandler implements ApiHandler {
private options: ApiHandlerOptions
private geminiHandler: GeminiHandler
private clientAnthropic: AnthropicVertex
private clientVertex: VertexAI
private options: ApiHandlerOptions
constructor(options: ApiHandlerOptions) {
this.options = options
// Create a GeminiHandler with isVertex flag for Gemini models
this.geminiHandler = new GeminiHandler({
...options,
isVertex: true,
})
// Initialize Anthropic client for Claude models
this.clientAnthropic = new AnthropicVertex({
projectId: this.options.vertexProjectId,
// https://cloud.google.com/vertex-ai/generative-ai/docs/partner-models/use-claude#regions
region: this.options.vertexRegion,
})
this.clientVertex = new VertexAI({
project: this.options.vertexProjectId,
location: this.options.vertexRegion,
})
}
@withRetry()
@@ -31,66 +33,46 @@ export class VertexHandler implements ApiHandler {
const model = this.getModel()
const modelId = model.id
if (modelId.includes("claude")) {
let budget_tokens = this.options.thinkingBudgetTokens || 0
const reasoningOn = modelId.includes("3-7") && budget_tokens !== 0 ? true : false
// For Gemini models, use the GeminiHandler
if (!modelId.includes("claude")) {
yield* this.geminiHandler.createMessage(systemPrompt, messages)
return
}
let stream
switch (modelId) {
case "claude-3-7-sonnet@20250219":
case "claude-3-5-sonnet-v2@20241022":
case "claude-3-5-sonnet@20240620":
case "claude-3-5-haiku@20241022":
case "claude-3-opus@20240229":
case "claude-3-haiku@20240307": {
// Find indices of user messages for cache control
const userMsgIndices = messages.reduce(
(acc, msg, index) => (msg.role === "user" ? [...acc, index] : acc),
[] as number[],
)
const lastUserMsgIndex = userMsgIndices[userMsgIndices.length - 1] ?? -1
const secondLastMsgUserIndex = userMsgIndices[userMsgIndices.length - 2] ?? -1
// Claude implementation
let budget_tokens = this.options.thinkingBudgetTokens || 0
const reasoningOn = modelId.includes("3-7") && budget_tokens !== 0 ? true : false
let stream
stream = await this.clientAnthropic.beta.messages.create(
{
model: modelId,
max_tokens: model.info.maxTokens || 8192,
thinking: reasoningOn ? { type: "enabled", budget_tokens: budget_tokens } : undefined,
temperature: reasoningOn ? undefined : 0,
system: [
{
text: systemPrompt,
type: "text",
cache_control: { type: "ephemeral" },
},
],
messages: messages.map((message, index) => {
if (index === lastUserMsgIndex || index === secondLastMsgUserIndex) {
return {
...message,
content:
typeof message.content === "string"
? [
{
type: "text",
text: message.content,
cache_control: {
type: "ephemeral",
},
},
]
: message.content.map((content, contentIndex) =>
contentIndex === message.content.length - 1
? {
...content,
cache_control: {
type: "ephemeral",
},
}
: content,
),
}
}
switch (modelId) {
case "claude-3-7-sonnet@20250219":
case "claude-3-5-sonnet-v2@20241022":
case "claude-3-5-sonnet@20240620":
case "claude-3-5-haiku@20241022":
case "claude-3-opus@20240229":
case "claude-3-haiku@20240307": {
// Find indices of user messages for cache control
const userMsgIndices = messages.reduce(
(acc, msg, index) => (msg.role === "user" ? [...acc, index] : acc),
[] as number[],
)
const lastUserMsgIndex = userMsgIndices[userMsgIndices.length - 1] ?? -1
const secondLastMsgUserIndex = userMsgIndices[userMsgIndices.length - 2] ?? -1
stream = await this.clientAnthropic.beta.messages.create(
{
model: modelId,
max_tokens: model.info.maxTokens || 8192,
thinking: reasoningOn ? { type: "enabled", budget_tokens: budget_tokens } : undefined,
temperature: reasoningOn ? undefined : 0,
system: [
{
text: systemPrompt,
type: "text",
cache_control: { type: "ephemeral" },
},
],
messages: messages.map((message, index) => {
if (index === lastUserMsgIndex || index === secondLastMsgUserIndex) {
return {
...message,
content:
@@ -99,184 +81,142 @@ export class VertexHandler implements ApiHandler {
{
type: "text",
text: message.content,
cache_control: {
type: "ephemeral",
},
},
]
: message.content,
: message.content.map((content, contentIndex) =>
contentIndex === message.content.length - 1
? {
...content,
cache_control: {
type: "ephemeral",
},
}
: content,
),
}
}),
stream: true,
},
{
headers: {},
},
)
break
}
default: {
stream = await this.clientAnthropic.beta.messages.create({
model: modelId,
max_tokens: model.info.maxTokens || 8192,
temperature: 0,
system: [
{
text: systemPrompt,
type: "text",
},
],
messages: messages.map((message) => ({
...message,
content:
typeof message.content === "string"
? [
{
type: "text",
text: message.content,
},
]
: message.content,
})),
stream: true,
})
break
}
}
for await (const chunk of stream) {
switch (chunk.type) {
case "message_start":
const usage = chunk.message.usage
yield {
type: "usage",
inputTokens: usage.input_tokens || 0,
outputTokens: usage.output_tokens || 0,
cacheWriteTokens: usage.cache_creation_input_tokens || undefined,
cacheReadTokens: usage.cache_read_input_tokens || undefined,
}
break
case "message_delta":
yield {
type: "usage",
inputTokens: 0,
outputTokens: chunk.usage.output_tokens || 0,
}
break
case "message_stop":
break
case "content_block_start":
switch (chunk.content_block.type) {
case "thinking":
yield {
type: "reasoning",
reasoning: chunk.content_block.thinking || "",
}
break
case "redacted_thinking":
// Handle redacted thinking blocks - we still mark it as reasoning
// but note that the content is encrypted
yield {
type: "reasoning",
reasoning: "[Redacted thinking block]",
}
break
case "text":
if (chunk.index > 0) {
yield {
type: "text",
text: "\n",
}
}
yield {
type: "text",
text: chunk.content_block.text,
}
break
}
break
case "content_block_delta":
switch (chunk.delta.type) {
case "thinking_delta":
yield {
type: "reasoning",
reasoning: chunk.delta.thinking,
}
break
case "text_delta":
yield {
type: "text",
text: chunk.delta.text,
}
break
}
break
case "content_block_stop":
break
}
}
} else {
// gemini
const generativeModel = this.clientVertex.getGenerativeModel({
model: this.getModel().id,
systemInstruction: {
role: "system",
parts: [{ text: systemPrompt }],
},
})
const request = {
contents: [
{
role: "user",
parts: messages.map((m) => {
if (typeof m.content === "string") {
return { text: m.content }
} else if (Array.isArray(m.content)) {
return {
text: m.content
.map((block) => {
if (typeof block === "string") {
return block
} else if (block.type === "text") {
return block.text
} else {
console.log("Unsupported block type", block)
return ""
}
})
.join(" "),
}
} else {
return { text: "" }
}
return {
...message,
content:
typeof message.content === "string"
? [
{
type: "text",
text: message.content,
},
]
: message.content,
}
}),
stream: true,
},
],
{
headers: {},
},
)
break
}
const streamingResult = await generativeModel.generateContentStream(request)
for await (const chunk of streamingResult.stream) {
// If usage data is available, yield it similarly:
// yield { type: "usage", inputTokens: 0, outputTokens: 0 }
// Otherwise, just yield text:
const candidates = chunk.candidates || []
for (const candidate of candidates) {
for (const part of candidate.content?.parts || []) {
if (part.text) {
default: {
stream = await this.clientAnthropic.beta.messages.create({
model: modelId,
max_tokens: model.info.maxTokens || 8192,
temperature: 0,
system: [
{
text: systemPrompt,
type: "text",
},
],
messages: messages.map((message) => ({
...message,
content:
typeof message.content === "string"
? [
{
type: "text",
text: message.content,
},
]
: message.content,
})),
stream: true,
})
break
}
}
for await (const chunk of stream) {
switch (chunk.type) {
case "message_start":
const usage = chunk.message.usage
yield {
type: "usage",
inputTokens: usage.input_tokens || 0,
outputTokens: usage.output_tokens || 0,
cacheWriteTokens: usage.cache_creation_input_tokens || undefined,
cacheReadTokens: usage.cache_read_input_tokens || undefined,
}
break
case "message_delta":
yield {
type: "usage",
inputTokens: 0,
outputTokens: chunk.usage?.output_tokens || 0,
}
break
case "message_stop":
break
case "content_block_start":
switch (chunk.content_block.type) {
case "thinking":
yield {
type: "reasoning",
reasoning: chunk.content_block.thinking || "",
}
break
case "redacted_thinking":
// Handle redacted thinking blocks - we still mark it as reasoning
// but note that the content is encrypted
yield {
type: "reasoning",
reasoning: "[Redacted thinking block]",
}
break
case "text":
if (chunk.index > 0) {
yield {
type: "text",
text: "\n",
}
}
yield {
type: "text",
text: part.text,
text: chunk.content_block.text,
}
}
break
}
}
}
// Handle token usage metadata
const { usageMetadata } = await streamingResult.response
if (usageMetadata) {
const { promptTokenCount = 0, candidatesTokenCount = 0 } = usageMetadata
yield {
type: "usage",
inputTokens: promptTokenCount,
outputTokens: candidatesTokenCount,
totalCost: calculateApiCostOpenAI(model.info, promptTokenCount, candidatesTokenCount, 0, 0),
}
break
case "content_block_delta":
switch (chunk.delta.type) {
case "thinking_delta":
yield {
type: "reasoning",
reasoning: chunk.delta.thinking,
}
break
case "text_delta":
yield {
type: "text",
text: chunk.delta.text,
}
break
}
break
case "content_block_stop":
break
}
}
}
+48 -1
View File
@@ -20,7 +20,8 @@ export async function createOpenRouterStream(
]
// prompt caching: https://openrouter.ai/docs/prompt-caching
// this is specifically for claude models (some models may 'support prompt caching' automatically without this)
// this was initially specifically for claude models (some models may 'support prompt caching' automatically without this)
// includes custom support for gemini which does not have iterative caching
switch (model.id) {
case "anthropic/claude-3.7-sonnet":
case "anthropic/claude-3.7-sonnet:beta":
@@ -70,6 +71,52 @@ export async function createOpenRouterStream(
}
})
break
case "google/gemini-2.5-pro-preview-03-25":
case "google/gemini-2.0-flash-001":
case "google/gemini-flash-1.5":
case "google/gemini-pro-1.5":
// gemini only uses the last breakpoint for caching, so the others will be ignored
openAiMessages[0] = {
role: "system",
content: [
{
type: "text",
text: systemPrompt,
// @ts-ignore-next-line
cache_control: { type: "ephemeral" },
},
],
}
const GEMINI_CACHE_USER_MESSAGE_INTERVAL = 4 // add new breakpoint every 4 turns
const userMessages = openAiMessages.filter((msg) => msg.role === "user")
const userMessageCount = userMessages.length
const targetUserMessageNumber =
Math.floor(userMessageCount / GEMINI_CACHE_USER_MESSAGE_INTERVAL) * GEMINI_CACHE_USER_MESSAGE_INTERVAL
if (targetUserMessageNumber > 0) {
// otherwise dont need to add a breakpoint
const msg = userMessages[targetUserMessageNumber - 1]
if (msg) {
if (typeof msg.content === "string") {
msg.content = [{ type: "text", text: msg.content }]
}
if (Array.isArray(msg.content)) {
// NOTE: this is fine since env details will always be added at the end. but if it weren't there, and the user added a image_url type message, it would pop a text part before it and then move it after to the end.
let lastTextPart = msg.content.filter((part) => part.type === "text").pop()
if (!lastTextPart) {
lastTextPart = { type: "text", text: "..." }
msg.content.push(lastTextPart)
}
// @ts-ignore-next-line
lastTextPart["cache_control"] = { type: "ephemeral" }
}
}
}
break
default:
break
}
+2
View File
@@ -24,6 +24,8 @@ export const toolUseNames = [
"load_mcp_documentation",
"attempt_completion",
"new_task",
"condense",
"new_rule",
] as const
// Converts array of tool call names into a union type ("execute_command" | "read_file" | ...)
@@ -55,7 +55,10 @@ export function parseAssistantMessage(assistantMessage: string) {
// special case for write_to_file where file contents could contain the closing tag, in which case the param would have closed and we end up with the rest of the file contents here. To work around this, we get the string between the starting content tag and the LAST content tag.
const contentParamName: ToolParamName = "content"
if (currentToolUse.name === "write_to_file" && accumulator.endsWith(`</${contentParamName}>`)) {
if (
(currentToolUse.name === "write_to_file" || currentToolUse.name === "new_rule") &&
accumulator.endsWith(`</${contentParamName}>`)
) {
const toolContent = accumulator.slice(currentToolUseStartIndex)
const contentStartTag = `<${contentParamName}>`
const contentEndTag = `</${contentParamName}>`
@@ -193,14 +193,20 @@ export class ContextManager {
public getNextTruncationRange(
apiMessages: Anthropic.Messages.MessageParam[],
currentDeletedRange: [number, number] | undefined,
keep: "half" | "quarter",
keep: "none" | "lastTwo" | "half" | "quarter",
): [number, number] {
// We always keep the first user-assistant pairing, and truncate an even number of messages from there
const rangeStartIndex = 2 // index 0 and 1 are kept
const startOfRest = currentDeletedRange ? currentDeletedRange[1] + 1 : 2 // inclusive starting index
let messagesToRemove: number
if (keep === "half") {
if (keep === "none") {
// Removes all messages beyond the first core user/assistant message pair
messagesToRemove = Math.max(apiMessages.length - startOfRest, 0)
} else if (keep === "lastTwo") {
// Keep the last user-assistant pair in addition to the first core user/assistant message pair
messagesToRemove = Math.max(apiMessages.length - startOfRest - 2, 0)
} else if (keep === "half") {
// Remove half of remaining user-assistant pairs
// We first calculate half of the messages then divide by 2 to get the number of pairs.
// After flooring, we multiply by 2 to get the number of messages.
@@ -382,6 +388,17 @@ export class ContextManager {
return [contextHistoryUpdated, uniqueFileReadIndices]
}
/**
* Public function for triggering potentially setting the truncation message
* If the truncation message already exists, does nothing, otherwise adds the message
*/
async triggerApplyStandardContextTruncationNoticeChange(timestamp: number, taskDirectory: string) {
const updated = this.applyStandardContextTruncationNoticeChange(timestamp)
if (updated) {
await this.saveContextHistory(taskDirectory)
}
}
/**
* if there is any truncation and there is no other alteration already set, alter the assistant message to indicate this occurred
*/
@@ -34,24 +34,24 @@ describe("ContextManager", () => {
const messages = createMessages(11)
const result = contextManager.getNextTruncationRange(messages, undefined, "half")
expect(result).to.deep.equal([1, 4])
expect(result).to.deep.equal([2, 5])
})
it("first truncation with quarter keep", () => {
const messages = createMessages(11)
const result = contextManager.getNextTruncationRange(messages, undefined, "quarter")
expect(result).to.deep.equal([1, 6])
expect(result).to.deep.equal([2, 7])
})
it("sequential truncation with half keep", () => {
const messages = createMessages(21)
const firstRange = contextManager.getNextTruncationRange(messages, undefined, "half")
expect(firstRange).to.deep.equal([1, 10])
expect(firstRange).to.deep.equal([2, 9])
// Pass the previous range for sequential truncation
const secondRange = contextManager.getNextTruncationRange(messages, firstRange, "half")
expect(secondRange).to.deep.equal([1, 14])
expect(secondRange).to.deep.equal([2, 13])
})
it("sequential truncation with quarter keep", () => {
@@ -60,7 +60,7 @@ describe("ContextManager", () => {
const secondRange = contextManager.getNextTruncationRange(messages, firstRange, "quarter")
expect(secondRange[0]).to.equal(1)
expect(secondRange[0]).to.equal(2)
expect(secondRange[1]).to.be.greaterThan(firstRange[1])
})
@@ -68,20 +68,20 @@ describe("ContextManager", () => {
const messages = createMessages(14)
const result = contextManager.getNextTruncationRange(messages, undefined, "half")
// Check if the message at the end of range is a user message
// Check if the message at the end of range is an assistant message
const lastRemovedMessage = messages[result[1]]
expect(lastRemovedMessage.role).to.equal("user")
expect(lastRemovedMessage.role).to.equal("assistant")
// Check if the next message after the range is an assistant message
// Check if the next message after the range is a user message
const nextMessage = messages[result[1] + 1]
expect(nextMessage.role).to.equal("assistant")
expect(nextMessage.role).to.equal("user")
})
it("handles small message arrays", () => {
const messages = createMessages(3)
const result = contextManager.getNextTruncationRange(messages, undefined, "half")
expect(result).to.deep.equal([1, 0])
expect(result).to.deep.equal([2, 1])
})
it("preserves the message structure when truncating", () => {
@@ -120,9 +120,10 @@ describe("ContextManager", () => {
const range: [number, number] = [1, 3]
const result = contextManager.getTruncatedMessages(messages, range)
expect(result).to.have.lengthOf(2)
expect(result).to.have.lengthOf(3)
expect(result[0]).to.deep.equal(messages[0])
expect(result[1]).to.deep.equal(messages[4])
expect(result[1]).to.deep.equal(messages[1])
expect(result[2]).to.deep.equal(messages[4])
})
it("works with a range that starts at the first message after task", () => {
@@ -131,20 +132,21 @@ describe("ContextManager", () => {
const range: [number, number] = [1, 2]
const result = contextManager.getTruncatedMessages(messages, range)
expect(result).to.have.lengthOf(2)
expect(result).to.have.lengthOf(3)
expect(result[0]).to.deep.equal(messages[0])
expect(result[1]).to.deep.equal(messages[3])
expect(result[1]).to.deep.equal(messages[1])
expect(result[2]).to.deep.equal(messages[3])
})
it("correctly handles removing a range while preserving alternation pattern", () => {
const messages = createMessages(5)
const range: [number, number] = [1, 2]
const range: [number, number] = [2, 3]
const result = contextManager.getTruncatedMessages(messages, range)
expect(result).to.have.lengthOf(3)
expect(result[0]).to.deep.equal(messages[0])
expect(result[1]).to.deep.equal(messages[3])
expect(result[1]).to.deep.equal(messages[1])
expect(result[2]).to.deep.equal(messages[4])
expect(result[0].role).to.equal("user")
@@ -76,26 +76,6 @@ describe("ModelContextTracker", () => {
}
})
it("should throw an error when controller is dereferenced", async () => {
// Create a new tracker with a controller that will be garbage collected
const weakTracker = new ModelContextTracker(mockContext, taskId)
// Force the WeakRef to return null by overriding the deref method
const weakRef = { deref: sandbox.stub().returns(null) }
sandbox.stub(WeakRef.prototype, "deref").callsFake(() => weakRef.deref())
try {
// Try to call the method - this should throw
await weakTracker.recordModelUsage("any-provider", "any-model", "any-mode")
// If we get here, the test should fail
expect.fail("Expected an error to be thrown")
} catch (error) {
// Verify the error message
expect(error.message).to.equal("Unable to access extension context")
}
})
it("should append model usage to existing entries", async () => {
// Add an existing model usage entry
const existingTimestamp = 1617200000000
@@ -6,17 +6,53 @@ import fs from "fs/promises"
import { ClineRulesToggles } from "@shared/cline-rules"
import { getGlobalState, getWorkspaceState, updateGlobalState, updateWorkspaceState } from "@core/storage/state"
import * as vscode from "vscode"
import { synchronizeRuleToggles, getRuleFilesTotalContent } from "@core/context/instructions/user-instructions/rule-helpers"
/**
* Converts .clinerules file to directory and places old .clinerule file inside directory, renaming it
* Doesn't do anything if .clinerules dir already exists or doesn't exist
* Returns whether there are any uncaught errors
*/
export async function ensureLocalClinerulesDirExists(cwd: string): Promise<boolean> {
const clinerulePath = path.resolve(cwd, GlobalFileNames.clineRules)
const defaultRuleFilename = "default-rules.md"
try {
const exists = await fileExistsAtPath(clinerulePath)
if (exists && !(await isDirectory(clinerulePath))) {
// logic to convert .clinerules file into directory, and rename the rules file to {defaultRuleFilename}
const content = await fs.readFile(clinerulePath, "utf8")
const tempPath = clinerulePath + ".bak"
await fs.rename(clinerulePath, tempPath) // create backup
try {
await fs.mkdir(clinerulePath, { recursive: true })
await fs.writeFile(path.join(clinerulePath, defaultRuleFilename), content, "utf8")
await fs.unlink(tempPath).catch(() => {}) // delete backup
return false // conversion successful with no errors
} catch (conversionError) {
// attempt to restore backup on conversion failure
try {
await fs.rm(clinerulePath, { recursive: true, force: true }).catch(() => {})
await fs.rename(tempPath, clinerulePath) // restore backup
} catch (restoreError) {}
return true // in either case here we consider this an error
}
}
// exists and is a dir or doesn't exist, either of these cases we dont need to handle here
return false
} catch (error) {
return true
}
}
export const getGlobalClineRules = async (globalClineRulesFilePath: string, toggles: ClineRulesToggles) => {
if (await fileExistsAtPath(globalClineRulesFilePath)) {
if (await isDirectory(globalClineRulesFilePath)) {
try {
const rulesFilePaths = await readDirectory(globalClineRulesFilePath)
const rulesFilesTotalContent = await getClineRulesFilesTotalContent(
rulesFilePaths,
globalClineRulesFilePath,
toggles,
)
const rulesFilesTotalContent = await getRuleFilesTotalContent(rulesFilePaths, globalClineRulesFilePath, toggles)
if (rulesFilesTotalContent) {
const clineRulesFileInstructions = formatResponse.clineRulesGlobalDirectoryInstructions(
globalClineRulesFilePath,
@@ -45,7 +81,7 @@ export const getLocalClineRules = async (cwd: string, toggles: ClineRulesToggles
if (await isDirectory(clineRulesFilePath)) {
try {
const rulesFilePaths = await readDirectory(clineRulesFilePath)
const rulesFilesTotalContent = await getClineRulesFilesTotalContent(rulesFilePaths, cwd, toggles)
const rulesFilesTotalContent = await getRuleFilesTotalContent(rulesFilePaths, cwd, toggles)
if (rulesFilesTotalContent) {
clineRulesFileInstructions = formatResponse.clineRulesLocalDirectoryInstructions(cwd, rulesFilesTotalContent)
}
@@ -69,86 +105,6 @@ export const getLocalClineRules = async (cwd: string, toggles: ClineRulesToggles
return clineRulesFileInstructions
}
const getClineRulesFilesTotalContent = async (rulesFilePaths: string[], basePath: string, toggles: ClineRulesToggles) => {
const ruleFilesTotalContent = await Promise.all(
rulesFilePaths.map(async (filePath) => {
const ruleFilePath = path.resolve(basePath, filePath)
const ruleFilePathRelative = path.relative(basePath, ruleFilePath)
if (ruleFilePath in toggles && toggles[ruleFilePath] === false) {
return null
}
return `${ruleFilePathRelative}\n` + (await fs.readFile(ruleFilePath, "utf8")).trim()
}),
).then((contents) => contents.filter(Boolean).join("\n\n"))
return ruleFilesTotalContent
}
export async function synchronizeRuleToggles(
rulesDirectoryPath: string,
currentToggles: ClineRulesToggles,
): Promise<ClineRulesToggles> {
// Create a copy of toggles to modify
const updatedToggles = { ...currentToggles }
try {
const pathExists = await fileExistsAtPath(rulesDirectoryPath)
if (pathExists) {
const isDir = await isDirectory(rulesDirectoryPath)
if (isDir) {
// DIRECTORY CASE
const filePaths = await readDirectory(rulesDirectoryPath)
const existingRulePaths = new Set<string>()
for (const filePath of filePaths) {
const ruleFilePath = path.resolve(rulesDirectoryPath, filePath)
existingRulePaths.add(ruleFilePath)
const pathHasToggle = ruleFilePath in updatedToggles
if (!pathHasToggle) {
updatedToggles[ruleFilePath] = true
}
}
// Clean up toggles for non-existent files
for (const togglePath in updatedToggles) {
const pathExists = existingRulePaths.has(togglePath)
if (!pathExists) {
delete updatedToggles[togglePath]
}
}
} else {
// FILE CASE
// Add toggle for this file
const pathHasToggle = rulesDirectoryPath in updatedToggles
if (!pathHasToggle) {
updatedToggles[rulesDirectoryPath] = true
}
// Remove toggles for any other paths
for (const togglePath in updatedToggles) {
if (togglePath !== rulesDirectoryPath) {
delete updatedToggles[togglePath]
}
}
}
} else {
// PATH DOESN'T EXIST CASE
// Clear all toggles since the path doesn't exist
for (const togglePath in updatedToggles) {
delete updatedToggles[togglePath]
}
}
} catch (error) {
console.error(`Failed to synchronize rule toggles for path: ${rulesDirectoryPath}`, error)
}
return updatedToggles
}
export async function refreshClineRulesToggles(
context: vscode.ExtensionContext,
workingDirectory: string,
@@ -182,7 +138,14 @@ export const createRuleFile = async (isGlobal: boolean, filename: string, cwd: s
filePath = path.join(globalClineRulesFilePath, filename)
} else {
const localClineRulesFilePath = path.resolve(cwd, GlobalFileNames.clineRules)
const hasError = await ensureLocalClinerulesDirExists(cwd)
if (hasError === true) {
return { filePath: null, fileExists: false }
}
await fs.mkdir(localClineRulesFilePath, { recursive: true })
filePath = path.join(localClineRulesFilePath, filename)
}
@@ -0,0 +1,120 @@
import path from "path"
import fs from "fs/promises"
import { GlobalFileNames } from "@core/storage/disk"
import { fileExistsAtPath, isDirectory } from "@utils/fs"
import { formatResponse } from "@core/prompts/responses"
import { getWorkspaceState, updateWorkspaceState } from "@core/storage/state"
import {
synchronizeRuleToggles,
combineRuleToggles,
getRuleFilesTotalContent,
readDirectoryRecursive,
} from "@core/context/instructions/user-instructions/rule-helpers"
import { ClineRulesToggles } from "@shared/cline-rules"
import * as vscode from "vscode"
/**
* Refreshes the toggles for windsurf and cursor rules
*/
export async function refreshExternalRulesToggles(
context: vscode.ExtensionContext,
workingDirectory: string,
): Promise<{
windsurfLocalToggles: ClineRulesToggles
cursorLocalToggles: ClineRulesToggles
}> {
// local windsurf toggles
const localWindsurfRulesToggles = ((await getWorkspaceState(context, "localWindsurfRulesToggles")) as ClineRulesToggles) || {}
const localWindsurfRulesFilePath = path.resolve(workingDirectory, GlobalFileNames.windsurfRules)
const updatedLocalWindsurfToggles = await synchronizeRuleToggles(localWindsurfRulesFilePath, localWindsurfRulesToggles)
await updateWorkspaceState(context, "localWindsurfRulesToggles", updatedLocalWindsurfToggles)
// local cursor toggles
const localCursorRulesToggles = ((await getWorkspaceState(context, "localCursorRulesToggles")) as ClineRulesToggles) || {}
// cursor has two valid locations for rules files, so we need to check both and combine
// synchronizeRuleToggles will drop whichever rules files are not in each given path, but combining the results will result in no data loss
let localCursorRulesFilePath = path.resolve(workingDirectory, GlobalFileNames.cursorRulesDir)
const updatedLocalCursorToggles1 = await synchronizeRuleToggles(localCursorRulesFilePath, localCursorRulesToggles, ".mdc")
localCursorRulesFilePath = path.resolve(workingDirectory, GlobalFileNames.cursorRulesFile)
const updatedLocalCursorToggles2 = await synchronizeRuleToggles(localCursorRulesFilePath, localCursorRulesToggles)
const updatedLocalCursorToggles = combineRuleToggles(updatedLocalCursorToggles1, updatedLocalCursorToggles2)
await updateWorkspaceState(context, "localCursorRulesToggles", updatedLocalCursorToggles)
return {
windsurfLocalToggles: updatedLocalWindsurfToggles,
cursorLocalToggles: updatedLocalCursorToggles,
}
}
/**
* Gather formatted windsurf rules
*/
export const getLocalWindsurfRules = async (cwd: string, toggles: ClineRulesToggles) => {
const windsurfRulesFilePath = path.resolve(cwd, GlobalFileNames.windsurfRules)
let windsurfRulesFileInstructions: string | undefined
if (await fileExistsAtPath(windsurfRulesFilePath)) {
if (!(await isDirectory(windsurfRulesFilePath))) {
try {
if (windsurfRulesFilePath in toggles && toggles[windsurfRulesFilePath] !== false) {
const ruleFileContent = (await fs.readFile(windsurfRulesFilePath, "utf8")).trim()
if (ruleFileContent) {
windsurfRulesFileInstructions = formatResponse.windsurfRulesLocalFileInstructions(cwd, ruleFileContent)
}
}
} catch {
console.error(`Failed to read .windsurfrules file at ${windsurfRulesFilePath}`)
}
}
}
return windsurfRulesFileInstructions
}
/**
* Gather formatted cursor rules, which can come from two sources
*/
export const getLocalCursorRules = async (cwd: string, toggles: ClineRulesToggles) => {
// we first check for the .cursorrules file
const cursorRulesFilePath = path.resolve(cwd, GlobalFileNames.cursorRulesFile)
let cursorRulesFileInstructions: string | undefined
if (await fileExistsAtPath(cursorRulesFilePath)) {
if (!(await isDirectory(cursorRulesFilePath))) {
try {
if (cursorRulesFilePath in toggles && toggles[cursorRulesFilePath] !== false) {
const ruleFileContent = (await fs.readFile(cursorRulesFilePath, "utf8")).trim()
if (ruleFileContent) {
cursorRulesFileInstructions = formatResponse.cursorRulesLocalFileInstructions(cwd, ruleFileContent)
}
}
} catch {
console.error(`Failed to read .cursorrules file at ${cursorRulesFilePath}`)
}
}
}
// we then check for the .cursor/rules dir
const cursorRulesDirPath = path.resolve(cwd, GlobalFileNames.cursorRulesDir)
let cursorRulesDirInstructions: string | undefined
if (await fileExistsAtPath(cursorRulesDirPath)) {
if (await isDirectory(cursorRulesDirPath)) {
try {
const rulesFilePaths = await readDirectoryRecursive(cursorRulesDirPath, ".mdc")
const rulesFilesTotalContent = await getRuleFilesTotalContent(rulesFilePaths, cwd, toggles)
if (rulesFilesTotalContent) {
cursorRulesDirInstructions = formatResponse.cursorRulesLocalDirectoryInstructions(cwd, rulesFilesTotalContent)
}
} catch {
console.error(`Failed to read .cursor/rules directory at ${cursorRulesDirPath}`)
}
}
}
return [cursorRulesFileInstructions, cursorRulesDirInstructions]
}
@@ -0,0 +1,121 @@
import { fileExistsAtPath, isDirectory, readDirectory } from "@utils/fs"
import * as path from "path"
import fs from "fs/promises"
import { ClineRulesToggles } from "@shared/cline-rules"
/**
* Recursively traverses directory and finds all files, including checking for optional whitelisted file extension
*/
export async function readDirectoryRecursive(directoryPath: string, allowedFileExtension: string): Promise<string[]> {
try {
const entries = await readDirectory(directoryPath)
let results: string[] = []
for (const entry of entries) {
if (allowedFileExtension !== "") {
const fileExtension = path.extname(entry)
if (fileExtension !== allowedFileExtension) {
continue
}
}
results.push(entry)
}
return results
} catch (error) {
console.error(`Error reading directory ${directoryPath}: ${error}`)
return []
}
}
/**
* Gets the up to date toggles
*/
export async function synchronizeRuleToggles(
rulesDirectoryPath: string,
currentToggles: ClineRulesToggles,
allowedFileExtension: string = "",
): Promise<ClineRulesToggles> {
// Create a copy of toggles to modify
const updatedToggles = { ...currentToggles }
try {
const pathExists = await fileExistsAtPath(rulesDirectoryPath)
if (pathExists) {
const isDir = await isDirectory(rulesDirectoryPath)
if (isDir) {
// DIRECTORY CASE
const filePaths = await readDirectoryRecursive(rulesDirectoryPath, allowedFileExtension)
const existingRulePaths = new Set<string>()
for (const filePath of filePaths) {
const ruleFilePath = path.resolve(rulesDirectoryPath, filePath)
existingRulePaths.add(ruleFilePath)
const pathHasToggle = ruleFilePath in updatedToggles
if (!pathHasToggle) {
updatedToggles[ruleFilePath] = true
}
}
// Clean up toggles for non-existent files
for (const togglePath in updatedToggles) {
const pathExists = existingRulePaths.has(togglePath)
if (!pathExists) {
delete updatedToggles[togglePath]
}
}
} else {
// FILE CASE
// Add toggle for this file
const pathHasToggle = rulesDirectoryPath in updatedToggles
if (!pathHasToggle) {
updatedToggles[rulesDirectoryPath] = true
}
// Remove toggles for any other paths
for (const togglePath in updatedToggles) {
if (togglePath !== rulesDirectoryPath) {
delete updatedToggles[togglePath]
}
}
}
} else {
// PATH DOESN'T EXIST CASE
// Clear all toggles since the path doesn't exist
for (const togglePath in updatedToggles) {
delete updatedToggles[togglePath]
}
}
} catch (error) {
console.error(`Failed to synchronize rule toggles for path: ${rulesDirectoryPath}`, error)
}
return updatedToggles
}
/**
* Certain project rules have more than a single location where rules are allowed to be stored
*/
export function combineRuleToggles(toggles1: ClineRulesToggles, toggles2: ClineRulesToggles): ClineRulesToggles {
return { ...toggles1, ...toggles2 }
}
/**
* Read the content of rules files
*/
export const getRuleFilesTotalContent = async (rulesFilePaths: string[], basePath: string, toggles: ClineRulesToggles) => {
const ruleFilesTotalContent = await Promise.all(
rulesFilePaths.map(async (filePath) => {
const ruleFilePath = path.resolve(basePath, filePath)
const ruleFilePathRelative = path.relative(basePath, ruleFilePath)
if (ruleFilePath in toggles && toggles[ruleFilePath] === false) {
return null
}
return `${ruleFilePathRelative}\n` + (await fs.readFile(ruleFilePath, "utf8")).trim()
}),
).then((contents) => contents.filter(Boolean).join("\n\n"))
return ruleFilesTotalContent
}
@@ -0,0 +1,30 @@
import * as vscode from "vscode"
import crypto from "crypto"
import { Controller } from "../index"
import { storeSecret } from "../../storage/state"
/**
* Handles the user clicking the login link in the UI.
* Generates a secure nonce for state validation, stores it in secrets,
* and opens the authentication URL in the external browser.
*
* @param controller The controller instance.
* @returns The login URL as a string.
*/
export async function accountLoginClicked(controller: Controller): Promise<String> {
// Generate nonce for state validation
const nonce = crypto.randomBytes(32).toString("hex")
await storeSecret(controller.context, "authNonce", nonce)
// Open browser for authentication with state param
console.log("Login button clicked in account page")
console.log("Opening auth page with state param")
const uriScheme = vscode.env.uriScheme
const authUrl = vscode.Uri.parse(
`https://app.cline.bot/auth?state=${encodeURIComponent(nonce)}&callback_url=${encodeURIComponent(`${uriScheme || "vscode"}://saoudrizwan.claude-dev/auth`)}`,
)
vscode.env.openExternal(authUrl)
return authUrl.toString()
}
+14
View File
@@ -0,0 +1,14 @@
import { createServiceRegistry, ServiceMethodHandler } from "../grpc-service"
import { registerAllMethods } from "./methods"
const accountService = createServiceRegistry("account")
// Export the method handler type and registration function
export type AccountMethodHandler = ServiceMethodHandler
export const registerMethod = accountService.registerMethod
// Export the request handler
export const handleAccountServiceRequest = accountService.handleRequest
// Register all account methods
registerAllMethods()
+12
View File
@@ -0,0 +1,12 @@
// AUTO-GENERATED FILE - DO NOT MODIFY DIRECTLY
// Generated by proto/build-proto.js
// Import all method implementations
import { registerMethod } from "./index"
import { accountLoginClicked } from "./accountLoginClicked"
// Register all account service methods
export function registerAllMethods(): void {
// Register each method with the registry
registerMethod("accountLoginClicked", accountLoginClicked)
}
@@ -0,0 +1,30 @@
import { ChromePath } from "../../../shared/proto/browser"
import { EmptyRequest } from "../../../shared/proto/common"
import { Controller } from "../index"
import { getAllExtensionState } from "../../storage/state"
import { BrowserSession } from "../../../services/browser/BrowserSession"
/**
* Get the detected Chrome executable path
* @param controller The controller instance
* @param request The empty request message
* @returns The detected Chrome path and whether it's bundled
*/
export async function getDetectedChromePath(controller: Controller, request: EmptyRequest): Promise<ChromePath> {
try {
const { browserSettings } = await getAllExtensionState(controller.context)
const browserSession = new BrowserSession(controller.context, browserSettings)
const result = await browserSession.getDetectedChromePath()
return {
path: result.path,
isBundled: result.isBundled,
}
} catch (error) {
console.error("Error getting detected Chrome path:", error)
return {
path: "",
isBundled: false,
}
}
}
+4
View File
@@ -5,12 +5,16 @@
import { registerMethod } from "./index"
import { discoverBrowser } from "./discoverBrowser"
import { getBrowserConnectionInfo } from "./getBrowserConnectionInfo"
import { getDetectedChromePath } from "./getDetectedChromePath"
import { testBrowserConnection } from "./testBrowserConnection"
import { updateBrowserSettings } from "./updateBrowserSettings"
// Register all browser service methods
export function registerAllMethods(): void {
// Register each method with the registry
registerMethod("discoverBrowser", discoverBrowser)
registerMethod("getBrowserConnectionInfo", getBrowserConnectionInfo)
registerMethod("getDetectedChromePath", getDetectedChromePath)
registerMethod("testBrowserConnection", testBrowserConnection)
registerMethod("updateBrowserSettings", updateBrowserSettings)
}
@@ -0,0 +1,46 @@
import { UpdateBrowserSettingsRequest } from "../../../shared/proto/browser"
import { Boolean } from "../../../shared/proto/common"
import { Controller } from "../index"
import { updateGlobalState } from "../../storage/state"
import { BrowserSettings as SharedBrowserSettings } from "../../../shared/BrowserSettings"
/**
* Update browser settings
* @param controller The controller instance
* @param request The browser settings request message
* @returns Success response
*/
export async function updateBrowserSettings(controller: Controller, request: UpdateBrowserSettingsRequest): Promise<Boolean> {
try {
// Convert from protobuf format to shared format
const browserSettings: SharedBrowserSettings = {
viewport: {
width: request.viewport?.width || 900,
height: request.viewport?.height || 600,
},
remoteBrowserEnabled: request.remoteBrowserEnabled || false,
remoteBrowserHost: request.remoteBrowserHost || undefined,
}
// Update global state with new settings
await updateGlobalState(controller.context, "browserSettings", browserSettings)
// Update task browser settings if task exists
if (controller.task) {
controller.task.browserSettings = browserSettings
controller.task.browserSession.browserSettings = browserSettings
}
// Post updated state to webview
await controller.postStateToWebview()
return {
value: true,
}
} catch (error) {
console.error("Error updating browser settings:", error)
return {
value: false,
}
}
}
@@ -0,0 +1,22 @@
import { Controller } from ".."
import { ClineCheckpointRestore } from "../../../shared/WebviewMessage"
import { CheckpointRestoreRequest } from "../../../shared/proto/checkpoints"
import { Empty } from "../../../shared/proto/common"
import pWaitFor from "p-wait-for"
export async function checkpointRestore(controller: Controller, request: CheckpointRestoreRequest): Promise<Empty> {
await controller.cancelTask() // we cannot alter message history say if the task is active, as it could be in the middle of editing a file or running a command, which expect the ask to be responded to rather than being superseded by a new message eg add deleted_api_reqs
if (request.number) {
// wait for messages to be loaded
await pWaitFor(() => controller.task?.isInitialized === true, {
timeout: 3_000,
}).catch(() => {
console.error("Failed to init new cline instance")
})
// NOTE: cancelTask awaits abortTask, which awaits diffViewProvider.revertChanges, which reverts any edited files, allowing us to reset to a checkpoint rather than running into a state where the revertChanges function is called alongside or after the checkpoint reset
await controller.task?.restoreCheckpoint(request.number, request.restoreType as ClineCheckpointRestore, request.offset)
}
return {}
}
+1 -1
View File
@@ -9,7 +9,7 @@ export type CheckpointsMethodHandler = ServiceMethodHandler
export const registerMethod = checkpointsService.registerMethod
// Export the request handler
export const handleCheckpointsDiffServiceRequest = checkpointsService.handleRequest
export const handleCheckpointsServiceRequest = checkpointsService.handleRequest
// Register all checkpoints methods
registerAllMethods()
@@ -4,9 +4,11 @@
// Import all method implementations
import { registerMethod } from "./index"
import { checkpointDiff } from "./checkpointDiff"
import { checkpointRestore } from "./checkpointRestore"
// Register all checkpoints service methods
export function registerAllMethods(): void {
// Register each method with the registry
registerMethod("checkpointDiff", checkpointDiff)
registerMethod("checkpointRestore", checkpointRestore)
}
@@ -0,0 +1,55 @@
import { Controller } from ".."
import { RuleFileRequest, RuleFile } from "@shared/proto/file"
import { FileMethodHandler } from "./index"
import {
createRuleFile as createRuleFileImpl,
refreshClineRulesToggles,
} from "@core/context/instructions/user-instructions/cline-rules"
import * as vscode from "vscode"
import * as path from "path"
import { handleFileServiceRequest } from "./index"
import { cwd } from "@core/task"
/**
* Creates a rule file in either global or workspace rules directory
* @param controller The controller instance
* @param request The request containing filename and isGlobal flag
* @returns Result with file path and display name
* @throws Error if operation fails
*/
export const createRuleFile: FileMethodHandler = async (controller: Controller, request: RuleFileRequest): Promise<RuleFile> => {
if (typeof request.isGlobal !== "boolean" || typeof request.filename !== "string" || !request.filename) {
console.error("createRuleFile: Missing or invalid parameters", {
isGlobal: typeof request.isGlobal === "boolean" ? request.isGlobal : `Invalid: ${typeof request.isGlobal}`,
filename: typeof request.filename === "string" ? request.filename : `Invalid: ${typeof request.filename}`,
})
throw new Error("Missing or invalid parameters")
}
const { filePath, fileExists } = await createRuleFileImpl(request.isGlobal, request.filename, cwd)
if (!filePath) {
throw new Error("Failed to create rule file.")
}
if (fileExists) {
vscode.window.showWarningMessage(`Rule file "${request.filename}" already exists.`)
// Still open it for editing
await handleFileServiceRequest(controller, "openFile", { value: filePath })
} else {
await refreshClineRulesToggles(controller.context, cwd)
await controller.postStateToWebview()
await handleFileServiceRequest(controller, "openFile", { value: filePath })
vscode.window.showInformationMessage(
`Created new ${request.isGlobal ? "global" : "workspace"} rule file: ${request.filename}`,
)
}
return RuleFile.create({
filePath: filePath,
displayName: path.basename(filePath),
alreadyExists: fileExists,
})
}

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