Compare commits

...
Author SHA1 Message Date
Elephant Lumps 370b774c14 changeset 2025-05-19 17:18:04 -07:00
Elephant Lumps 557c1549be centralize navigation message handling in the extension state context 2025-05-19 17:17:23 -07:00
Tomás Barreiro c535a5ec73 Fail the workflow on webview test errors (#3275)
* do not exit with status code 0 if tests fail

* fix broken tests

* use a data-testid to find the button

* Fix API options test
2025-05-19 23:22:49 +05:30
canvrno 644280bbb4 copyToClipboard protobus migration (#3615) 2025-05-19 10:37:34 -07:00
EvanandElephant Lumps 43357c1100 Migrate restartMcpServer protobus (#3606)
* migrate restartMcpServer

* changeset

* remove markdown file

* use stringRequest

* fix type

---------

Co-authored-by: Elephant Lumps <celestial_vault@Elephants-MacBook-Pro.local>
2025-05-18 17:13:18 -07:00
canvrno eb19731843 taskCompletionViewChanges protobus migration (#3588) 2025-05-18 13:30:33 -07:00
github-actions[bot] 95750f8c9c v3.16.1 Release Notes
v3.16.1 Release Notes
2025-05-17 17:43:34 -07:00
12820a4042 Improve Gemini Retry Handling UI and UX (#3589)
* Feat: Display API auto-retry status in chat UI

This commit enhances user experience by providing real-time feedback
on automatic API request retries directly within the chat interface.
When an API request encounters a retriable error (e.g., 429), the UI
will now indicate that a retry is in progress, showing the current
attempt, maximum attempts, and delay until the next attempt.

Key changes:
- Modified the `withRetry` decorator in `src/api/retry.ts` to accept
  an `onRetryAttempt` callback. This callback is invoked before each
  retry, passing details like attempt number, max retries, delay, and
  the error that triggered the retry.
- `Task` (`src/core/task/index.ts`) now provides this callback to API
  handlers. It updates the `api_req_started` message in `clineMessages`
  with `retryStatus` information and posts the updated state to the
  webview. It also clears retry status if retries are exhausted.
- The `ChatRow.tsx` component in the webview UI has been updated to
  display this retry status (e.g., "Retrying (attempt X of Y, next in Zs)...").
  If retries are exhausted, the standard error display is shown.
- Data structures in `src/shared/` (ExtensionMessage, api, proto/file)
  were updated to include `retryStatus` and the `onRetryAttempt` callback.
- Added test code to `GeminiHandler` (`src/api/providers/gemini.ts`) to
  simulate 429 errors, allowing for easier testing and verification of
  the retry feedback mechanism.

* Remove TaskTimeLine altogether

* Remove TaskTimeLine altogether

* Update src/core/task/index.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: ellipsis-dev[bot] <65095814+ellipsis-dev[bot]@users.noreply.github.com>
2025-05-17 17:28:25 -07:00
Frostbourne 8e3adb42d6 Auto approve toggle switch (#3592)
* Add Enable AA button, rename toggle all, rm icons from bar

* Fix auto-approve bar not working and centralize feature

* move tooltip

* changeset
2025-05-17 17:26:59 -07:00
AraandCline Evaluation 8ab35a5b06 fix: Address memory leak by bypassing subscribeToState gRPC stream for state updates (#3597)
* fix: Address memory leak by bypassing subscribeToState gRPC stream for state updates

* Remove TaskTimeLine altogether

* Remove TaskTimeLine altogether

---------

Co-authored-by: Cline Evaluation <cline@example.com>
2025-05-17 17:12:35 -07:00
Sarah Fortune ba64d9fafb Don't use symlinks in the standalone distribution zip. (#3582)
Don't install vscode with file:./vscode because it creates a
symlink which is not portable for the distribution.
2025-05-17 14:52:19 -07:00
canvrno 2ba2b5b264 fetchOpenGraphData protobus migration (#3549) 2025-05-17 14:52:02 -07:00
canvrno 0dad8e178a [PROTOBUS] Move resetState to protobus (#3573)
* resetState protobus migration

* changeset
2025-05-17 14:51:27 -07:00
canvrno 1470563142 taskFeedback protobus migration (#3590) 2025-05-17 14:49:55 -07:00
github-actions[bot] 0ca16961ee v3.16.0 Release Notes
v3.16.0 Release Notes
2025-05-16 16:54:28 -07:00
canvrno 8d8452e668 [PROTOBUS] Move askResponse to protobus (#3539)
* askResponse protobus migration

* Standalone script updated
2025-05-16 12:29:33 -07:00
Matthew Rogers 6c18d5154f fix: permit use of global endpoint for vertex ai (#3469) 2025-05-17 00:07:12 +05:30
EvanandElephant Lumps aabe4ae1e1 Check if new user (#3586)
* add detection for new users for intro component

* fix lint issue

* changeset

* remove redundant fragment

---------

Co-authored-by: Elephant Lumps <celestial_vault@Elephants-MacBook-Pro.local>
2025-05-16 23:43:08 +05:30
ToshiiandCline Evaluation 5147e28aaf workflows (#3540)
* remove workflows subdirectory from cline local toggles

* set workflow toggles

* pre-updating the rules deletion logic

* delete file logic

* integration with task

* words

* pre-updating storage structure of workflows

* workflow menu items, no regex

* slash menu scrolling

* menu buttons

* placeholder

* match command base

* regex

* nit

* slash menu click outside

* changeset

* fixing linter warning

* better UI/UX

---------

Co-authored-by: Cline Evaluation <cline@example.com>
2025-05-15 22:20:20 -07:00
Dimosthenis Kaponis c6e8b04b86 feat: Enhance HistoryPreview component with collapsible/expandable ta… (#3534)
* feat: Enhance HistoryPreview component with collapsible/expandable task history view

* fix: Update font size for empty state/'No recent tasks' message in HistoryPreview component
2025-05-15 21:38:53 -07:00
Tomás Barreiro c0b3c69a8f Consider the previous message as last if the last is a checkpoint (#3571) 2025-05-15 20:55:38 -07:00
EvanandElephant Lumps 080ed7c1c6 Add Extension Recommendation (#3530)
* add tailwind css intelliSense rec

* changeset

---------

Co-authored-by: Elephant Lumps <celestial_vault@Elephants-MacBook-Pro.local>
2025-05-15 20:53:14 -07:00
canvrno 570ece3284 selectImages protobus migration (#3575) 2025-05-15 18:58:58 -07:00
Frostbourne 8f6f6464a0 Inject react-devtools (#3569) 2025-05-15 15:43:06 -07:00
Sarah Fortune 8c565b5a7c Run the cline extension as a standalone process outside of vscode. (#3535)
* Add standalone cline server.

Add directory standalone/ with the scripts to generate
a cline instance that runs a gRPC service for the proto bus.

* Rm unused dependencies

* Build standalone extension

Build stubs for the whole vscode SDK.

Import extension.js instead of putting everything in one file.

Move all the files the extension needs at runtime in files/
  Use local packages for vscode and stub-utils instead of module alias.
  Move vscode-impls into the vscode module.
  Create separate package.json for the standalone extension in files/.

* Handlers for gRPC requests

Add code to the bottom of extension.js to export the gRPC handlers.
Add a wrapper to the handlers to catch and log extensions, otherwise the whole server process fails.
Fix use of open module.

* Standalone gRPC server

Export handers from the extension.
Add reflection and healthcheck to the server.
Add vscode launch file for standalone server.

* Fix formatting

* Better error handling in the server template.

Exit if the server could not bind to the port.
Use internal error code if exception is thrown.

* Formatting

* Stop using google-protobuf npm module to generate JS for protos

The code generated by google-protobuf cannot serialize protos from plain objects. It needs the protos to be class instances created with ProtoExample.create().
But, the protos created in the extension are just POJOs.
Use protoLoader instead which is fine with plain objects.
Protoloader is also the method used in the grpc JS documentation: https://grpc.io/docs/languages/node/basics/#loading-service-descriptors-from-proto-files

* Rm proto that was removed in cline/cline

* Rm old protos when building standalone extension.

* Log gRPC requests

* feat(standalone): implement TypeScript gRPC-based standalone extension

The major improvement is that the gRPC implementation is now written in TypeScript instead of JavaScript, and the standalone extension is compiled together with the original extension rather than using the compiled JS output. This provides full type safety throughout the codebase and prevents issues with the TypeScript compiler renaming handlers during compilation, making the system more robust and maintainable.

- Add new standalone implementation files in src/standalone/ directory using TypeScript
- Implement gRPC server setup in extension-standalone.ts with full type safety
- Generate server setup code with service registrations
- Update build script to support the new standalone architecture
- Reorganize runtime files from standalone/files/ to standalone/runtime-files/
- Replace template-based server generation with gRPC service registration

* Fix issues when doing clean build

Use correct build dir in esbuild.js
Remove undefined type.

* Add handler for gRPC methods with streaming response.

Add a handler-wrapper for rpc's with streaming responses.

Fix issue where grpc-js won't deserialize protos in camelcase. It is the default
for generated code for protos to use camelcase (keepCase: false), but I cannot find
where is being set for the proto serializations to keep the case. For now, just convert the
properties of the proto messages to snake case. This is not a good
solution, but trying to fix this is time sink.

* Formatting

* Add streaming response support to the script that generates setup-server.ts

Add types for the handlers.

* Formatting

* Fix case conversion for gRPC requset protos as well.

Convert snake case to camelcase for incoming request protos.

* formatting

* Improve build process / building for standalone extension

Add separate configs for the extension and the standalone in the esbuild config.
Modules that use __dirname to load files at runtime are marked as external in the build config.
Rename vscode-impls to vscode-context.
Remove unecessary files from the standalone runtime.

* Rename extension-standalone.js to standalone.js

* Move generate-server-setup script to protos dir.

Add the script the npm target `protos`, so it is run when the protos are regenerated.

* formatting

* Add a post build step for the npm run target `protos` to format the generated files.

* Move generate-server-setup to scripts directory

* Add a JS script to package the standalone build, replacing the shell script.

Add a post build step for the standalone target that:
    * copies the vscode module files into the output directory.
    * checks that native modules are not included in the output
    * creates a zip of the build.

* Rm files that were included from merge by mistake

* Move scripts from standalone in scripts directory

Remove unused package.json files from standalone/

* Update scripts and launch.json to use correct paths

* During build install external modules in the dist directory.

Add package.json for the distribution.
Set the node path for the vscode launch config.
Make the prettier silent during `npm run protos`

* Fix ellipsis suggestions
2025-05-15 12:04:46 -07:00
AraandCline Evaluation cd1ff2ad25 Refactor reasoning effort option and checkpoint handling (#3454)
• Replace "o3MiniReasoningEffort" with "reasoningEffort" in API providers
• Remove deprecated configuration properties from package.json
• Guard checkpoint tracker initialization and saving using the enableCheckpoints flag

Co-authored-by: Cline Evaluation <cline@example.com>
2025-05-15 22:24:16 +05:30
github-actions[bot] d2979631d8 v3.15.5 Release Notes
v3.15.5 Release Notes
2025-05-14 21:20:15 -07:00
Frostbourne 4dfc1358c5 Migrate Task Timeline tooltip to HeroUI (#3547)
* Task Timeline tooltip heroui migration

* decrease closeDelay, and changeset
2025-05-14 21:01:20 -07:00
Tomás Barreiro 6a96c183a3 Handle Gemini Rate Limits (#3532) 2025-05-14 20:23:13 -07:00
pashpashpashandCline Evaluation 9df023b9d0 reverting closing diff edit view because it didnt help gray screen issues (#3546)
Co-authored-by: Cline Evaluation <cline@example.com>
2025-05-14 20:06:07 -07:00
pashpashpashandCline Evaluation 19e4387b86 Optimizing memory management for task timeline via virtuoso (#3545)
* optimizing memory management for task timeline via virtuoso

* removing logs

---------

Co-authored-by: Cline Evaluation <cline@example.com>
2025-05-14 19:54:24 -07:00
Saoud Rizwan ab01a518d1 Allow blank issues (#3543) 2025-05-14 19:29:27 -07:00
a66724e312 Refactor auto approve menu to modal (#3537)
* refactor auto approval menu to modal

* changeset

* move constants to shared location; change chevron dynamically; remove useless notes

* address comments

* improve spacing

---------

Co-authored-by: Elephant Lumps <celestial_vault@Elephants-MacBook-Pro.local>
Co-authored-by: frostbournesb <frostbournesb@protonmail.com>
2025-05-14 19:08:53 -07:00
github-actions[bot] cc56486814 v3.15.4 Release Notes
v3.15.4 Release Notes
2025-05-14 16:32:14 -07:00
Dennis Bartlett 277b20a1b2 Add gemini model back to vertex provider (#3538) 2025-05-14 16:27:08 -07:00
Ara 55d12d7556 feat: Add performance telemetry for Gemini API streams (#3523) 2025-05-14 11:01:44 -07:00
canvrno a527acc56c Feat: Workspace filter in Task History View (#3476)
* Filter tasks to current workspace

* Switched custom radio button to tailwind
2025-05-14 10:50:09 -07:00
Sarah Fortune dc1d7f51cb Create proto descriptor set in build-protos.js script. (#3524)
* Create proto descriptor set in build-protos.js script.

Create the descriptor set that will be used by the standalone cline service.
Add the standalone dist directory to the gitignore.
Only call protoc once when generating typescript files, instead of for each file separately.

* Fix undefined var in error message

* Inline the exec options
2025-05-13 17:28:06 -07:00
4ff7e06044 Changeset version bump (#3490)
* changeset version bump

* Updating CHANGELOG.md format

* ready for hotfix release

* language

---------

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
Co-authored-by: github-actions <github-actions@github.com>
Co-authored-by: Cline Evaluation <cline@example.com>
2025-05-13 16:27:35 -07:00
Dennis Bartlett 2968c8d99c Fix API Options Types in Tests (#3522) 2025-05-13 16:14:21 -07:00
pashpashpashandCline Evaluation c617d2550e fixing parsing v2 thanks to @cte (#3520)
* fixing parsing v2 thanks to @cte

* fixing parsing v2 thanks to @cte

* cleaner PR

---------

Co-authored-by: Cline Evaluation <cline@example.com>
2025-05-13 15:58:29 -07:00
pashpashpashandCline Evaluation 7937530c74 Remove free gemini models (#3494)
* removing free gemini provider

* changeset

---------

Co-authored-by: Cline Evaluation <cline@example.com>
2025-05-13 15:57:19 -07:00
Frostbourne 3657e903f5 Auto-approve menu stylistic fixes (#3504)
* marginal improvements

* undo forbidding enable all favorite

* changeset
2025-05-13 15:42:10 -07:00
0fcab4d989 Fix/chrome remote debugging user data dir (#3492)
* fix: Add required --user-data-dir flag when launching Chrome with remote debugging port

When Chrome is launched with the --remote-debugging-port flag, it requires a non-default user data directory to be specified using the --user-data-dir flag. Without this flag, Chrome shows the error 'DevTools remote debugging requires a non-default data directory' and the debug port is not opened.

This fix adds the --user-data-dir flag when launching Chrome with the remote debugging port, which resolves the 'Chrome was launched but debug port is not responding' error.

* Add changeset for Chrome remote debugging fix

* fix: Add required --user-data-dir flag when launching Chrome with remote debugging port

* Update src/services/browser/BrowserSession.ts

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

* Revert "Update src/services/browser/BrowserSession.ts"

This reverts commit 5dbd82aea2.

* import os, quote path arg

* apparently quotes are bad

* probably dont need the whole warning and relaunch flow now

* rename button labels to launch browser

---------

Co-authored-by: Andrei Eternal <garoth@gmail.com>
Co-authored-by: ellipsis-dev[bot] <65095814+ellipsis-dev[bot]@users.noreply.github.com>
Co-authored-by: Andrei Edell <andrei@nugbase.com>
2025-05-14 00:59:31 +05:30
Trevor Hudson afb64c896e add boostrap (#3502)
* add boostrap

* make sure machine ID is there
2025-05-13 11:47:27 -07:00
canvrno 65f1b05420 FIX: Detect directory change when reusing active terminals (#3503)
* Added confirmation of a sucessful cd prior to executing commands in active terminals

* typo fix, fine tuning

* cleanup
2025-05-13 01:27:27 -07:00
Andrei EternalandAndrei Edell 8f37543800 add arm rollup to optional deps so cline can build on my arm linux (#3498)
Co-authored-by: Andrei Edell <andrei@nugbase.com>
2025-05-12 20:18:45 -07:00
canvrno abbe40ee9c [PROTOBUS] Move downloadMcp to protobus (#3487)
* downloadMcp protobus migration

* added setIsDownloading(false) to error handling
2025-05-12 20:17:47 -07:00
canvrno 5c082762c4 toggleFavoriteModel protobus migration (#3488) 2025-05-12 20:17:38 -07:00
4a230ad878 Add Fireworks API Provider (#3496)
* initial

* finishing touches

* Update webview-ui/src/utils/validate.ts

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

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

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

* requested changes

* fix url

* fix vars

* Update webview-ui/src/components/chat/ChatTextArea.tsx

Co-authored-by: Dennis Bartlett <bartlett.dc.1@gmail.com>

* Update fireworks API link

* Improve margins

---------

Co-authored-by: Matt Apperson <me@mattapperson.com>
Co-authored-by: ellipsis-dev[bot] <65095814+ellipsis-dev[bot]@users.noreply.github.com>
Co-authored-by: Dennis Bartlett <bartlett.dc.1@gmail.com>
2025-05-12 19:59:28 -07:00
pashpashpashandCline Evaluation 94c432f3f3 Activation Events (#3491)
* adding activation events so cline is activated when vs code is open

* changeset

---------

Co-authored-by: Cline Evaluation <cline@example.com>
2025-05-12 17:01:16 -07:00
Toshii d88c07c932 PROTO refactor condense tool (#3489)
* proto for condense

* changeset

* condense text
2025-05-12 16:41:13 -07:00
5ee5577010 Changeset version bump (#3453)
* changeset version bump

* Updating CHANGELOG.md format

* changelog + version

* changelog

---------

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
Co-authored-by: github-actions <github-actions@github.com>
Co-authored-by: Cline Evaluation <cline@example.com>
2025-05-12 15:53:53 -07:00
ksmkzs 01877c1629 fix: prevent IME composition Enter from auto‑sending edited message (#3477) 2025-05-12 15:37:57 -07:00
Toshii f8a7b563aa PROTO refactor reportbug (#3485)
* protos report bug

* changeset
2025-05-12 15:35:31 -07:00
Trevor Hudson 915555f80f Trevhud/auto approve (#3486)
* ship with good defaults

* show items that are checked

* add close button at bottom

* changeset
2025-05-12 15:19:06 -07:00
AraandCline Evaluation 26eafd96dd fix: Resolve all different copy paste issues once and for all (#3443)
* Enhance copy functionality in ChatView to handle selections within code blocks. If the selection is inside a <pre><code> block, copy plain text; otherwise, convert HTML to Markdown before copying. This improves user experience when copying code snippets.

* Make jumps better please

---------

Co-authored-by: Cline Evaluation <cline@example.com>
2025-05-12 15:14:30 -07:00
Trevor Hudson e504b9d414 Trevhud/telem defaults (#3449)
* fresh install mode

* add nocapture

* add ui host

* changeset
2025-05-12 13:58:25 -07:00
Toshii 312777ddc5 Remove explicit caching for gemini in OR / Cline provider (#3470)
* remove explicit cache

* changeset
2025-05-12 13:04:19 -07:00
EvanandElephant Lumps c79acf5ffe Disable breaking out of diff auto scroll (#3473)
* disable breaking out of auto scroll

* changeset

---------

Co-authored-by: Elephant Lumps <celestial_vault@Elephants-MacBook-Pro.local>
2025-05-12 12:37:05 -07:00
Shravan Vadeghar 7d5d347cdd feat: Add optimized V2 parser for assistant messages (#3425)
This commit introduces `parseAssistantMessageV2`, a new function designed to parse assistant message strings containing text and XML-like tool usage tags (`<tool_name>...</tool_name>`, `<param_name>...</param_name>`).

Motivation:
The original parser (`V1`) used a character-by-character accumulator, which could lead to performance overhead due to repeated string concatenations and checks (`endsWith`). V2 aims to improve parsing efficiency.

Implementation Details (V2 vs V1):
- V2 iterates through the string using an index and checks for tags using `startsWith` with calculated offsets, avoiding the V1 accumulator.
- It tracks start indices for text, tools, and parameters, performing `slice` operations only when a block is completed or the string ends.
- Known tool and parameter opening tags are precomputed into Maps for potentially faster lookups.
- Special handling for nested tags within `write_to_file`/`new_rule` content parameters is preserved using `indexOf`/`lastIndexOf`.

Other Changes:
- The original parser implementation has been renamed to `parseAssistantMessageV1`.
2025-05-12 12:21:44 -07:00
pashpashpash 95cc15a142 Releasing memory after every diff edit - greyscreen fix? (#3459) 2025-05-12 11:17:13 -07:00
Sarah Fortune f7d464a51d Add request param to accountLoginClicked. (#3471)
All the handlers need to have the same signature f(controller, request),
otherwise the typechecker will be unhappy when setting up the gRPC server.
2025-05-12 18:52:58 +01:00
Hiroki Nakashima a6c4c0c0ea feat: Add detailed configuration options for LiteLLM provider (#2056)
* add configuration to litellm

* update defualt model name

* fix typo

* add changeset

* update default model

* remove model cost setting

* add temperature setting

* remove redandant comment

* use const

* handle model change

* fix unsaved bug
2025-05-12 23:10:44 +05:30
AraandCline Evaluation 976a8fa85e Migrate Browsertools settings to the webview from Vscode settings (#3444)
* Removing redundant settings

* Add chromeExecutablePath to BrowserSettings and UpdateBrowserSettingsRequest

- Introduced optional chromeExecutablePath field in BrowserSettings and UpdateBrowserSettingsRequest.
- Updated updateBrowserSettings function to merge new settings with existing ones, preserving previous values.
- Enhanced BrowserSession to check for the chromeExecutablePath in global state.
- Modified BrowserSettingsSection to include a UI input for specifying the Chrome executable path.

* Removing browser stuff

* Removing browser stuff

* Removing browser stuff

* Removing browser stuff

* Add cute animation

* Add cute animation

* Add cute animation

* Add cute animation

* Add cute animation

* Add cute animation

* Add cute animation

* adding stuff

---------

Co-authored-by: Cline Evaluation <cline@example.com>
2025-05-12 23:06:37 +05:30
canvrno 33413e91c6 refreshRequestyModels protobus migration (#3422) 2025-05-11 22:42:14 -07:00
Sarah Fortune 801c59e75e Use correct type for return value of accountLoginClicked. (#3447)
Return type should be cline.String not String from JS global namespace.
Use await when calling async function vscode.env.openExternal.
2025-05-11 22:39:36 -07:00
Trevor Hudson df9c8e2e80 Trevhud/vite auto (#3448)
* move enable all

* add tooltip

* changeset

* fix spacing and move notifications to other section
2025-05-11 16:47:59 -07:00
canvrno 4d480ea3fe Add telemetry enable/disable controls by category to TelemetryService (#3450) 2025-05-11 14:53:33 -07:00
7e26d1117a Changeset version bump (#3440)
* changeset version bump

* Updating CHANGELOG.md format

* package lock

* changelog

* brackets

---------

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
Co-authored-by: github-actions <github-actions@github.com>
Co-authored-by: Cline Evaluation <cline@example.com>
2025-05-10 19:39:04 -05:00
b04810c480 increased error timeout from 500 -> 5000 for windows users (#3439)
* increased error timeout from 500 -> 5000

* conditionally setting to 5000 if windows

* Create rude-bats-brush.md

---------

Co-authored-by: Cline Evaluation <cline@example.com>
Co-authored-by: Dennis Bartlett <bartlett.dc.1@gmail.com>
2025-05-10 17:23:14 -07:00
github-actions[bot] 5255da936f v3.15.0 Release Notes
v3.15.0 Release Notes
2025-05-09 17:18:17 -07:00
EvanandElephant Lumps 248871d770 Simple home header (#3424)
* simplified home header

* changeset

* add variable color logo for different themes

* random slash

---------

Co-authored-by: Elephant Lumps <celestial_vault@Elephants-MacBook-Pro.local>
2025-05-09 17:26:07 -05:00
nutstore-devandweiwenhan c634bf6368 fix: make sure clineIgnoreController initialized before task start (#3410)
Co-authored-by: weiwenhan <weiwenhan@cn.nutstore.net>
2025-05-09 13:21:02 -07:00
Ara f5dbfaf234 fix: Restore native copy functionality in chat input text area (#3416)
* fix: Restore native copy functionality in chat input text area

* fix: Restore native copy functionality in chat input text area
2025-05-09 10:32:06 -07:00
Trevor Hudsonandellipsis-dev[bot] aa4d97f05d Trevhud/auto approve menu (#3405)
* improved auto-approve

* roll back chevron

* changeset

* add pills

* back to checkboxes

* turn on parent when subAction is turned on

* use vscode colors

* Update webview-ui/src/components/chat/auto-approve-menu/AutoApproveMenu.tsx

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

* Update webview-ui/src/components/chat/auto-approve-menu/AutoApproveMenu.tsx

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

* improve responsiveness

* remove opacity animation

---------

Co-authored-by: ellipsis-dev[bot] <65095814+ellipsis-dev[bot]@users.noreply.github.com>
2025-05-09 22:47:14 +05:30
Toshii c20a513b70 prompt wording (#3409)
* base

* changeset
2025-05-09 01:19:02 -07:00
738c03ff3e slash command report bug (#3387)
* slash command report bug

* nits

* nits

* sigh, portible way to open urls with proper escaping because vs code api is broken

* only asking for non-algorithmically derived info

* Update webview-ui/src/components/chat/ChatView.tsx

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

* gather user system info

* Revert "gather user system info"

This reverts commit fb16c72224.

---------

Co-authored-by: Cline Evaluation <cline@example.com>
Co-authored-by: pashpashpash <nik@cline.bot>
Co-authored-by: ellipsis-dev[bot] <65095814+ellipsis-dev[bot]@users.noreply.github.com>
2025-05-09 01:10:44 -07:00
canvrno e8a68c49ce [PROTOBUS] Move refreshOpenAiModels to protobus (#3403)
* refreshOpenAiModels protobus migration

* changeset

* Debounce OpenAi model list refresh when users are typing

* debounce cleanup
2025-05-08 23:33:12 -07:00
pashpashpashandCline Evaluation 961400fdca Fixing task lockout after shell integration stream bug leading to terminal hang (#3404)
* shell timeout bug throw error

* changeset

* explanation in comments

---------

Co-authored-by: Cline Evaluation <cline@example.com>
2025-05-08 17:23:00 -10:00
canvrno 8827b167ca [PROTOBUS] Move refreshOpenRouterModels to protobus (#3401)
* refreshOpenRouterModels protobus migration

* changeset

* cleanup

* Ellipsis inspired changes

* one small change
2025-05-08 20:14:49 -07:00
Andrei EternalandAndrei Edell e1389a62c7 run prettier correctly on generated protos (#3399)
Co-authored-by: Andrei Edell <andrei@nugbase.com>
2025-05-08 13:21:54 -10:00
canvrno 7b416ccc70 Feat: Task Favorites ️ (#3392)
* Task Favorites

* Task management docs
2025-05-08 15:49:05 -07:00
Alex 29f3cfa894 Update index.css (#3367) 2025-05-09 03:18:53 +05:30
Araandellipsis-dev[bot] 978f34e30b Supporting implicit Caching in Gemini (#3394)
* Refactor GeminiHandler to remove caching logic and update pricing structure

* Removed the enhanced caching system and related logic from GeminiHandler.
* Updated the pricing structure for cache reads in both geminiModels and vertexModels.
* Simplified the message creation process by eliminating unnecessary cache checks and operations.

* Fixing Gemini and vertex cache pricing

* Fixing Gemini and vertex cache pricing

* Update src/api/providers/gemini.ts

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-09 03:17:41 +05:30
canvrno 445e25221a [PROTOBUS] Move requestVsCodeLmModels to protobus (#3344)
* Task Favorites

* getOllamaModels protobus migration

* VsCodeLmModels protobus migration

* cleanup
2025-05-08 10:50:23 -10:00
Araandellipsis-dev[bot] 489a05117c Increasing file sizes for files that can be read by cline (#3396)
* Increasing file sizes for files that can be read by cline

* Update src/integrations/misc/extract-text.ts

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

* Increasing file sizes for files that can be read by cline

---------

Co-authored-by: ellipsis-dev[bot] <65095814+ellipsis-dev[bot]@users.noreply.github.com>
2025-05-08 12:55:40 -07:00
WinterYukky e572ee44f9 fix(bedrock): application inference profile is not work (#3388)
* fix(bedrock): application inference profile is not work

* chore: add change set

* chore: change the encoding condition to whether it contains a slash
2025-05-09 00:26:05 +05:30
pashpashpashandCline Evaluation f4e14bfe3b removing sparkle from command name (#3395)
Co-authored-by: Cline Evaluation <cline@example.com>
2025-05-09 00:16:40 +05:30
watany bddc1b5e96 fix(bedrock); update bedrock api (#3157)
* fix nova

* haiku

* changeset

* changeset

* clean up duplicate changeset

* commented caching write
2025-05-08 10:52:08 -07:00
pashpashpashandCline Evaluation cb0de8f17e tracking models in diff edit failures (#3297)
* tracking models in diff edit failures

* prettier

---------

Co-authored-by: Cline Evaluation <cline@example.com>
2025-05-08 12:33:29 -05:00
EvanandElephant Lumps e1a0b244de Conditionally initialize posthog webview (#3381)
* conditionally initialize posthog client webview

* changeset

---------

Co-authored-by: Elephant Lumps <celestial_vault@Elephants-MacBook-Pro.local>
2025-05-08 12:08:40 -05:00
Dennis Bartlett a9d5411bf0 Revert "Update deployer team name (#3377)" 2025-05-08 06:57:18 -05:00
Dennis Bartlett 16af9125ec Update variable name (#3384) 2025-05-08 06:51:55 -05:00
Ara 2792e7698f Raise Errors when users try to upload images larger than 7500x7500 pixels (#3336)
* Adding iamge dimension check

* Adding iamge dimension check

* Adding iamge dimension check

* Adding iamge dimension check

* Adding iamge dimension check

* Adding iamge dimension check
2025-05-07 23:48:04 -07:00
d02e5a89e5 fix excessive markdown format character escaping (#3355)
* fix excessive markdown format character escaping

* add changeset

* made it a little more robust

---------

Co-authored-by: Wesley Smith <wes@neofactory.ai>
Co-authored-by: Cline Evaluation <cline@example.com>
2025-05-07 22:31:31 -07:00
Dennis Bartlett 20f19917d3 Add org to team affiliation check (#3380) 2025-05-08 00:01:42 -05:00
EvanandElephant Lumps 7e5cd52864 Always allow textarea typing (#3356)
* enable text area while cline is doing stuff

* changeset

* add sendingDisabled to dependency array

---------

Co-authored-by: Elephant Lumps <celestial_vault@Elephants-MacBook-Pro.local>
2025-05-07 22:01:07 -07:00
pashpashpashandCline Evaluation 4622ad767b Copy buttons (#3373)
* copy button in task header

* changeset

* added copy buttons to assistant messages that show up on hover

* added aria

---------

Co-authored-by: Cline Evaluation <cline@example.com>
2025-05-07 21:59:42 -07:00
Dennis Bartlett 96048d5ac5 Update deployer team name (#3377)
* Update deployer team name

* Create clever-balloons-wave.md
2025-05-07 23:37:33 -05:00
Ara facec93082 Adding Mistral 3 medium model (#3366)
* Fixing Gemini and vertex cache pricing

* Fixing Gemini and vertex cache pricing
2025-05-08 05:46:09 +05:30
Saoud Rizwan c040be9eb1 Disables autocaptures when initializing feature flags 2025-05-07 15:55:33 -05:00
EvanandElephant Lumps 8d3cf53289 Docs: image links (#3350)
* add cdn image links

* changeset

---------

Co-authored-by: Elephant Lumps <celestial_vault@Elephants-MacBook-Pro.local>
2025-05-07 13:41:42 -05:00
Trevor Hudson 83c4a82e6d Diable auto track (#3364)
* disable autocatpure

* changeset
2025-05-07 11:32:33 -07:00
250 changed files with 16024 additions and 3269 deletions
+5
View File
@@ -0,0 +1,5 @@
---
"claude-dev": minor
---
Put all the navigation state and message handling and navigation functions in the extension state context instead of the app.tsx
-5
View File
@@ -1,5 +0,0 @@
---
"claude-dev": patch
---
Add the o4-mini model in the isOminiModel
-5
View File
@@ -1,5 +0,0 @@
---
"claude-dev": patch
---
Allow option to collect events to send them in a bundle to avoid sending too many events
-5
View File
@@ -1,5 +0,0 @@
---
"claude-dev": minor
---
add open ai cache to ui
-5
View File
@@ -1,5 +0,0 @@
---
"claude-dev": patch
---
Moved rule file conversions
-5
View File
@@ -1,5 +0,0 @@
---
"claude-dev": minor
---
suggested model exists again
-5
View File
@@ -1,5 +0,0 @@
---
"claude-dev": patch
---
getRelativePaths protobus migration
-5
View File
@@ -1,5 +0,0 @@
---
"claude-dev": patch
---
getOllamaModels protobus migration
-5
View File
@@ -1,5 +0,0 @@
---
"claude-dev": minor
---
Add FeatureFlagProvider service for the Node.js extension side
-5
View File
@@ -1,5 +0,0 @@
---
"claude-dev": patch
---
Add confirmation dialog to Delete All History button
-5
View File
@@ -1,5 +0,0 @@
---
"claude-dev": minor
---
breakpoint just in system prompt for gemini for OR and cline provider
-5
View File
@@ -1,5 +0,0 @@
---
"claude-dev": minor
---
fetch cache details from generation endpoint
-5
View File
@@ -1,5 +0,0 @@
---
"claude-dev": patch
---
Bump ollama from 0.5.13 to 0.5.15
+5
View File
@@ -0,0 +1,5 @@
---
"claude-dev": patch
---
taskCompletionViewChanges protobus migration
-5
View File
@@ -1,5 +0,0 @@
---
"claude-dev": minor
---
Add npm script for issue creation
-5
View File
@@ -1,5 +0,0 @@
---
"claude-dev": minor
---
Migrate more info section to new docs
+5
View File
@@ -0,0 +1,5 @@
---
"claude-dev": patch
---
copyToClipboard protobus migration
-5
View File
@@ -1,5 +0,0 @@
---
"claude-dev": patch
---
Extend ReasoningEffort to non-o3-mini reasoning models for all providers
-5
View File
@@ -1,5 +0,0 @@
---
"claude-dev": patch
---
Re-enable tests in workflow
-5
View File
@@ -1,5 +0,0 @@
---
"claude-dev": minor
---
updated gemini caching for OR and cline provider
-5
View File
@@ -1,5 +0,0 @@
---
"claude-dev": patch
---
searchFiles protobus migration
-5
View File
@@ -1,5 +0,0 @@
---
"claude-dev": minor
---
Add ability to generate commit message via cline
-5
View File
@@ -1,5 +0,0 @@
---
"claude-dev": minor
---
updated OR/cline provider to automate gemini models caching
-5
View File
@@ -1,5 +0,0 @@
---
"claude-dev": patch
---
getLmStudioModels protobus migration
-5
View File
@@ -1,5 +0,0 @@
---
"claude-dev": patch
---
adding quote reply support
-5
View File
@@ -1,5 +0,0 @@
---
"claude-dev": minor
---
Add enterprise section to new docs
-5
View File
@@ -1,5 +0,0 @@
---
"claude-dev": patch
---
Make Previous Updates in the Announcement a dropdown
-5
View File
@@ -1,5 +0,0 @@
---
"claude-dev": minor
---
Migrate prompting section to new docs
+5
View File
@@ -0,0 +1,5 @@
---
"claude-dev": minor
---
Migrate restartMcpServer to protobus
-5
View File
@@ -1,5 +0,0 @@
---
"claude-dev": minor
---
Migrate running models locally section to new docs
-5
View File
@@ -1,5 +0,0 @@
---
"claude-dev": patch
---
timestamp visualization
-5
View File
@@ -1,5 +0,0 @@
---
"claude-dev": minor
---
Allow the user to scroll when Cline is editing a file by disabling auto-scroll when the user scrolls up
-5
View File
@@ -1,5 +0,0 @@
---
"claude-dev": minor
---
Migrate MCP section to new docs
-5
View File
@@ -1,5 +0,0 @@
---
"claude-dev": minor
---
Migrate custom model config section to new docs
-5
View File
@@ -1,5 +0,0 @@
---
"claude-dev": minor
---
add ui for windsurf and cursor rules
-5
View File
@@ -1,5 +0,0 @@
---
"claude-dev": patch
---
Batch selection and deletion of tasks in history
-5
View File
@@ -1,5 +0,0 @@
---
"claude-dev": minor
---
Migrate getting-started section to new docs
-5
View File
@@ -1,5 +0,0 @@
---
"claude-dev": minor
---
Task Timeline
+1 -1
View File
@@ -209,7 +209,7 @@ class Task {
switch (chunk.type) {
case "text":
// Parse into content blocks
this.assistantMessageContent = parseAssistantMessage(chunk.text)
this.assistantMessageContent = parseAssistantMessageV2(chunk.text)
// Present blocks to user
await this.presentAssistantMessage()
break
+1 -1
View File
@@ -1,4 +1,4 @@
blank_issues_enabled: false
blank_issues_enabled: true
contact_links:
- name: ✨ Feature Request
url: https://github.com/cline/cline/discussions/categories/feature-requests?discussions_q=is%3Aopen+category%3A%22Feature+Requests%22+sort%3Atop
@@ -33,6 +33,7 @@ jobs:
uses: morfien101/actions-authorized-user@4a3cfbf0bcb3cafe4a71710a278920c5d94bb38b
with:
username: ${{ github.actor }}
org: ${{ github.repository_owner }}
team: "deployer"
github_token: ${{ secrets.GITHUB_TOKEN }}
+1 -1
View File
@@ -92,7 +92,7 @@ jobs:
cd webview-ui
# Ensure coverage dependency is installed
npm install --no-save @vitest/coverage-v8
npm run test:coverage > webview_coverage.txt 2>&1 || true
npm run test:coverage > webview_coverage.txt 2>&1
cd ..
PYTHONPATH=.github/scripts python -m coverage_check extract-coverage webview-ui/webview_coverage.txt --type=webview --github-output --verbose
+2 -1
View File
@@ -1,5 +1,6 @@
out
dist
dist-standalone
node_modules
tmp
.vscode-test/
@@ -18,4 +19,4 @@ coverage
# But don't ignore the coverage scripts in .github/scripts/
!.github/scripts/coverage/
*evals.env
*evals.env
+6 -1
View File
@@ -1,5 +1,10 @@
{
// See http://go.microsoft.com/fwlink/?LinkId=827846
// for the documentation about the extensions.json format
"recommendations": ["dbaeumer.vscode-eslint", "connor4312.esbuild-problem-matchers", "ms-vscode.extension-test-runner"]
"recommendations": [
"dbaeumer.vscode-eslint",
"connor4312.esbuild-problem-matchers",
"ms-vscode.extension-test-runner",
"bradlc.vscode-tailwindcss"
]
}
+39
View File
@@ -16,6 +16,45 @@
"IS_DEV": "true",
"DEV_WORKSPACE_FOLDER": "${workspaceFolder}"
}
},
{
"name": "Run Extension (Fresh Install Mode)",
"type": "extensionHost",
"request": "launch",
"runtimeExecutable": "${execPath}",
"args": [
"--profile-temp",
"--sync",
"off",
"--disable-extensions",
"--extensionDevelopmentPath=${workspaceFolder}",
"${workspaceFolder}"
],
"outFiles": ["${workspaceFolder}/dist/**/*.js"],
"preLaunchTask": "clean-sandbox",
"internalConsoleOptions": "openOnSessionStart",
"postDebugTask": "stop",
"env": {
"IS_DEV": "true",
"DEV_WORKSPACE_FOLDER": "${workspaceFolder}"
}
},
{
"type": "node",
"request": "launch",
"name": "Run Standalone Extension",
"skipFiles": ["<node_internals>/**"],
"sourceMaps": true,
"resolveSourceMapLocations": ["${workspaceFolder}/**", "!**/node_modules/**"],
"cwd": "${workspaceFolder}/dist-standalone",
"outFiles": ["${workspaceFolder}/dist-standalone/**/*.js"],
"preLaunchTask": "compile-standalone",
"env": {
"GRPC_TRACE": "all",
"GRPC_VERBOSITY": "DEBUG",
"NODE_PATH": "${workspaceFolder}/dist-standalone/node_modules"
},
"program": "standalone.js"
}
]
}
+16
View File
@@ -3,6 +3,16 @@
{
"version": "2.0.0",
"tasks": [
{
"label": "compile-standalone",
"type": "npm",
"script": "compile-standalone",
"group": "build",
"problemMatcher": [],
"presentation": {
"reveal": "always"
}
},
{
"label": "npm: protos",
"type": "npm",
@@ -185,6 +195,12 @@
"label": "stop",
"command": "echo ${input:terminate}",
"type": "shell"
},
{
"label": "clean-sandbox",
"type": "shell",
"dependsOn": ["watch"],
"command": "rm -rf .vscode-dev"
}
],
"inputs": [
+92
View File
@@ -1,5 +1,97 @@
# Changelog
## [3.16.1]
- Add Enable auto approve toggle switch, allowing users to easily turn auto-approve functionality on or off without losing their action settings
- Improve Gemini retry handling with better UI feedback, showing retry progress during API request attempts
- Fix memory leak issue that could occur during long sessions with multiple tasks
- Improve UI for Gemini model retry attempts with clearer status updates
- Fix quick actions functionality in auto-approve settings
- Update UI styling for auto-approve menu items to conserve space
## [3.16.0]
- Add new workflow feature allowing users to create and manage workflow files that can be injected into conversations via slash commands
- Add collapsible recent task list, allowing users to hide their task history when sharing their screen (Thanks @cosmix!)
- Add global endpoint option for Vertex AI users, providing higher availability and reducing 429 errors (Thanks @soniqua!)
- Add detection for new users to display special components and guidance
- Add Tailwind CSS IntelliSense to the recommended extensions list
- Fix eternal loading states when the last message is a checkpoint (Thanks @BarreiroT!)
- Improve settings organization by migrating VSCode Advanced settings to Settings Webview
## [3.15.5]
- Fix inefficient memory management in the task timeline
- Fix Gemini rate limitation response not being handled properly (Thanks @BarreiroT!)
## [3.15.4]
- Add gemini model back to vertex provider
- Add gemini telemetry
- Add filtering for tasks tied to the current workspace
## [3.15.3]
- Add Fireworks API Provider
- Fix minor visual issues with auto-approve menu
- Fix one instance of terminal not getting output
- Fix 'Chrome was launched but debug port is not responding' error
## [3.15.2]
- Added details to auto approve menu and more sensible default controls
- Add detailed configuration options for LiteLLM provider
- Add webview telemetry for users who have opted in to telemetry
- Update Gemini in OpenRouter/Cline providers to use implicit caching
- Fix freezing issues during rendering of large streaming text
- Fix grey screen webview crashes by releasing memory after every diff edit
- Fix breaking out of diff auto-scroll
- Fix IME composition Enter autosending edited message
## [3.15.1]
- Fix bug where PowerShell commands weren't given enough time before giving up and showing an error
## [3.15.0]
- Add Task Timeline visualization to tasks (Thanks eomcaleb!)
- Add cache to ui for OpenAi provider
- Add FeatureFlagProvider service for the Node.js extension side
- Add copy buttons to task header and assistant messages
- Add a more simplified home header was added
- Add ability to favorite a task, allowing it to be kept when clearing all tasks
- Add npm script for issue creation (Thanks DaveFres!)
- Add confirmation dialog to Delete All History button
- Add ability to allow the user to type their next message into the chat while Cline is taking action
- Add ability to generate commit message via cline (Thanks zapp88!)
- Add improvements to caching for gemini models on OpenRouter and Cline providers
- Add improvements to allow scrolling the file being edited.
- Add ui for windsurf and cursor rules
- Add mistral medium-3 model
- Add option to collect events to send them in a bundle to avoid sending too many events
- Add support to quote a previous message in chat
- Add support for Gemini Implicit Caching
- Add support for batch selection and deletion of tasks in history (Thanks danix800!)
- Update change suggested models
- Update fetch cache details from generation endpoint
- Update converted docs to Mintlify
- Update the isOminiModel to include o4-mini model (Thanks PeterDaveHello!)
- Update file size that can be read by Cline, allowing larger files
- Update defaults for bedrock API models (Thanks Watany!)
- Update to extend ReasoningEffort to non-o3-mini reasoning models for all providers (Thanks PeterDaveHello!)
- Update to give error when a user tries to upload an image larger than 7500x7500 pixels
- Update announcement so that previous updates are in a dropdown
- Update UI for auto approve with favorited settings
- Fix bug where certain terminal commands would lock you out of a task
- Fix only initialize posthog in the webview if the user has opted into telemetry
- Fix bug where autocapture was on for front-end telemetry
- Fix for markdown copy excessively escaping characters (Thanks weshoke!)
- Fix an issue where loading never finished when using an application inference profile for the model ID (Thanks WinterYukky!)
## [3.14.1]
- Disables autocaptures when initializing feature flags
## [3.14.0]
- Add support for custom model ID in AWS Bedrock provider, enabling use of Application Inference Profile (Thanks @clicube!)
@@ -36,7 +36,7 @@ Cline offers the option of utilizing AWS credentials or AWS profiles to access A
<Frame>
<img
src="/assets/robot_panel_dark.png"
src="https://storage.googleapis.com/cline_public_images/docs/assets/cline-aws-setup-markup%20(1).png"
alt="AWS Bedrock configuration in Cline settings showing profile authentication setup"
/>
</Frame>
+9 -6
View File
@@ -44,16 +44,16 @@ This guide is tailored for organizations with established GCP environments (leve
#### 2.1 Choose and Confirm a Region
Vertex AI supports eight regions. Select a region that meets your latency, compliance, and capacity needs. Examples include:
Vertex AI supports multiple regions. Select a region that meets your latency, compliance, and capacity needs. Examples include:
- **us-east5 (Columbus, Ohio)**
- **us-east1 (South Carolina)**
- **us-east4 (Northern Virginia)**
- **us-central1 (Iowa)**
- **us-west1 (The Dalles, Oregon)**
- **us-west4 (Las Vegas, Nevada)**
- **europe-west1 (Belgium)**
- **europe-west4 (Netherlands)**
- **asia-southeast1 (Singapore)**
- **global (Global)**
The Global endpoint may offer higher availability and reduce resource exhausted errors. Only Gemini models are supported.
#### 2.2 Enable the Claude 3.5 Sonnet v2 Model
@@ -76,7 +76,10 @@ Vertex AI supports eight regions. Select a region that meets your latency, compl
- Search for **Cline** and install the extension
<Frame>
<img src="/assets/robot_panel_dark.png" alt="Cline extension in VS Code" />
<img
src="https://storage.googleapis.com/cline_public_images/docs/assets/cline-extension-arrow.png"
alt="Cline extension in VS Code"
/>
</Frame>
#### 3.2 Configure Cline Settings
+1
View File
@@ -62,6 +62,7 @@
"getting-started/installing-dev-essentials",
"getting-started/model-selection-guide",
"getting-started/our-favorite-tech-stack",
"getting-started/task-management",
"getting-started/understanding-context-management",
"getting-started/what-is-cline"
]
@@ -6,7 +6,7 @@ Cline supports major cloud providers like AWS Bedrock and Google's Cloud Vertex;
For the purpose of this document, we assume your organization will use cloud-based frontier models. Cloud inference providers offer cutting-edge capabilities and the flexibility to select models which best suit your needs.
Certain scenarios may warrant using local models, including handling highly sensitive data, applications requiring consistent low-latency responses, or compliance with strict data sovereignty requirements. If your team needs to utilize local models, see [Running Local Models ](/running-local-models/read-me-first.mdx)with Cline.
Certain scenarios may warrant using local models, including handling highly sensitive data, applications requiring consistent low-latency responses, or compliance with strict data sovereignty requirements. If your team needs to utilize local models, see [Running Local Models ](/running-models-locally/read-me-first.mdx)with Cline.
---
@@ -14,9 +14,9 @@ Certain scenarios may warrant using local models, including handling highly sens
#### [IAM Security Best Practices](https://docs.aws.amazon.com/IAM/latest/UserGuide/best-practices.html) (For administrators)
#### [AWS Bedrock setup for Legacy IAM (AWS Credentials)](/custom-model-configs/aws-bedrock.mdx)
#### [AWS Bedrock setup for Legacy IAM (AWS Credentials)](/custom-model-configs/aws-bedrock-with-credentials-authentication.mdx)
#### [AWS Bedrock setup for SSO token (AWS Profile)](/custom-model-configs/aws-bedrock-w-profile-authentication.mdx)
#### [AWS Bedrock setup for SSO token (AWS Profile)](/custom-model-configs/aws-bedrock-with-profile-authentication.mdx)
#### VPC Endpoint Setup
@@ -28,12 +28,12 @@ To protect your team's data, Cline supports VPC (Virtual Private Cloud) endpoint
2. Follow the directions for [creating a VPC endpoint](https://docs.aws.amazon.com/vpc/latest/privatelink/create-interface-endpoint.html#create-interface-endpoint-aws) in the AWS console. The image below pertains to steps 4 and 5 of the AWS guide linked above.
<Frame>
<img src="/assets/robot_panel_dark.png" alt="VPC Console" />
<img src="https://storage.googleapis.com/cline_public_images/docs/assets/vpc-console.png" alt="VPC Console" />
</Frame>
3. Note the IP address of your VPC endpoint, open Cline's settings menu, and select `AWS Bedrock`from the API Provider dropdown.
4. Click the `Use Custom VPC endpoint`checkbox and enter the IP address of your VPC endpoint
<Frame>
<img src="/assets/robot_panel_dark.png" alt="VPC Settings Menu" />
<img src="https://storage.googleapis.com/cline_public_images/docs/assets/vpc-settings-menu.png" alt="VPC Settings Menu" />
</Frame>
@@ -13,7 +13,10 @@ title: "Security Concerns"
Cline operates exclusively as a client-side VSCode extension with zero server-side components. This fundamental design choice ensures that your code and data remain within your secure environment at all times. Unlike traditional AI assistants that send data to external servers for processing, Cline connects directly to your chosen cloud provider's AI endpoints, keeping all sensitive information within your infrastructure boundaries.
<Frame>
<img src="/assets/robot_panel_dark.png" alt="Cline's relationship to local and remote assets" />
<img
src="https://storage.googleapis.com/cline_public_images/docs/assets/cline-arch.png"
alt="Cline's relationship to local and remote assets"
/>
</Frame>
### Data Privacy Commitment
+9 -3
View File
@@ -28,7 +28,10 @@ After each tool use, you can:
2. Click the "Restore" button to open restore options
<Frame>
<img src="/assets/robot_panel_dark.png" alt="Checkpoint comparison and restore options" />
<img
src="https://storage.googleapis.com/cline_public_images/docs/assets/image%20(13).png"
alt="Checkpoint comparison and restore options"
/>
</Frame>
#### Rolling Back
@@ -60,7 +63,7 @@ Checkpoints let you be more experimental with Cline. While human coding is often
- 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" />
<img src="https://storage.googleapis.com/cline_public_images/docs/assets/checkpointsDemo.gif" alt="Checkpoint restore demo" />
</Frame>
### ✨ Best Practices
@@ -104,5 +107,8 @@ Perhaps you didn't get the results you wanted, thought of a better way to phrase
- Shift + Enter: Insert new line / line break
<Frame>
<img src="/assets/robot_panel_dark.png" alt="Message editing interface" />
<img
src="https://storage.googleapis.com/cline_public_images/docs/assets/message-editing.png"
alt="Message editing interface"
/>
</Frame>
@@ -7,7 +7,10 @@ title: "Plan & Act Modes: A Guide to Effective AI Development"
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" />
<img
src="https://storage.googleapis.com/cline_public_images/docs/assets/planningThenActing%20(1).gif"
alt="Use Plan to gather context before using Act to implement the plan"
/>
</Frame>
### Understanding the Modes
@@ -27,7 +30,7 @@ Plan & Act modes represent Cline's approach to structured AI development, emphas
- Can execute changes to your codebase
<Frame>
<img src="/assets/robot_panel_dark.png" alt="Act mode capabilities" />
<img src="https://storage.googleapis.com/cline_public_images/docs/assets/image%20(5).png" alt="Act mode capabilities" />
</Frame>
### Workflow Guide
@@ -39,7 +42,7 @@ Begin every significant development task in Plan mode:
In this mode:
<Frame>
<img src="/assets/robot_panel_dark.png" alt="Plan mode workflow" />
<img src="https://storage.googleapis.com/cline_public_images/docs/assets/image%20(5)%20(1).png" alt="Plan mode workflow" />
</Frame>
- Share your requirements
@@ -48,7 +51,10 @@ In this mode:
- Develop implementation strategy
<Frame>
<img src="/assets/robot_panel_dark.png" alt="Planning phase" />
<img
src="https://storage.googleapis.com/cline_public_images/docs/assets/image%20(2)%20(1)%20(1)%20(1).png"
alt="Planning phase"
/>
</Frame>
#### 2. Switch to Act Mode
@@ -56,7 +62,7 @@ In this mode:
Once you have a clear plan, switch to Act mode:
<Frame>
<img src="/assets/robot_panel_dark.png" alt="Switching to Act mode" />
<img src="https://storage.googleapis.com/cline_public_images/docs/assets/switching-to-act.gif" alt="Switching to Act mode" />
</Frame>
Act mode allows Cline to:
@@ -90,7 +96,10 @@ Complex projects often require multiple plan-act cycles:
4. Document significant decisions
<Frame>
<img src="/assets/robot_panel_dark.png" alt="Implementation best practices" />
<img
src="https://storage.googleapis.com/cline_public_images/docs/assets/image%20(3)%20(1).png"
alt="Implementation best practices"
/>
</Frame>
### Power User Tips
@@ -119,7 +128,7 @@ Complex projects often require multiple plan-act cycles:
- Executing test cases
<Frame>
<img src="/assets/robot_panel_dark.png" alt="Mode usage patterns" />
<img src="https://storage.googleapis.com/cline_public_images/docs/assets/image%20(6).png" alt="Mode usage patterns" />
</Frame>
### Contributing
+4 -1
View File
@@ -22,7 +22,10 @@ Follow these steps to get Cline up and running:
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" />
<img
src="https://storage.googleapis.com/cline_public_images/docs/assets/image%20(20).png"
alt="VS Code marketplace showing Cline extension"
/>
</Frame>
1. **Install the Extension:** Click the "Install" button next to the Cline extension.
@@ -28,7 +28,10 @@ Cline helps you manage this limitation with its Context Window Progress Bar, whi
- 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" />
<img
src="https://storage.googleapis.com/cline_public_images/docs/assets/image%20(11).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.
+67
View File
@@ -0,0 +1,67 @@
---
title: "Task Management in Cline"
description: "Learn how to effectively manage your task history, use favorites, and organize your work in Cline."
---
# Task Management
As you use Cline, you'll accumulate many tasks over time. The task management system helps you organize, filter, search, and clean up your task history to keep your workspace efficient.
## Accessing Task History
You can access your task history by:
1. Clicking on the "History" button in the Cline sidebar
2. Using the command palette to search for "Cline: Show Task History"
## Task History Features
The task history view provides several powerful features:
### Searching and Filtering
- **Search Bar**: Use the fuzzy search at the top to quickly find tasks by content
- **Sort Options**: Sort tasks by:
- Newest (default)
- Oldest
- Most Expensive (highest API cost)
- Most Tokens (highest token usage)
- Most Relevant (when searching)
- **Favorites Filter**: Toggle to show only favorited tasks
### Task Actions
Each task in the history view has several actions available:
- **Open**: Click on a task to reopen it in the Cline chat
- **Favorite**: Click the star icon to mark a task as a favorite
- **Delete**: Remove individual tasks (favorites are protected from deletion)
- **Export**: Export a task's conversation to markdown
## ⭐ Task Favorites
The favorites feature allows you to mark important tasks that you want to preserve and find quickly.
### How Favorites Work
- **Marking Favorites**: Click the star icon next to any task to toggle its favorite status
- **Protection**: Favorited tasks are protected from individual and bulk deletion operations (can be overridden)
- **Filtering**: Use the favorites filter to quickly access your important tasks
## Batch Operations
The task history view supports several batch operations:
- **Select Multiple**: Use the checkboxes to select multiple tasks
- **Select All/None**: Quickly select or deselect all tasks
- **Delete Selected**: Remove all selected tasks
- **Delete All**: Remove all tasks from history (favorites are preserved unless you choose to include them)
## Best Practices
1. **Favorite Important Tasks**: Mark reference tasks or frequently accessed conversations as favorites
2. **Regular Cleanup**: Periodically remove old or unused tasks to improve performance
3. **Use Search**: Leverage the fuzzy search to quickly find specific conversations
4. **Export Valuable Tasks**: Export important tasks to markdown for external reference
Task management helps you maintain an organized workflow when using Cline, allowing you to quickly find past conversations, preserve important work, and keep your history clean and efficient.
@@ -14,7 +14,7 @@ description: "Context is key to getting the most out of Cline"
<Frame caption="In a world of infinite context, the context window is what Cline currently has available">
<img
src="/assets/robot_panel_dark.png"
src="https://storage.googleapis.com/cline_public_images/docs/assets/image%20(2).png"
alt="In a world of infinite context, the context window is what Cline currently has available"
/>
</Frame>
@@ -65,7 +65,10 @@ Think of context like a whiteboard you and Cline share:
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" />
<img
src="https://storage.googleapis.com/cline_public_images/docs/assets/image%20(1)%20(1).png"
alt="Context window progress bar"
/>
</Frame>
### Reading the Bar
+8 -6
View File
@@ -11,7 +11,10 @@ Utilizing MCP servers will increase your token usage. Cline offers the ability t
3. Cline will open a new settings window. find `Cline>Mcp:Mode` and make your selection from the dropdown menu.
<Frame>
<img src="/assets/robot_panel_dark.png" alt="MCP settings edit" />
<img
src="https://storage.googleapis.com/cline_public_images/docs/assets/MCP-settings-edit%20(1).png"
alt="MCP settings edit"
/>
</Frame>
## Managing Individual MCP Servers
@@ -22,7 +25,10 @@ Each MCP server has its own configuration panel where you can modify settings, m
2. Locate the MCP server you want to manage in the list, and open it by clicking on its name.
<Frame>
<img src="/assets/robot_panel_dark.png" alt="MCP settings individual" />
<img
src="https://storage.googleapis.com/cline_public_images/docs/assets/MCP-settings-individual.png"
alt="MCP settings individual"
/>
</Frame>
### Deleting a Server
@@ -45,10 +51,6 @@ To set the maximum time to wait for a response after a tool call to the MCP serv
1. Click the `Network Timeout` dropdown at the bottom of the individual MCP server's config box and change the time. Default is 1 minute but it can be set between 30 seconds and 1 hour.
<Frame>
<img src="/assets/robot_panel_dark.png" alt="Network Timeout pulldown" />
</Frame>
## Editing MCP Settings Files
Settings for all installed MCP servers are located in the `cline_mcp_settings.json` file:
+1 -1
View File
@@ -14,7 +14,7 @@ Model Context Protocol is an open protocol that standardizes how applications pr
<Frame>
<img
src="/assets/robot_panel_dark.png"
src="https://storage.googleapis.com/cline_public_images/docs/assets/mcp-diagram.png"
alt="MCP diagram showing how MCP servers connect LLMs to external tools and data sources"
/>
</Frame>
+8 -2
View File
@@ -242,7 +242,10 @@ Let's walk through the development process of our AlphaAdvantage MCP server, whi
### Planning Phase
<Frame>
<img src="/assets/robot_panel_dark.png" alt="Planning phase demonstration" />
<img
src="https://storage.googleapis.com/cline_public_images/docs/assets/planning-phase.gif"
alt="Planning phase demonstration"
/>
</Frame>
During the planning phase, we:
@@ -267,7 +270,10 @@ During the planning phase, we:
### Implementation
<Frame>
<img src="/assets/robot_panel_dark.png" alt="Building MCP plugin demonstration" />
<img
src="https://storage.googleapis.com/cline_public_images/docs/assets/building-mcp-plugin.gif"
alt="Building MCP plugin demonstration"
/>
</Frame>
We began by bootstrapping the project:
+2 -2
View File
@@ -26,9 +26,9 @@ For complete transparency, you can inspect our [telemetry implementation](https:
### How to Opt Out
Telemetry in Cline is entirely optional and requires your explicit consent:
Telemetry in Cline is entirely optional:
- When you update or install our VS Code extension, you'll see a simple prompt: "Help Improve Cline" with Allow or Deny options
- When you update or install our VS Code extension, you'll see a message about our anonymous telemetry
- You can change your preference anytime in settings
Cline also respects VS Code's global telemetry settings. If you've disabled telemetry at the VS Code level, Cline's telemetry will automatically be disabled as well.
+5 -5
View File
@@ -13,7 +13,7 @@ To get started with Cline Memory Bank:
3. **Paste into Cline** - Add as custom instructions or in a .clinerules file
4. **Initialize** - Ask Cline to "initialize memory bank"
[See detailed setup instructions](cline-memory-bank.md#getting-started-with-memory-bank)
[See detailed setup instructions](#getting-started-with-memory-bank)
### Cline Memory Bank Custom Instructions \[COPY THIS]
@@ -152,7 +152,7 @@ The Memory Bank is a structured documentation system that allows Cline to mainta
The Memory Bank isn't a Cline-specific feature - it's a methodology for managing AI context through structured documentation. When you instruct Cline to "follow custom instructions," it reads the Memory Bank files to rebuild its understanding of your project.
<Frame>
<img src="/assets/robot_panel_dark.png" alt="Memory Bank Workflow" />
<img src="https://storage.googleapis.com/cline_public_images/docs/assets/image%20(15).png" alt="Memory Bank Workflow" />
</Frame>
#### Understanding the Files
@@ -162,7 +162,7 @@ Memory Bank files are simply markdown files you create in your project. They're
Files are organized in a hierarchical structure that builds up a complete picture of your project:
<Frame>
<img src="/assets/robot_panel_dark.png" alt="Memory Bank File Structure" />
<img src="https://storage.googleapis.com/cline_public_images/docs/assets/image%20(16).png" alt="Memory Bank File Structure" />
</Frame>
### Memory Bank Files Explained
@@ -223,7 +223,7 @@ Create additional files when needed to organize:
3. Ask Cline to "initialize memory bank"
<Frame>
<img src="/assets/robot_panel_dark.png" alt="Memory Bank Setup" />
<img src="https://storage.googleapis.com/cline_public_images/docs/assets/image%20(17).png" alt="Memory Bank Setup" />
</Frame>
#### Project Brief Tips
@@ -287,7 +287,7 @@ As you work with Cline, your context window will eventually fill up (note the pr
This workflow ensures that important context is preserved in your Memory Bank files before the context window is cleared, allowing you to continue seamlessly in a fresh conversation.
<Frame>
<img src="/assets/robot_panel_dark.png" alt="Memory Bank Context Window" />
<img src="https://storage.googleapis.com/cline_public_images/docs/assets/image%20(18).png" alt="Memory Bank Context Window" />
</Frame>
#### How often should I update the memory bank?
+2 -2
View File
@@ -22,7 +22,7 @@ To add custom instructions:
4. Paste your instructions
<Frame>
<img src="/assets/robot_panel_dark.png" alt="Cline Logo" />
<img src="https://storage.googleapis.com/cline_public_images/docs/assets/image%20(1).png" alt="Cline Logo" />
</Frame>
Custom instructions are powerful for:
@@ -207,7 +207,7 @@ Located conveniently under the chat input field, this popover allows you to:
This UI significantly simplifies switching contexts and managing different sets of instructions without needing to manually edit files or configurations during a conversation.
<Frame>
<img src="/assets/robot_panel_dark.png" alt="Cline Logo" />
<img src="https://storage.googleapis.com/cline_public_images/docs/assets/image%20(1).png" alt="Cline Logo" />
</Frame>
## .clineignore File Guide
+17 -5
View File
@@ -20,7 +20,7 @@ Run AI models locally using LM Studio with Cline.
- Download and install for your operating system
<Frame>
<img src="/assets/robot_panel_dark.png" alt="LM Studio download page" />
<img src="https://storage.googleapis.com/cline_public_images/docs/assets/image%20(7).png" alt="LM Studio download page" />
</Frame>
#### 2. Launch LM Studio
@@ -29,7 +29,10 @@ Run AI models locally using LM Studio with Cline.
- You'll see four tabs on the left: **Chat**, **Developer** (where you will start the server), **My Models** (where your downloaded models are stored), **Discover** (add new models)
<Frame>
<img src="/assets/robot_panel_dark.png" alt="LM Studio interface overview" />
<img
src="https://storage.googleapis.com/cline_public_images/docs/assets/image%20(10).png"
alt="LM Studio interface overview"
/>
</Frame>
#### 3. Download a Model
@@ -39,7 +42,10 @@ Run AI models locally using LM Studio with Cline.
- Wait for download to complete
<Frame>
<img src="/assets/robot_panel_dark.png" alt="Downloading a model in LM Studio" />
<img
src="https://storage.googleapis.com/cline_public_images/docs/assets/lm-studio-download-model.gif"
alt="Downloading a model in LM Studio"
/>
</Frame>
#### 4. Start the Server
@@ -49,7 +55,10 @@ Run AI models locally using LM Studio with Cline.
- Note: The server will run at `http://localhost:1234`
<Frame>
<img src="/assets/robot_panel_dark.png" alt="Starting the LM Studio server" />
<img
src="https://storage.googleapis.com/cline_public_images/docs/assets/lm-studio-starting-server.gif"
alt="Starting the LM Studio server"
/>
</Frame>
#### 5. Configure Cline
@@ -60,7 +69,10 @@ Run AI models locally using LM Studio with Cline.
4. Select your model from the available options
<Frame>
<img src="/assets/robot_panel_dark.png" alt="Configuring Cline with LM Studio" />
<img
src="https://storage.googleapis.com/cline_public_images/docs/assets/lm-studio-select-model-cline.gif"
alt="Configuring Cline with LM Studio"
/>
</Frame>
### ⚠️ Important Notes
+16 -4
View File
@@ -16,7 +16,10 @@ description: "A quick guide to setting up Ollama for local AI model execution wi
- Download and install for your operating system
<Frame>
<img src="/assets/robot_panel_dark.png" alt="Ollama download page" />
<img
src="https://storage.googleapis.com/cline_public_images/docs/assets/image%20(2)%20(1)%20(1).png"
alt="Ollama download page"
/>
</Frame>
#### 2. Choose and Download a Model
@@ -29,7 +32,10 @@ description: "A quick guide to setting up Ollama for local AI model execution wi
```
<Frame>
<img src="/assets/robot_panel_dark.png" alt="Selecting a model in Ollama" />
<img
src="https://storage.googleapis.com/cline_public_images/docs/assets/ollama-model-grab%20(2).gif"
alt="Selecting a model in Ollama"
/>
</Frame>
- Open your Terminal and run the command:
@@ -41,7 +47,10 @@ description: "A quick guide to setting up Ollama for local AI model execution wi
```
<Frame>
<img src="/assets/robot_panel_dark.png" alt="Running Ollama in terminal" />
<img
src="https://storage.googleapis.com/cline_public_images/docs/assets/starting-ollama-terminal%20(2).gif"
alt="Running Ollama in terminal"
/>
</Frame>
**✨ Your model is now ready to use within Cline!**
@@ -56,7 +65,10 @@ description: "A quick guide to setting up Ollama for local AI model execution wi
- Select the model from your available options
<Frame>
<img src="/assets/robot_panel_dark.png" alt="Configuring Cline with Ollama" />
<img
src="https://storage.googleapis.com/cline_public_images/docs/assets/selecting-ollama-model-cline%20(3).gif"
alt="Configuring Cline with Ollama"
/>
</Frame>
### ⚠️ Important Notes
@@ -20,7 +20,10 @@ Local models are created by training a smaller model to imitate a larger one, bu
Think of it like running your development environment on a calculator instead of a computer it might handle basic tasks, but complex operations become unreliable or impossible.
<Frame>
<img src="/assets/robot_panel_dark.png" alt="Local model comparison diagram" />
<img
src="https://storage.googleapis.com/cline_public_images/docs/assets/image%20(4).png"
alt="Local model comparison diagram"
/>
</Frame>
### What Actually Happens
+24 -5
View File
@@ -4,6 +4,8 @@ const path = require("path")
const production = process.argv.includes("--production")
const watch = process.argv.includes("--watch")
const standalone = process.argv.includes("--standalone")
const destDir = standalone ? "dist-standalone" : "dist"
/**
* @type {import('esbuild').Plugin}
@@ -85,7 +87,7 @@ const copyWasmFiles = {
build.onEnd(() => {
// tree sitter
const sourceDir = path.join(__dirname, "node_modules", "web-tree-sitter")
const targetDir = path.join(__dirname, "dist")
const targetDir = path.join(__dirname, destDir)
// Copy tree-sitter.wasm
fs.copyFileSync(path.join(sourceDir, "tree-sitter.wasm"), path.join(targetDir, "tree-sitter.wasm"))
@@ -117,7 +119,8 @@ const copyWasmFiles = {
},
}
const extensionConfig = {
// Base configuration shared between extension and standalone builds
const baseConfig = {
bundle: true,
minify: production,
sourcemap: !production,
@@ -140,16 +143,32 @@ const extensionConfig = {
},
},
],
entryPoints: ["src/extension.ts"],
format: "cjs",
sourcesContent: false,
platform: "node",
outfile: "dist/extension.js",
}
// Extension-specific configuration
const extensionConfig = {
...baseConfig,
entryPoints: ["src/extension.ts"],
outfile: `${destDir}/extension.js`,
external: ["vscode"],
}
// Standalone-specific configuration
const standaloneConfig = {
...baseConfig,
entryPoints: ["src/standalone/standalone.ts"],
outfile: `${destDir}/standalone.js`,
// These gRPC protos need to load files from the module directory at runtime,
// so they cannot be bundled.
external: ["vscode", "@grpc/reflection", "grpc-health-check"],
}
async function main() {
const extensionCtx = await esbuild.context(extensionConfig)
const config = standalone ? standaloneConfig : extensionConfig
const extensionCtx = await esbuild.context(config)
if (watch) {
await extensionCtx.watch()
} else {
+1057 -134
View File
File diff suppressed because it is too large Load Diff
+19 -77
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.14.0",
"version": "3.16.1",
"icon": "assets/icons/icon.png",
"engines": {
"vscode": "^1.84.0"
@@ -40,6 +40,8 @@
"llama"
],
"activationEvents": [
"onLanguage",
"onStartupFinished",
"workspaceContains:evals.env"
],
"main": "./dist/extension.js",
@@ -121,7 +123,7 @@
},
{
"command": "cline.generateGitCommitMessage",
"title": "Generate Commit Message with Cline",
"title": "Generate Commit Message with Cline",
"category": "Cline",
"icon": "$(robot)"
}
@@ -234,87 +236,20 @@
},
"configuration": {
"title": "Cline",
"properties": {
"cline.vsCodeLmModelSelector": {
"type": "object",
"properties": {
"vendor": {
"type": "string",
"description": "The vendor of the language model (e.g. copilot)"
},
"family": {
"type": "string",
"description": "The family of the language model (e.g. gpt-4)"
}
},
"description": "Settings for VSCode Language Model API"
},
"cline.enableCheckpoints": {
"type": "boolean",
"default": true,
"description": "Enables extension to save checkpoints of workspace throughout the task. Uses git under the hood which may not work well with large workspaces."
},
"cline.disableBrowserTool": {
"type": "boolean",
"default": false,
"description": "Disables extension from spawning browser session."
},
"cline.modelSettings.o3Mini.reasoningEffort": {
"type": "string",
"enum": [
"low",
"medium",
"high"
],
"default": "medium",
"description": "Controls the reasoning effort when using an OpenAI reasoning model. Higher values may result in more thorough but slower responses."
},
"cline.chromeExecutablePath": {
"type": "string",
"default": null,
"description": "Path to Chrome executable for browser use functionality. If not set, the extension will attempt to find or download it automatically."
},
"cline.preferredLanguage": {
"type": "string",
"enum": [
"English",
"Arabic - العربية",
"Portuguese - Português (Brasil)",
"Czech - Čeština",
"French - Français",
"German - Deutsch",
"Hindi - हिन्दी",
"Hungarian - Magyar",
"Italian - Italiano",
"Japanese - 日本語",
"Korean - 한국어",
"Polish - Polski",
"Portuguese - Português (Portugal)",
"Russian - Русский",
"Simplified Chinese - 简体中文",
"Spanish - Español",
"Traditional Chinese - 繁體中文",
"Turkish - Türkçe"
],
"default": "English",
"description": "The language that Cline should use for communication."
},
"cline.mcpMarketplace.enabled": {
"type": "boolean",
"default": true,
"description": "Controls whether the MCP Marketplace is enabled."
}
}
"properties": {}
}
},
"scripts": {
"vscode:prepublish": "npm run package",
"compile": "npm run check-types && npm run lint && node esbuild.js",
"compile-standalone": "npm run protos && npm run check-types && npm run lint && node esbuild.js --standalone",
"postcompile-standalone": "node scripts/package-standalone.mjs",
"watch": "npm-run-all -p watch:*",
"watch:esbuild": "node esbuild.js --watch",
"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",
"protos": "node proto/build-proto.js && node scripts/generate-server-setup.mjs",
"postprotos": "prettier src/shared/proto src/core/controller webview-ui/src/services src/standalone/server-setup.ts --write --log-level silent",
"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",
@@ -336,7 +271,9 @@
"prepare": "husky",
"changeset": "changeset",
"version-packages": "changeset version",
"docs:preview": "cd docs && mintlify dev",
"docs": "cd docs && mintlify dev",
"docs:check-links": "cd docs && mintlify broken-links",
"docs:rename-file": "cd docs && mintlify rename",
"report-issue": "node scripts/report-issue.js"
},
"devDependencies": {
@@ -382,8 +319,9 @@
"@aws-sdk/client-bedrock-runtime": "^3.758.0",
"@bufbuild/protobuf": "^2.2.5",
"@google-cloud/vertexai": "^1.9.3",
"@google/genai": "^0.9.0",
"@google/genai": "^0.13.0",
"@grpc/grpc-js": "^1.9.15",
"@grpc/reflection": "^1.0.4",
"@mistralai/mistralai": "^1.5.0",
"@modelcontextprotocol/sdk": "^1.7.0",
"@opentelemetry/api": "^1.4.1",
@@ -394,6 +332,7 @@
"@opentelemetry/semantic-conventions": "^1.30.0",
"@sentry/browser": "^9.12.0",
"@vscode/codicons": "^0.0.36",
"archiver": "^7.0.1",
"axios": "^1.8.2",
"cheerio": "^1.0.0",
"chokidar": "^4.0.1",
@@ -407,14 +346,16 @@
"fzf": "^0.5.2",
"get-folder-size": "^5.0.0",
"globby": "^14.0.2",
"grpc-health-check": "^2.0.2",
"iconv-lite": "^0.6.3",
"ignore": "^7.0.3",
"image-size": "^2.0.2",
"isbinaryfile": "^5.0.2",
"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": "^10.1.2",
"open-graph-scraper": "^6.9.0",
"openai": "^4.83.0",
"os-name": "^6.0.0",
@@ -428,6 +369,7 @@
"simple-git": "^3.27.0",
"strip-ansi": "^7.1.0",
"tree-sitter-wasms": "^0.1.11",
"ts-morph": "^25.0.1",
"turndown": "^7.2.0",
"web-tree-sitter": "^0.22.6",
"zod": "^3.24.2"
+4
View File
@@ -40,6 +40,8 @@ message BrowserSettings {
Viewport viewport = 1;
optional string remote_browser_host = 2;
optional bool remote_browser_enabled = 3;
optional string chrome_executable_path = 4;
optional bool disable_tool_use = 5;
}
message UpdateBrowserSettingsRequest {
@@ -47,4 +49,6 @@ message UpdateBrowserSettingsRequest {
Viewport viewport = 2;
optional string remote_browser_host = 3;
optional bool remote_browser_enabled = 4;
optional string chrome_executable_path = 5;
optional bool disable_tool_use = 6;
}
+34 -21
View File
@@ -29,6 +29,7 @@ const serviceNameMap = {
task: "cline.TaskService",
web: "cline.WebService",
models: "cline.ModelsService",
slash: "cline.SlashService",
// Add new services here - no other code changes needed!
}
const serviceDirs = Object.keys(serviceNameMap).map((serviceKey) => path.join(ROOT_DIR, "src", "core", "controller", serviceKey))
@@ -54,30 +55,42 @@ 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, absolute: true })
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 tsProtocCommand = [
protoc,
`--proto_path="${SCRIPT_DIR}"`,
`--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",
...protoFiles,
].join(" ")
try {
console.log(chalk.cyan(`Generating TypeScript code for:\n${protoFiles.join("\n")}...`))
execSync(tsProtocCommand, { stdio: "inherit" })
} catch (error) {
console.error(chalk.red("Error generating TypeScript for proto files:"), error)
process.exit(1)
}
// Build the protoc command with proper path handling for cross-platform
const protocCommand = [
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}"`,
`"${path.join(SCRIPT_DIR, protoFile)}"`,
].join(" ")
const descriptorOutDir = path.join(ROOT_DIR, "dist-standalone", "proto")
await fs.mkdir(descriptorOutDir, { recursive: true })
try {
const execOptions = {
stdio: "inherit",
}
execSync(protocCommand, execOptions)
} catch (error) {
console.error(chalk.red(`Error generating TypeScript for ${protoFile}:`), error)
process.exit(1)
}
const descriptorFile = path.join(descriptorOutDir, "descriptor_set.pb")
const descriptorProtocCommand = [
protoc,
`--proto_path="${SCRIPT_DIR}"`,
`--descriptor_set_out="${descriptorFile}"`,
"--include_imports",
...protoFiles,
].join(" ")
try {
console.log(chalk.cyan("Generating descriptor set..."))
execSync(descriptorProtocCommand, { stdio: "inherit" })
} catch (error) {
console.error(chalk.red("Error generating descriptor set for proto file:"), error)
process.exit(1)
}
console.log(chalk.green("Protocol Buffer code generation completed successfully."))
+7
View File
@@ -8,6 +8,9 @@ import "common.proto";
// Service for file-related operations
service FileService {
// Copies text to clipboard
rpc copyToClipboard(StringRequest) returns (Empty);
// Opens a file in the editor
rpc openFile(StringRequest) returns (Empty);
@@ -22,6 +25,9 @@ service FileService {
// Search git commits in the workspace
rpc searchCommits(StringRequest) returns (GitCommits);
// Select images from the file system and return as data URLs
rpc selectImages(EmptyRequest) returns (StringArray);
// Convert URIs to workspace-relative paths
rpc getRelativePaths(RelativePathsRequest) returns (RelativePaths);
@@ -82,6 +88,7 @@ message RuleFileRequest {
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)
optional string type = 5; // Type of the file to create (optional)
}
// Result for rule file operations with meaningful data only
+2
View File
@@ -10,6 +10,8 @@ service McpService {
rpc toggleMcpServer(ToggleMcpServerRequest) returns (McpServers);
rpc updateMcpTimeout(UpdateMcpTimeoutRequest) returns (McpServers);
rpc addRemoteMcpServer(AddRemoteMcpServerRequest) returns (McpServers);
rpc downloadMcp(StringRequest) returns (Empty);
rpc restartMcpServer(StringRequest) returns (McpServers);
}
message ToggleMcpServerRequest {
+46 -1
View File
@@ -10,7 +10,52 @@ import "common.proto";
service ModelsService {
// Fetches available models from Ollama
rpc getOllamaModels(StringRequest) returns (StringArray);
// Fetches available models from LM Studio
rpc getLmStudioModels(StringRequest) returns (StringArray);
// Fetches available models from VS Code LM API
rpc getVsCodeLmModels(EmptyRequest) returns (VsCodeLmModelsArray);
// Refreshes and returns OpenRouter models
rpc refreshOpenRouterModels(EmptyRequest) returns (OpenRouterCompatibleModelInfo);
// Refreshes and returns OpenAI models
rpc refreshOpenAiModels(OpenAiModelsRequest) returns (StringArray);
// Refreshes and returns Requesty models
rpc refreshRequestyModels(EmptyRequest) returns (OpenRouterCompatibleModelInfo);
}
// List of VS Code LM models
message VsCodeLmModelsArray {
repeated VsCodeLmModel models = 1;
}
// Structure representing a VS Code LM model
message VsCodeLmModel {
string vendor = 1;
string family = 2;
string version = 3;
string id = 4;
}
// For OpenRouterCompatibleModelInfo structure in OpenRouterModels
message OpenRouterModelInfo {
int32 max_tokens = 1;
int32 context_window = 2;
bool supports_images = 3;
bool supports_prompt_cache = 4;
double input_price = 5;
double output_price = 6;
double cache_writes_price = 7;
double cache_reads_price = 8;
string description = 9;
}
// Shared response message for model information
message OpenRouterCompatibleModelInfo {
map<string, OpenRouterModelInfo> models = 1;
}
// Request for fetching OpenAI models
message OpenAiModelsRequest {
Metadata metadata = 1;
string baseUrl = 2;
string apiKey = 3;
}
+14
View File
@@ -0,0 +1,14 @@
syntax = "proto3";
package cline;
option java_package = "bot.cline.proto";
option java_multiple_files = true;
import "common.proto";
// SlashService provides methods for managing slash
service SlashService {
// Sends button click message
rpc reportBug(StringRequest) returns (Empty);
rpc condense(StringRequest) returns (Empty);
}
+2
View File
@@ -6,6 +6,8 @@ import "common.proto";
service StateService {
rpc getLatestState(EmptyRequest) returns (State);
rpc subscribeToState(EmptyRequest) returns (stream State);
rpc toggleFavoriteModel(StringRequest) returns (Empty);
rpc resetState(EmptyRequest) returns (Empty);
}
message State {
+76 -1
View File
@@ -16,9 +16,21 @@ service TaskService {
// Creates a new task with the given text and optional images
rpc newTask(NewTaskRequest) returns (Empty);
// Shows a task with the specified ID
rpc showTaskWithId(StringRequest) returns (Empty);
rpc showTaskWithId(StringRequest) returns (TaskResponse);
// Exports a task with the given ID to markdown
rpc exportTaskWithId(StringRequest) returns (Empty);
// Toggles the favorite status of a task
rpc toggleTaskFavorite(TaskFavoriteRequest) returns (Empty);
// Deletes all non-favorited tasks
rpc deleteNonFavoritedTasks(EmptyRequest) returns (DeleteNonFavoritedTasksResults);
// Gets filtered task history
rpc getTaskHistory(GetTaskHistoryRequest) returns (TaskHistoryArray);
// Sends a response to a previous ask operation
rpc askResponse(AskResponseRequest) returns (Empty);
// Records task feedback (thumbs up/down)
rpc taskFeedback(StringRequest) returns (Empty);
// Shows task completion changes diff in a view
rpc taskCompletionViewChanges(Int64Request) returns (Empty);
}
// Request message for creating a new task
@@ -28,3 +40,66 @@ message NewTaskRequest {
repeated string images = 3;
}
// Request message for toggling task favorite status
message TaskFavoriteRequest {
Metadata metadata = 1;
string task_id = 2;
bool is_favorited = 3;
}
// Response for task details
message TaskResponse {
string id = 1;
string task = 2;
int64 ts = 3;
bool is_favorited = 4;
int64 size = 5;
double total_cost = 6;
int32 tokens_in = 7;
int32 tokens_out = 8;
int32 cache_writes = 9;
int32 cache_reads = 10;
}
// Results returned when deleting non-favorited tasks
message DeleteNonFavoritedTasksResults {
int32 tasks_preserved = 1;
int32 tasks_deleted = 2;
}
// Request for getting task history with filtering
message GetTaskHistoryRequest {
Metadata metadata = 1;
bool favorites_only = 2;
string search_query = 3;
string sort_by = 4;
bool current_workspace_only = 5;
}
// Response for task history
message TaskHistoryArray {
repeated TaskItem tasks = 1;
int32 total_count = 2;
}
// Task item details for history list
message TaskItem {
string id = 1;
string task = 2;
int64 ts = 3;
bool is_favorited = 4;
int64 size = 5;
double total_cost = 6;
int32 tokens_in = 7;
int32 tokens_out = 8;
int32 cache_writes = 9;
int32 cache_reads = 10;
}
// Request for ask response operation
message AskResponseRequest {
Metadata metadata = 1;
string response_type = 2;
string text = 3;
repeated string images = 4;
}
+10
View File
@@ -8,9 +8,19 @@ import "common.proto";
service WebService {
rpc checkIsImageUrl(StringRequest) returns (IsImageUrl);
rpc fetchOpenGraphData(StringRequest) returns (OpenGraphData);
}
message IsImageUrl {
bool is_image = 1;
string url = 2;
}
message OpenGraphData {
string title = 1;
string description = 2;
string image = 3;
string url = 4;
string site_name = 5;
string type = 6;
}
+79
View File
@@ -0,0 +1,79 @@
import * as fs from "fs"
import * as grpc from "@grpc/grpc-js"
import * as protoLoader from "@grpc/proto-loader"
import * as health from "grpc-health-check"
import { fileURLToPath } from "url"
import path from "path"
const OUT_FILE = path.resolve("src/standalone/server-setup.ts")
const DESCRIPTOR_SET = path.resolve("dist-standalone/proto/descriptor_set.pb")
// Load service definitions.
const clineDef = protoLoader.loadFileDescriptorSetFromBuffer(fs.readFileSync(DESCRIPTOR_SET))
const healthDef = protoLoader.loadSync(health.protoPath)
const packageDefinition = { ...clineDef, ...healthDef }
const proto = grpc.loadPackageDefinition(packageDefinition)
/**
* Generate imports and function to add all the handlers to the server for all services defined in the proto files.
*/
function generateHandlersAndExports() {
let imports = []
let handlerSetup = []
for (const [name, def] of Object.entries(proto.cline)) {
if (!def || !("service" in def)) {
continue
}
const domain = name.replace(/Service$/, "")
const dir = domain.charAt(0).toLowerCase() + domain.slice(1)
imports.push(`// ${domain} Service`)
handlerSetup.push(` // ${domain} Service`)
handlerSetup.push(` server.addService(proto.cline.${name}.service, {`)
for (const [rpcName, rpc] of Object.entries(def.service)) {
imports.push(`import { ${rpcName} } from "../core/controller/${dir}/${rpcName}"`)
if (rpc.requestStream) {
throw new Error("Request streaming is not supported")
}
if (rpc.responseStream) {
handlerSetup.push(` ${rpcName}: wrapStreamingResponse(${rpcName}, controller),`)
} else {
handlerSetup.push(` ${rpcName}: wrapper(${rpcName}, controller),`)
}
}
handlerSetup.push(` });`)
imports.push("")
handlerSetup.push("")
}
return {
imports: imports.join("\n"),
handlerSetup: handlerSetup.join("\n"),
}
}
const { imports, handlerSetup } = generateHandlersAndExports()
const scriptName = path.basename(fileURLToPath(import.meta.url))
// Create output file
let output = `// GENERATED CODE -- DO NOT EDIT!
// Generated by ${scriptName}
import * as grpc from "@grpc/grpc-js"
import { Controller } from "../core/controller"
import { GrpcHandlerWrapper, GrpcStreamingResponseHandlerWrapper } from "./grpc-types"
${imports}
export function addServices(
server: grpc.Server,
proto: any,
controller: Controller,
wrapper: GrpcHandlerWrapper,
wrapStreamingResponse: GrpcStreamingResponseHandlerWrapper,
): void {
${handlerSetup}
}
`
// Write output file
fs.writeFileSync(OUT_FILE, output)
console.log(`Generated service handlers in ${OUT_FILE}.`)
+96
View File
@@ -0,0 +1,96 @@
const fs = require("fs")
const path = require("path")
const { Project, SyntaxKind } = require("ts-morph")
function traverse(container, output, prefix = "") {
for (const node of container.getStatements()) {
const kind = node.getKind()
if (kind === SyntaxKind.ModuleDeclaration) {
const name = node.getName().replace(/^['"]|['"]$/g, "")
var fullPrefix
if (prefix) {
fullPrefix = `${prefix}.${name}`
} else {
fullPrefix = name
}
output.push(`${fullPrefix} = {};`)
const body = node.getBody()
if (body && body.getKind() === SyntaxKind.ModuleBlock) {
traverse(body, output, fullPrefix)
}
} else if (kind === SyntaxKind.FunctionDeclaration) {
const name = node.getName()
const params = node.getParameters().map((p, i) => sanitizeParam(p.getName(), i))
const typeNode = node.getReturnTypeNode()
const returnType = typeNode ? typeNode.getText() : ""
const ret = mapReturn(returnType)
output.push(
`${prefix}.${name} = function(${params.join(", ")}) { console.log('Called stubbed function: ${prefix}.${name}'); ${ret} };`,
)
} else if (kind === SyntaxKind.EnumDeclaration) {
const name = node.getName()
const members = node.getMembers().map((m) => m.getName())
output.push(`${prefix}.${name} = { ${members.map((m) => `${m}: 0`).join(", ")} };`)
} else if (kind === SyntaxKind.VariableStatement) {
for (const decl of node.getDeclarations()) {
const name = decl.getName()
output.push(`${prefix}.${name} = createStub("${prefix}.${name}");`)
}
} else if (kind == SyntaxKind.ClassDeclaration) {
const name = node.getName()
output.push(
`${prefix}.${name} = class { constructor(...args) {
console.log('Constructed stubbed class: new ${prefix}.${name}(', args, ')');
return createStub(${prefix}.${name});
}};`,
)
} else if (kind === SyntaxKind.TypeAliasDeclaration || kind === SyntaxKind.InterfaceDeclaration) {
//console.log("Skipping", SyntaxKind[kind], node.getName())
// Skip interfaces and type aliases because they are only used at compile time by typescript.
} else {
console.log("Can't handle: ", SyntaxKind[kind])
}
}
}
function mapReturn(typeStr) {
if (!typeStr) return ""
if (typeStr.includes("void")) return ""
if (typeStr.includes("string")) return `return '';`
if (typeStr.includes("number")) return `return 0;`
if (typeStr.includes("boolean")) return `return false;`
if (typeStr.includes("[]")) return `return [];`
if (typeStr.includes("Thenable")) return `return Promise.resolve(null);`
return `return createStub("unknown");`
}
function sanitizeParam(name, index) {
return name || `arg${index}`
}
async function main() {
const inputPath = "node_modules/@types/vscode/index.d.ts"
const outputPath = "standalone/runtime-files/vscode/vscode-stubs.js"
const project = new Project()
const sourceFile = project.addSourceFileAtPath(inputPath)
const output = []
output.push("// GENERATED CODE -- DO NOT EDIT!")
output.push('console.log("Loading stubs...");')
output.push('const { createStub } = require("./stub-utils")')
traverse(sourceFile, output)
output.push("module.exports = vscode;")
output.push('console.log("Finished loading stubs");')
fs.mkdirSync(path.dirname(outputPath), { recursive: true })
fs.writeFileSync(outputPath, output.join("\n"))
console.log(`Wrote vscode SDK stubs to ${outputPath}`)
}
main().catch((err) => {
console.error(err)
process.exit(1)
})
+18
View File
@@ -0,0 +1,18 @@
#!/usr/bin/env bash
set -eu
DIR=${1:-src/}
DEST_DIR=dist-standalone
DEST=dist-standalone/vscode-uses.txt
mkdir -p $DEST_DIR
{
git grep -h 'vscode\.' $DIR |
grep -Ev '//.*vscode' | # remove commented out code
sed 's|.*vscode\.|vscode.|'| # remove everything before vscode.
sed 's/[^a-zA-Z0-9_.].*$//' | # remove everything after last identifier
sort | uniq > $DEST
}
echo Done, wrote uses of the vscode SDK to $(realpath $DEST)
+54
View File
@@ -0,0 +1,54 @@
import fs from "fs"
import path from "path"
import { glob } from "glob"
import archiver from "archiver"
import { cp } from "fs/promises"
import { execSync } from "child_process"
const BUILD_DIR = "dist-standalone"
const SOURCE_DIR = "standalone/runtime-files"
await cp(SOURCE_DIR, BUILD_DIR, { recursive: true })
// Run npm install in the distribution directory
console.log("Running npm install in distribution directory...")
const cwd = process.cwd()
process.chdir(BUILD_DIR)
try {
execSync("npm install", { stdio: "inherit" })
// Move the vscode directory into node_modules.
// It can't be installed using npm because it will create a symlink which is not portable.
fs.renameSync("vscode", path.join("node_modules", "vscode"))
} catch (error) {
console.error("Error during setup:", error)
process.exit(1)
} finally {
process.chdir(cwd)
}
// Check for native .node modules.
const nativeModules = await glob("**/*.node", { cwd: BUILD_DIR, nodir: true })
if (nativeModules.length > 0) {
console.error("Native node modules cannot be included in the standalone distribution:\n", nativeModules.join("\n"))
process.exit(1)
}
// Zip the build directory (excluding any pre-existing output zip).
const zipPath = path.join(BUILD_DIR, "standalone.zip")
const output = fs.createWriteStream(zipPath)
const archive = archiver("zip", { zlib: { level: 9 } })
output.on("close", () => {
console.log(`Created ${zipPath} (${archive.pointer()} bytes)`)
})
archive.on("error", (err) => {
throw err
})
archive.pipe(output)
archive.glob("**/*", {
cwd: BUILD_DIR,
ignore: ["standalone.zip"],
})
await archive.finalize()
+3
View File
@@ -19,6 +19,7 @@ import { DoubaoHandler } from "./providers/doubao"
import { VsCodeLmHandler } from "./providers/vscode-lm"
import { ClineHandler } from "./providers/cline"
import { LiteLlmHandler } from "./providers/litellm"
import { FireworksHandler } from "./providers/fireworks"
import { AskSageHandler } from "./providers/asksage"
import { XAIHandler } from "./providers/xai"
import { SambanovaHandler } from "./providers/sambanova"
@@ -58,6 +59,8 @@ export function buildApiHandler(configuration: ApiConfiguration): ApiHandler {
return new DeepSeekHandler(options)
case "requesty":
return new RequestyHandler(options)
case "fireworks":
return new FireworksHandler(options)
case "together":
return new TogetherHandler(options)
case "qwen":
+6 -2
View File
@@ -272,10 +272,14 @@ export class AwsBedrockHandler implements ApiHandler {
}
/**
* Gets the appropriate model ID, accounting for cross-region inference if enabled
* Gets the appropriate model ID, accounting for cross-region inference if enabled.
* If the model ID is an ARN that contains a slash, you will get the URL encoded ARN.
*/
async getModelId(): Promise<string> {
if (this.options.awsUseCrossRegionInference) {
if (this.options.awsBedrockCustomSelected && this.getModel().id.includes("/")) {
return encodeURIComponent(this.getModel().id)
}
if (!this.options.awsBedrockCustomSelected && this.options.awsUseCrossRegionInference) {
const regionPrefix = this.getRegion().slice(0, 3)
switch (regionPrefix) {
case "us-":
+1 -1
View File
@@ -33,7 +33,7 @@ export class ClineHandler implements ApiHandler {
systemPrompt,
messages,
this.getModel(),
this.options.o3MiniReasoningEffort,
this.options.reasoningEffort,
this.options.thinkingBudgetTokens,
this.options.openRouterProviderSorting,
)
+94
View File
@@ -0,0 +1,94 @@
import { Anthropic } from "@anthropic-ai/sdk"
import OpenAI from "openai"
import { withRetry } from "../retry"
import { ApiHandler } from ".."
import {
ApiHandlerOptions,
DeepSeekModelId,
ModelInfo,
deepSeekDefaultModelId,
deepSeekModels,
openAiModelInfoSaneDefaults,
} from "../../shared/api"
import { convertToOpenAiMessages } from "../transform/openai-format"
import { ApiStream } from "../transform/stream"
export class FireworksHandler implements ApiHandler {
private options: ApiHandlerOptions
private client: OpenAI
constructor(options: ApiHandlerOptions) {
this.options = options
this.client = new OpenAI({
baseURL: "https://api.fireworks.ai/inference/v1",
apiKey: this.options.fireworksApiKey,
})
}
@withRetry()
async *createMessage(systemPrompt: string, messages: Anthropic.Messages.MessageParam[]): ApiStream {
const modelId = this.options.fireworksModelId ?? ""
const openAiMessages: OpenAI.Chat.ChatCompletionMessageParam[] = [
{ role: "system", content: systemPrompt },
...convertToOpenAiMessages(messages),
]
const stream = await this.client.chat.completions.create({
model: modelId,
...(this.options.fireworksModelMaxCompletionTokens
? { max_completion_tokens: this.options.fireworksModelMaxCompletionTokens }
: {}),
...(this.options.fireworksModelMaxTokens ? { max_tokens: this.options.fireworksModelMaxTokens } : {}),
messages: openAiMessages,
stream: true,
stream_options: { include_usage: true },
temperature: 0,
})
let reasoning: string | null = null
for await (const chunk of stream) {
const delta = chunk.choices[0]?.delta
if (reasoning || delta?.content?.includes("<think>")) {
reasoning = (reasoning || "") + (delta.content ?? "")
}
if (delta?.content && !reasoning) {
yield {
type: "text",
text: delta.content,
}
}
if (reasoning || ("reasoning_content" in delta && delta.reasoning_content)) {
yield {
type: "reasoning",
reasoning: delta.content || ((delta as any).reasoning_content as string | undefined) || "",
}
if (reasoning?.includes("</think>")) {
// Reset so the next chunk is regular content
reasoning = null
}
}
if (chunk.usage) {
yield {
type: "usage",
inputTokens: chunk.usage.prompt_tokens || 0, // (deepseek reports total input AND cache reads/writes, see context caching: https://api-docs.deepseek.com/guides/kv_cache) where the input tokens is the sum of the cache hits/misses, while anthropic reports them as separate tokens. This is important to know for 1) context management truncation algorithm, and 2) cost calculation (NOTE: we report both input and cache stats but for now set input price to 0 since all the cost calculation will be done using cache hits/misses)
outputTokens: chunk.usage.completion_tokens || 0,
// @ts-ignore-next-line
cacheReadTokens: chunk.usage.prompt_cache_hit_tokens || 0,
// @ts-ignore-next-line
cacheWriteTokens: chunk.usage.prompt_cache_miss_tokens || 0,
}
}
}
}
getModel(): { id: string; info: ModelInfo } {
return {
id: this.options.fireworksModelId ?? "",
info: openAiModelInfoSaneDefaults,
}
}
}
+102 -341
View File
@@ -1,12 +1,12 @@
import type { Anthropic } from "@anthropic-ai/sdk"
// Restore GenerateContentConfig import and add GenerateContentResponseUsageMetadata
import { GoogleGenAI, type Content, type GenerateContentConfig, type GenerateContentResponseUsageMetadata } from "@google/genai"
import NodeCache from "node-cache"
import { GoogleGenAI, type GenerateContentConfig, type GenerateContentResponseUsageMetadata } from "@google/genai"
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"
import { telemetryService } from "@services/posthog/telemetry/TelemetryService"
// Define a default TTL for the cache (e.g., 15 minutes in seconds)
const DEFAULT_CACHE_TTL_SECONDS = 900
@@ -39,12 +39,6 @@ export class GeminiHandler implements ApiHandler {
private options: ApiHandlerOptions
private client: GoogleGenAI
// 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
@@ -67,84 +61,27 @@ export class GeminiHandler implements ApiHandler {
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
* Creates a message using the Gemini API with implicit caching.
*
* 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()
@withRetry({
maxRetries: 4,
baseDelay: 2000,
maxDelay: 15000,
})
async *createMessage(systemPrompt: string, messages: Anthropic.Messages.MessageParam[]): ApiStream {
const { id: model, info } = this.getModel()
const { id: modelId, info } = this.getModel()
const contents = messages.map(convertAnthropicMessageToGemini)
// Ensure we have a stable cache key (taskId)
if (!this.options.taskId) {
console.warn("[GeminiHandler] No taskId provided, caching will be disabled")
}
const taskId = this.options.taskId
// 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
@@ -153,10 +90,7 @@ export class GeminiHandler implements ApiHandler {
const requestConfig: GenerateContentConfig = {
// 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 }),
...{ systemInstruction: systemPrompt },
// Set temperature (default to 0)
temperature: 0,
}
@@ -169,260 +103,114 @@ export class GeminiHandler implements ApiHandler {
}
// Generate content using the configured parameters
const result = await this.client.models.generateContentStream({
model,
contents: uncachedContent ?? contents,
config: {
...requestConfig,
...(isCacheUsed ? { cachedContent } : {}),
},
})
// 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
const sdkCallStartTime = Date.now()
let sdkFirstChunkTime: number | undefined
let ttftSdkMs: number | undefined
let apiSuccess = false
let apiError: string | undefined
let promptTokens = 0
let outputTokens = 0
let cacheReadTokens = 0
let lastUsageMetadata: GenerateContentResponseUsageMetadata | undefined
// Process the stream
for await (const chunk of result) {
if (chunk.text) {
yield {
type: "text",
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,
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,
const result = await this.client.models.generateContentStream({
model: modelId,
contents: contents,
config: {
contents,
systemInstruction,
ttl: `${DEFAULT_CACHE_TTL_SECONDS}s`,
httpOptions: { timeout: 120_000 },
...requestConfig,
},
})
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)
let isFirstSdkChunk = true
for await (const chunk of result) {
if (isFirstSdkChunk) {
sdkFirstChunkTime = Date.now()
ttftSdkMs = sdkFirstChunkTime - sdkCallStartTime
isFirstSdkChunk = false
}
// 3. Update our local tracking
this.contentCaches.set<{ key: string; count: number }>(taskId, {
key: name,
count: contents.length,
if (chunk.text) {
yield {
type: "text",
text: chunk.text,
}
}
if (chunk.usageMetadata) {
lastUsageMetadata = chunk.usageMetadata
promptTokens = lastUsageMetadata.promptTokenCount ?? promptTokens
outputTokens = lastUsageMetadata.candidatesTokenCount ?? outputTokens
cacheReadTokens = lastUsageMetadata.cachedContentTokenCount ?? cacheReadTokens
}
}
apiSuccess = true
if (lastUsageMetadata) {
const totalCost = this.calculateCost({
info,
inputTokens: promptTokens,
outputTokens,
cacheReadTokens,
})
this.taskCacheNames.set(taskId, name)
yield {
type: "usage",
inputTokens: promptTokens,
outputTokens,
cacheReadTokens,
cacheWriteTokens: 0,
totalCost,
}
}
} catch (error) {
apiSuccess = false
// Let the error propagate to be handled by withRetry or Task.ts
// Telemetry will be sent in the finally block.
if (error instanceof Error) {
apiError = error.message
// 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
// Gemini doesn't include status codes in their errors
// https://github.com/googleapis/js-genai/blob/61f7f27b866c74333ca6331883882489bcb708b9/src/_api_client.ts#L569
if (error.name === "ClientError" && error.message.includes("got status: 429 Too Many Requests.")) {
;(error as any).status = 429
}
} else {
apiError = String(error)
}
return
} catch (error) {
console.error(`[GeminiHandler] Failed to update cache for task ${taskId}:`, error)
return
throw error
} finally {
this.isCacheBusy = false
const sdkCallEndTime = Date.now()
const totalDurationSdkMs = sdkCallEndTime - sdkCallStartTime
const cacheHit = cacheReadTokens > 0
const cacheHitPercentage = promptTokens > 0 ? (cacheReadTokens / promptTokens) * 100 : undefined
const throughputTokensPerSecSdk =
totalDurationSdkMs > 0 && outputTokens > 0 ? outputTokens / (totalDurationSdkMs / 1000) : undefined
if (this.options.taskId) {
telemetryService.captureGeminiApiPerformance(
this.options.taskId,
modelId,
{
ttftSec: ttftSdkMs !== undefined ? ttftSdkMs / 1000 : undefined,
totalDurationSec: totalDurationSdkMs / 1000,
promptTokens,
outputTokens,
cacheReadTokens,
cacheHit,
cacheHitPercentage,
apiSuccess,
apiError,
throughputTokensPerSec: throughputTokensPerSecSdk,
},
true,
)
} else {
console.warn("GeminiHandler: taskId not available for telemetry in createMessage.")
}
}
}
/**
* 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.
*
@@ -430,21 +218,18 @@ export class GeminiHandler implements ApiHandler {
* - Input token costs (for uncached tokens)
* - Output token costs
* - Cache read costs
* - Gemini implicit caching has no write 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
@@ -454,9 +239,7 @@ export class GeminiHandler implements ApiHandler {
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
@@ -465,7 +248,6 @@ export class GeminiHandler implements ApiHandler {
if (tier) {
inputPrice = tier.inputPrice ?? inputPrice
outputPrice = tier.outputPrice ?? outputPrice
cacheWritesPrice = tier.cacheWritesPrice ?? cacheWritesPrice
cacheReadsPrice = tier.cacheReadsPrice ?? cacheReadsPrice
}
}
@@ -502,27 +284,6 @@ export class GeminiHandler implements ApiHandler {
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
*/
+2 -2
View File
@@ -65,7 +65,7 @@ export class LiteLlmHandler implements ApiHandler {
const reasoningOn = budgetTokens !== 0 ? true : false
const thinkingConfig = reasoningOn ? { type: "enabled", budget_tokens: budgetTokens } : undefined
let temperature: number | undefined = 0
let temperature: number | undefined = this.options.liteLlmModelInfo?.temperature ?? 0
if (isOminiModel && reasoningOn) {
temperature = undefined // Thinking mode doesn't support temperature
@@ -169,7 +169,7 @@ export class LiteLlmHandler implements ApiHandler {
getModel() {
return {
id: this.options.liteLlmModelId || liteLlmDefaultModelId,
info: liteLlmModelInfoSaneDefaults,
info: this.options.liteLlmModelInfo || liteLlmModelInfoSaneDefaults,
}
}
}
+2 -1
View File
@@ -66,8 +66,9 @@ export class OpenAiNativeHandler implements ApiHandler {
messages: [{ role: "developer", content: systemPrompt }, ...convertToOpenAiMessages(messages)],
stream: true,
stream_options: { include_usage: true },
reasoning_effort: (this.options.o3MiniReasoningEffort as ChatCompletionReasoningEffort) || "medium",
reasoning_effort: (this.options.reasoningEffort as ChatCompletionReasoningEffort) || "medium",
})
for await (const chunk of stream) {
const delta = chunk.choices[0]?.delta
if (delta?.content) {
+1 -1
View File
@@ -65,7 +65,7 @@ export class OpenAiHandler implements ApiHandler {
if (isReasoningModelFamily) {
openAiMessages = [{ role: "developer", content: systemPrompt }, ...convertToOpenAiMessages(messages)]
temperature = undefined // does not support temperature
reasoningEffort = (this.options.o3MiniReasoningEffort as ChatCompletionReasoningEffort) || "medium"
reasoningEffort = (this.options.reasoningEffort as ChatCompletionReasoningEffort) || "medium"
}
const stream = await this.client.chat.completions.create({
+1 -1
View File
@@ -35,7 +35,7 @@ export class OpenRouterHandler implements ApiHandler {
systemPrompt,
messages,
this.getModel(),
this.options.o3MiniReasoningEffort,
this.options.reasoningEffort,
this.options.thinkingBudgetTokens,
this.options.openRouterProviderSorting,
)
+1 -1
View File
@@ -32,7 +32,7 @@ export class RequestyHandler implements ApiHandler {
...convertToOpenAiMessages(messages),
]
const reasoningEffort = this.options.o3MiniReasoningEffort || "medium"
const reasoningEffort = this.options.reasoningEffort || "medium"
const reasoning = { reasoning_effort: reasoningEffort }
const reasoningArgs = model.id.startsWith("openai/o") ? reasoning : {}
+9
View File
@@ -54,6 +54,15 @@ export function withRetry(options: RetryOptions = {}) {
delay = Math.min(maxDelay, baseDelay * Math.pow(2, attempt))
}
const handlerInstance = this as any
if (handlerInstance.options?.onRetryAttempt) {
try {
handlerInstance.options.onRetryAttempt(attempt + 1, maxRetries, delay, error)
} catch (e) {
console.error("Error in onRetryAttempt callback:", e)
}
}
await new Promise((resolve) => setTimeout(resolve, delay))
}
}
+2 -70
View File
@@ -9,7 +9,7 @@ export async function createOpenRouterStream(
systemPrompt: string,
messages: Anthropic.Messages.MessageParam[],
model: { id: string; info: ModelInfo },
o3MiniReasoningEffort?: string,
reasoningEffort?: string,
thinkingBudgetTokens?: number,
openRouterProviderSorting?: string,
) {
@@ -75,74 +75,6 @@ export async function createOpenRouterStream(
break
}
// handles gemini caching logic
if (model.id.startsWith("google/") && model.info.supportsPromptCache) {
// 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" },
},
],
}
// for safety, but this should always be the case
if (openAiMessages.length >= 2) {
const msg = openAiMessages[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" }
}
}
}
// it doesn't make sense to alter breakpoints at all with the gemini cache implementation at this time
/*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" }
}
}
}*/
}
// Not sure how openrouter defaults max tokens when no value is provided, but the anthropic api requires this value and since they offer both 4096 and 8192 variants, we should ensure 8192.
// (models usually default to max tokens allowed)
let maxTokens: number | undefined
@@ -212,7 +144,7 @@ export async function createOpenRouterStream(
stream_options: { include_usage: true },
transforms: shouldApplyMiddleOutTransform ? ["middle-out"] : undefined,
include_reasoning: true,
...(model.id.startsWith("openai/o") ? { reasoning_effort: o3MiniReasoningEffort || "medium" } : {}),
...(model.id.startsWith("openai/o") ? { reasoning_effort: reasoningEffort || "medium" } : {}),
...(reasoning ? { reasoning } : {}),
...(openRouterProviderSorting ? { provider: { sort: openRouterProviderSorting } } : {}),
})
+7 -1
View File
@@ -1,6 +1,6 @@
export type AssistantMessageContent = TextContent | ToolUse
export { parseAssistantMessage } from "./parse-assistant-message"
export { parseAssistantMessageV1, parseAssistantMessageV2 } from "./parse-assistant-message"
export interface TextContent {
type: "text"
@@ -25,6 +25,7 @@ export const toolUseNames = [
"attempt_completion",
"new_task",
"condense",
"report_bug",
"new_rule",
] as const
@@ -53,6 +54,11 @@ export const toolParamNames = [
"response",
"result",
"context",
"title",
"what_happened",
"steps_to_reproduce",
"api_request_output",
"additional_context",
] as const
export type ToolParamName = (typeof toolParamNames)[number]
@@ -1,6 +1,24 @@
import { AssistantMessageContent, TextContent, ToolUse, ToolParamName, toolParamNames, toolUseNames, ToolUseName } from "."
import { AssistantMessageContent, TextContent, ToolUse, ToolParamName, toolParamNames, toolUseNames, ToolUseName } from "." // Assuming types are defined in index.ts or a similar file
export function parseAssistantMessage(assistantMessage: string) {
/**
* @description **Version 1**
* Parses an assistant message string potentially containing mixed text and tool usage blocks
* marked with XML-like tags into an array of structured content objects.
*
* This version iterates through the message character by character, building an accumulator string.
* It maintains state to track whether it's currently parsing text, a tool use block, or a specific tool parameter.
* It detects the start and end of tool uses and parameters by checking if the accumulator ends with
* the corresponding opening or closing tags.
* Special handling is included for `write_to_file` and `new_rule` tool uses to correctly parse
* the `content` parameter, which might contain the closing tag itself, by looking for the *last*
* occurrence of the closing tag.
* If the input string ends mid-tag or mid-content, the last block (text or tool use) is marked as partial.
*
* @param assistantMessage The raw string output from the assistant.
* @returns An array of `AssistantMessageContent` objects, which can be `TextContent` or `ToolUse`.
* Blocks that were not fully closed by the end of the input string will have their `partial` flag set to `true`.
*/
export function parseAssistantMessageV1(assistantMessage: string): AssistantMessageContent[] {
const contentBlocks: AssistantMessageContent[] = []
let currentTextContent: TextContent | undefined = undefined
let currentTextContentStartIndex = 0
@@ -14,46 +32,56 @@ export function parseAssistantMessage(assistantMessage: string) {
const char = assistantMessage[i]
accumulator += char
// --- State: Parsing a Tool Parameter ---
// there should not be a param without a tool use
if (currentToolUse && currentParamName) {
const currentParamValue = accumulator.slice(currentParamValueStartIndex)
const paramClosingTag = `</${currentParamName}>`
if (currentParamValue.endsWith(paramClosingTag)) {
// end of param value
// End of param value found
currentToolUse.params[currentParamName] = currentParamValue.slice(0, -paramClosingTag.length).trim()
currentParamName = undefined
continue
currentParamName = undefined // Go back to parsing tool content or looking for next param
continue // Move to next character
} else {
// partial param value is accumulating
continue
// Partial param value is accumulating
continue // Move to next character
}
}
// --- State: Parsing a Tool Use (but not a specific parameter) ---
// no currentParamName
if (currentToolUse) {
const currentToolValue = accumulator.slice(currentToolUseStartIndex)
const toolUseClosingTag = `</${currentToolUse.name}>`
if (currentToolValue.endsWith(toolUseClosingTag)) {
// end of a tool use
// End of a tool use found
currentToolUse.partial = false
contentBlocks.push(currentToolUse)
currentToolUse = undefined
continue
currentToolUse = undefined // Go back to parsing text or looking for next tool
// Reset text start index in case text follows immediately
currentTextContentStartIndex = i + 1
continue // Move to next character
} else {
// Check if starting a new parameter within the current tool use
const possibleParamOpeningTags = toolParamNames.map((name) => `<${name}>`)
let foundParamStart = false
for (const paramOpeningTag of possibleParamOpeningTags) {
if (accumulator.endsWith(paramOpeningTag)) {
// start of a new parameter
// Start of a new parameter found
currentParamName = paramOpeningTag.slice(1, -1) as ToolParamName
currentParamValueStartIndex = accumulator.length
foundParamStart = true
break
}
}
if (foundParamStart) {
continue // Move to next character
}
// there's no current param, and not starting a new param
// 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.
// Special case for write_to_file/new_rule content param allowing nested tags
// Check if a </content> tag appears, potentially indicating the end of the content param
// even if the main tool closing tag hasn't been seen yet.
const contentParamName: ToolParamName = "content"
if (
(currentToolUse.name === "write_to_file" || currentToolUse.name === "new_rule") &&
@@ -63,73 +91,384 @@ export function parseAssistantMessage(assistantMessage: string) {
const contentStartTag = `<${contentParamName}>`
const contentEndTag = `</${contentParamName}>`
const contentStartIndex = toolContent.indexOf(contentStartTag) + contentStartTag.length
// Use lastIndexOf to handle cases where </content> might appear within the content itself
const contentEndIndex = toolContent.lastIndexOf(contentEndTag)
if (contentStartIndex !== -1 && contentEndIndex !== -1 && contentEndIndex > contentStartIndex) {
currentToolUse.params[contentParamName] = toolContent.slice(contentStartIndex, contentEndIndex).trim()
// Ensure we found valid start/end tags and end is after start
if (
contentStartIndex !== -1 &&
contentEndIndex !== -1 &&
contentEndIndex > contentStartIndex - contentStartTag.length // Ensure end tag is after start tag begins
) {
// Check if this content param was already being parsed. If so, update it.
// If not, and we just found the closing tag, assign it.
// This handles cases where the </content> detection might fire before
// the <content> tag detection logic, or if the content is very short.
if (currentParamName === contentParamName) {
// Already parsing content, now we found the end tag
currentToolUse.params[contentParamName] = toolContent.slice(contentStartIndex, contentEndIndex).trim()
currentParamName = undefined // Finished with this param
} else if (currentParamName === undefined) {
// Not parsing a param, but found </content>. Assume it closes the content block.
currentToolUse.params[contentParamName] = toolContent.slice(contentStartIndex, contentEndIndex).trim()
// We stay in the "parsing tool use" state, looking for more params or the tool end tag.
}
}
}
// partial tool value is accumulating
continue
// If none of the above, partial tool value is accumulating
continue // Move to next character
}
}
// --- State: Parsing Text (or looking for start of a tool use) ---
// no currentToolUse
let didStartToolUse = false
const possibleToolUseOpeningTags = toolUseNames.map((name) => `<${name}>`)
for (const toolUseOpeningTag of possibleToolUseOpeningTags) {
if (accumulator.endsWith(toolUseOpeningTag)) {
// start of a new tool use
// Start of a new tool use found
const toolName = toolUseOpeningTag.slice(1, -1) as ToolUseName
currentToolUse = {
type: "tool_use",
name: toolUseOpeningTag.slice(1, -1) as ToolUseName,
name: toolName,
params: {},
partial: true,
}
currentToolUseStartIndex = accumulator.length
// this also indicates the end of the current text content
// This also indicates the end of the current text content block (if any)
if (currentTextContent) {
currentTextContent.partial = false
// remove the partially accumulated tool use tag from the end of text (<tool)
currentTextContent.content = currentTextContent.content
.slice(0, -toolUseOpeningTag.slice(0, -1).length)
.trim()
contentBlocks.push(currentTextContent)
// Extract text content, removing the part that formed the tool opening tag
const textEndIndex = accumulator.length - toolUseOpeningTag.length
currentTextContent.content = accumulator.slice(currentTextContentStartIndex, textEndIndex).trim()
// Only add if there's actual content
if (currentTextContent.content.length > 0) {
contentBlocks.push(currentTextContent)
}
currentTextContent = undefined
} else {
// Check if there was text before this tool use started
const textEndIndex = accumulator.length - toolUseOpeningTag.length
const potentialText = accumulator.slice(currentTextContentStartIndex, textEndIndex).trim()
if (potentialText.length > 0) {
contentBlocks.push({
type: "text",
content: potentialText,
partial: false, // Ended because tool use started
})
}
}
didStartToolUse = true
break
break // Found tool start, stop checking for others
}
}
if (!didStartToolUse) {
// no tool use, so it must be text either at the beginning or between tools
// No tool use started, so it must be text content accumulating
// (or continuing after a closed tool use)
if (currentTextContent === undefined) {
currentTextContentStartIndex = i
}
currentTextContent = {
type: "text",
content: accumulator.slice(currentTextContentStartIndex).trim(),
partial: true,
}
}
}
// Start of a new text block
currentTextContentStartIndex = i - (accumulator.length - currentTextContentStartIndex - 1) // Adjust start index based on how much we've accumulated since the last block ended or the beginning
// If accumulator starts from 0, start index is i
if (contentBlocks.length === 0 && currentToolUse === undefined) {
currentTextContentStartIndex = accumulator.length - 1 // i
} else {
// Re-calculate based on the actual start of the current text segment
// Find the end of the last block
let lastBlockEndIndex = 0
if (contentBlocks.length > 0) {
const lastBlock = contentBlocks[contentBlocks.length - 1]
// Approximation: find where the accumulator matches the end of the message string representation of the last block. This is complex.
// Simpler: Assume text starts right after the last block ended implicitly at index i.
lastBlockEndIndex = i // Where the loop *was* when the last block finished processing
// Need a more robust way to track the end index of the *raw string* corresponding to the last block.
// Let's stick to the accumulator slice approach for simplicity in this version.
// The start index should be where the current *unmatched* text began.
let lastProcessedIndex = -1
if (contentBlocks.length > 0) {
// This requires knowing the raw string length of the previous block, which V1 doesn't explicitly track easily.
// We'll approximate based on the current accumulator and start index logic.
// The issue arises if a tool tag was just closed. accumulator contains everything up to i.
// lastBlockEndIndex should point to the character *after* the closing tag of the last block.
}
// Reset start index to the beginning of the *current* potential text block
currentTextContentStartIndex = accumulator.length - 1 // Start accumulating from the current character `i`
}
// If we just closed a tool, text starts *after* its closing tag
// The logic needs refinement here for accurate start index after a tool closure.
// Let's assume for now the start index logic inside the loop handles it via slicing.
}
currentTextContent = {
type: "text",
content: "", // Content will be filled by slicing accumulator
partial: true,
}
}
// Update text content based on the accumulator from its start index
currentTextContent.content = accumulator.slice(currentTextContentStartIndex).trimStart() // Trim start to avoid leading space if text follows tool
}
} // End of loop
// --- Finalization after loop ---
// If a tool use was open at the end
if (currentToolUse) {
// stream did not complete tool call, add it as partial
// If a parameter was open within that tool use
if (currentParamName) {
// tool call has a parameter that was not completed
// The remaining accumulator content belongs to this partial parameter
currentToolUse.params[currentParamName] = accumulator.slice(currentParamValueStartIndex).trim()
}
// Add the potentially partial tool use block
contentBlocks.push(currentToolUse)
}
// If text content was being accumulated at the end
// Note: Only one of currentToolUse or currentTextContent can be defined here,
// as starting a tool use finalizes the preceding text block.
else if (currentTextContent) {
// Update content one last time
currentTextContent.content = accumulator.slice(currentTextContentStartIndex).trim()
// Add the potentially partial text block only if it contains content
if (currentTextContent.content.length > 0) {
contentBlocks.push(currentTextContent)
}
}
// Note: it doesn't matter if check for currentToolUse or currentTextContent, only one of them will be defined since only one can be partial at a time
if (currentTextContent) {
// stream did not complete text content, add it as partial
contentBlocks.push(currentTextContent)
return contentBlocks
}
/**
* @description **Version 2**
* Parses an assistant message string potentially containing mixed text and tool usage blocks
* marked with XML-like tags into an array of structured content objects.
*
* This version aims for efficiency by avoiding the character-by-character accumulator of V1.
* It iterates through the string using an index `i`. At each position, it checks if the substring
* *ending* at `i` matches any known opening or closing tags for tools or parameters using `startsWith`
* with an offset.
* It uses pre-computed Maps (`toolUseOpenTags`, `toolParamOpenTags`) for quick tag lookups.
* State is managed using indices (`currentTextContentStart`, `currentToolUseStart`, `currentParamValueStart`)
* pointing to the start of the current block within the original `assistantMessage` string.
* Slicing is used to extract content only when a block (text, parameter, or tool use) is completed.
* Special handling for `write_to_file` and `new_rule` content parameters is included, using `indexOf`
* and `lastIndexOf` on the relevant slice to handle potentially nested closing tags.
* If the input string ends mid-block, the last open block is added and marked as partial.
*
* @param assistantMessage The raw string output from the assistant.
* @returns An array of `AssistantMessageContent` objects, which can be `TextContent` or `ToolUse`.
* Blocks that were not fully closed by the end of the input string will have their `partial` flag set to `true`.
*/
export function parseAssistantMessageV2(assistantMessage: string): AssistantMessageContent[] {
const contentBlocks: AssistantMessageContent[] = []
let currentTextContentStart = 0 // Index where the current text block started
let currentTextContent: TextContent | undefined = undefined
let currentToolUseStart = 0 // Index *after* the opening tag of the current tool use
let currentToolUse: ToolUse | undefined = undefined
let currentParamValueStart = 0 // Index *after* the opening tag of the current param
let currentParamName: ToolParamName | undefined = undefined
// Precompute tags for faster lookups
const toolUseOpenTags = new Map<string, ToolUseName>()
const toolParamOpenTags = new Map<string, ToolParamName>()
for (const name of toolUseNames) {
toolUseOpenTags.set(`<${name}>`, name)
}
for (const name of toolParamNames) {
toolParamOpenTags.set(`<${name}>`, name)
}
const len = assistantMessage.length
for (let i = 0; i < len; i++) {
const currentCharIndex = i
// --- State: Parsing a Tool Parameter ---
if (currentToolUse && currentParamName) {
const closeTag = `</${currentParamName}>`
// Check if the string *ending* at index `i` matches the closing tag
if (
currentCharIndex >= closeTag.length - 1 &&
assistantMessage.startsWith(
closeTag,
currentCharIndex - closeTag.length + 1, // Start checking from potential start of tag
)
) {
// Found the closing tag for the parameter
const value = assistantMessage
.slice(
currentParamValueStart, // Start after the opening tag
currentCharIndex - closeTag.length + 1, // End before the closing tag
)
.trim()
currentToolUse.params[currentParamName] = value
currentParamName = undefined // Go back to parsing tool content
// We don't continue loop here, need to check for tool close or other params at index i
} else {
continue // Still inside param value, move to next char
}
}
// --- State: Parsing a Tool Use (but not a specific parameter) ---
if (currentToolUse && !currentParamName) {
// Ensure we are not inside a parameter already
// Check if starting a new parameter
let startedNewParam = false
for (const [tag, paramName] of toolParamOpenTags.entries()) {
if (currentCharIndex >= tag.length - 1 && assistantMessage.startsWith(tag, currentCharIndex - tag.length + 1)) {
currentParamName = paramName
currentParamValueStart = currentCharIndex + 1 // Value starts after the tag
startedNewParam = true
break
}
}
if (startedNewParam) {
continue // Handled start of param, move to next char
}
// Check if closing the current tool use
const toolCloseTag = `</${currentToolUse.name}>`
if (
currentCharIndex >= toolCloseTag.length - 1 &&
assistantMessage.startsWith(toolCloseTag, currentCharIndex - toolCloseTag.length + 1)
) {
// End of the tool use found
// Special handling for content params *before* finalizing the tool
const toolContentSlice = assistantMessage.slice(
currentToolUseStart, // From after the tool opening tag
currentCharIndex - toolCloseTag.length + 1, // To before the tool closing tag
)
// Check if content parameter needs special handling (write_to_file/new_rule)
// This check is important if the closing </content> tag was missed by the parameter parsing logic
// (e.g., if content is empty or parsing logic prioritizes tool close)
const contentParamName: ToolParamName = "content"
if (
currentToolUse.name === "write_to_file" /* || currentToolUse.name === "new_rule" */ &&
toolContentSlice.includes(`<${contentParamName}>`)
) {
const contentStartTag = `<${contentParamName}>`
const contentEndTag = `</${contentParamName}>`
const contentStart = toolContentSlice.indexOf(contentStartTag)
// Use lastIndexOf for robustness against nested tags
const contentEnd = toolContentSlice.lastIndexOf(contentEndTag)
if (contentStart !== -1 && contentEnd !== -1 && contentEnd > contentStart) {
const contentValue = toolContentSlice.slice(contentStart + contentStartTag.length, contentEnd).trim()
currentToolUse.params[contentParamName] = contentValue
}
}
currentToolUse.partial = false // Mark as complete
contentBlocks.push(currentToolUse)
currentToolUse = undefined // Reset state
currentTextContentStart = currentCharIndex + 1 // Potential text starts after this tag
continue // Move to next char
}
// If not starting a param and not closing the tool, continue accumulating tool content implicitly
continue
}
// --- State: Parsing Text / Looking for Tool Start ---
if (!currentToolUse) {
// Check if starting a new tool use
let startedNewTool = false
for (const [tag, toolName] of toolUseOpenTags.entries()) {
if (currentCharIndex >= tag.length - 1 && assistantMessage.startsWith(tag, currentCharIndex - tag.length + 1)) {
// End current text block if one was active
if (currentTextContent) {
currentTextContent.content = assistantMessage
.slice(
currentTextContentStart, // From where text started
currentCharIndex - tag.length + 1, // To before the tool tag starts
)
.trim()
currentTextContent.partial = false // Ended because tool started
if (currentTextContent.content.length > 0) {
contentBlocks.push(currentTextContent)
}
currentTextContent = undefined
} else {
// Check for any text between the last block and this tag
const potentialText = assistantMessage
.slice(
currentTextContentStart, // From where text *might* have started
currentCharIndex - tag.length + 1, // To before the tool tag starts
)
.trim()
if (potentialText.length > 0) {
contentBlocks.push({
type: "text",
content: potentialText,
partial: false,
})
}
}
// Start the new tool use
currentToolUse = {
type: "tool_use",
name: toolName,
params: {},
partial: true, // Assume partial until closing tag is found
}
currentToolUseStart = currentCharIndex + 1 // Tool content starts after the opening tag
startedNewTool = true
break
}
}
if (startedNewTool) {
continue // Handled start of tool, move to next char
}
// If not starting a tool, it must be text content
if (!currentTextContent) {
// Start a new text block if we aren't already in one
currentTextContentStart = currentCharIndex // Text starts at the current character
// Check if the current char is the start of potential text *immediately* after a tag
// This needs the previous state - simpler to let slicing handle it later.
// Resetting start index accurately is key.
// It should be the index *after* the last processed tag.
// The logic managing currentTextContentStart after closing tags handles this.
currentTextContent = {
type: "text",
content: "", // Will be determined by slicing at the end or when a tool starts
partial: true,
}
}
// Continue accumulating text implicitly; content is extracted later.
}
} // End of loop
// --- Finalization after loop ---
// Finalize any open parameter within an open tool use
if (currentToolUse && currentParamName) {
currentToolUse.params[currentParamName] = assistantMessage
.slice(currentParamValueStart) // From param start to end of string
.trim()
// Tool use remains partial
}
// Finalize any open tool use (which might contain the finalized partial param)
if (currentToolUse) {
// Tool use is partial because the loop finished before its closing tag
contentBlocks.push(currentToolUse)
}
// Finalize any trailing text content
// Only possible if a tool use wasn't open at the very end
else if (currentTextContent) {
currentTextContent.content = assistantMessage
.slice(currentTextContentStart) // From text start to end of string
.trim()
// Text is partial because the loop finished
if (currentTextContent.content.length > 0) {
contentBlocks.push(currentTextContent)
}
}
return contentBlocks
@@ -8,45 +8,6 @@ import { getGlobalState, getWorkspaceState, updateGlobalState, updateWorkspaceSt
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)) {
@@ -80,7 +41,8 @@ export const getLocalClineRules = async (cwd: string, toggles: ClineRulesToggles
if (await fileExistsAtPath(clineRulesFilePath)) {
if (await isDirectory(clineRulesFilePath)) {
try {
const rulesFilePaths = await readDirectory(clineRulesFilePath)
const rulesFilePaths = await readDirectory(clineRulesFilePath, [[".clinerules", "workflows"]])
const rulesFilesTotalContent = await getRuleFilesTotalContent(rulesFilePaths, cwd, toggles)
if (rulesFilesTotalContent) {
clineRulesFileInstructions = formatResponse.clineRulesLocalDirectoryInstructions(cwd, rulesFilesTotalContent)
@@ -121,7 +83,9 @@ export async function refreshClineRulesToggles(
// Local toggles
const localClineRulesToggles = ((await getWorkspaceState(context, "localClineRulesToggles")) as ClineRulesToggles) || {}
const localClineRulesFilePath = path.resolve(workingDirectory, GlobalFileNames.clineRules)
const updatedLocalToggles = await synchronizeRuleToggles(localClineRulesFilePath, localClineRulesToggles)
const updatedLocalToggles = await synchronizeRuleToggles(localClineRulesFilePath, localClineRulesToggles, "", [
[".clinerules", "workflows"],
])
await updateWorkspaceState(context, "localClineRulesToggles", updatedLocalToggles)
return {
@@ -129,82 +93,3 @@ export async function refreshClineRulesToggles(
localToggles: updatedLocalToggles,
}
}
export const createRuleFile = async (isGlobal: boolean, filename: string, cwd: string) => {
try {
let filePath: string
if (isGlobal) {
const globalClineRulesFilePath = await ensureRulesDirectoryExists()
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)
}
const fileExists = await fileExistsAtPath(filePath)
if (fileExists) {
return { filePath, fileExists }
}
await fs.writeFile(filePath, "", "utf8")
return { filePath, fileExists: false }
} catch (error) {
return { filePath: null, fileExists: false }
}
}
export async function deleteRuleFile(
context: vscode.ExtensionContext,
rulePath: string,
isGlobal: boolean,
): Promise<{ success: boolean; message: string }> {
try {
// Check if file exists
const fileExists = await fileExistsAtPath(rulePath)
if (!fileExists) {
return {
success: false,
message: `Rule file does not exist: ${rulePath}`,
}
}
// Delete the file from disk
await fs.unlink(rulePath)
// Get the filename for messages
const fileName = path.basename(rulePath)
// Update the appropriate toggles
if (isGlobal) {
const toggles = ((await getGlobalState(context, "globalClineRulesToggles")) as ClineRulesToggles) || {}
delete toggles[rulePath]
await updateGlobalState(context, "globalClineRulesToggles", toggles)
} else {
const toggles = ((await getWorkspaceState(context, "localClineRulesToggles")) as ClineRulesToggles) || {}
delete toggles[rulePath]
await updateWorkspaceState(context, "localClineRulesToggles", toggles)
}
return {
success: true,
message: `Rule file "${fileName}" deleted successfully`,
}
} catch (error) {
const errorMessage = error instanceof Error ? error.message : String(error)
console.error(`Error deleting rule file: ${errorMessage}`, error)
return {
success: false,
message: `Failed to delete rule file.`,
}
}
}
@@ -1,14 +1,21 @@
import { fileExistsAtPath, isDirectory, readDirectory } from "@utils/fs"
import { ensureRulesDirectoryExists, GlobalFileNames } from "@core/storage/disk"
import { getGlobalState, getWorkspaceState, updateGlobalState, updateWorkspaceState } from "@core/storage/state"
import * as path from "path"
import fs from "fs/promises"
import { ClineRulesToggles } from "@shared/cline-rules"
import * as vscode from "vscode"
/**
* Recursively traverses directory and finds all files, including checking for optional whitelisted file extension
*/
export async function readDirectoryRecursive(directoryPath: string, allowedFileExtension: string): Promise<string[]> {
export async function readDirectoryRecursive(
directoryPath: string,
allowedFileExtension: string,
excludedPaths: string[][] = [],
): Promise<string[]> {
try {
const entries = await readDirectory(directoryPath)
const entries = await readDirectory(directoryPath, excludedPaths)
let results: string[] = []
for (const entry of entries) {
if (allowedFileExtension !== "") {
@@ -33,6 +40,7 @@ export async function synchronizeRuleToggles(
rulesDirectoryPath: string,
currentToggles: ClineRulesToggles,
allowedFileExtension: string = "",
excludedPaths: string[][] = [],
): Promise<ClineRulesToggles> {
// Create a copy of toggles to modify
const updatedToggles = { ...currentToggles }
@@ -45,7 +53,7 @@ export async function synchronizeRuleToggles(
if (isDir) {
// DIRECTORY CASE
const filePaths = await readDirectoryRecursive(rulesDirectoryPath, allowedFileExtension)
const filePaths = await readDirectoryRecursive(rulesDirectoryPath, allowedFileExtension, excludedPaths)
const existingRulePaths = new Set<string>()
for (const filePath of filePaths) {
@@ -119,3 +127,155 @@ export const getRuleFilesTotalContent = async (rulesFilePaths: string[], basePat
).then((contents) => contents.filter(Boolean).join("\n\n"))
return ruleFilesTotalContent
}
/**
* Handles converting any directory into a file (specifically used for .clinerules and .clinerules/workflows)
* The old .clinerules file or .clinerules/workflows file will be renamed to a default filename
* Doesn't do anything if the dir already exists or doesn't exist
* Returns whether there are any uncaught errors
*/
export async function ensureLocalClineDirExists(clinerulePath: string, defaultRuleFilename: string): Promise<boolean> {
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
}
}
/**
* Create a rule file or workflow file
*/
export const createRuleFile = async (isGlobal: boolean, filename: string, cwd: string, type: string) => {
try {
let filePath: string
if (isGlobal) {
// global means its implicitly clinerules
const globalClineRulesFilePath = await ensureRulesDirectoryExists()
filePath = path.join(globalClineRulesFilePath, filename)
} else {
const localClineRulesFilePath = path.resolve(cwd, GlobalFileNames.clineRules)
const hasError = await ensureLocalClineDirExists(localClineRulesFilePath, "default-rules.md")
if (hasError === true) {
return { filePath: null, fileExists: false }
}
await fs.mkdir(localClineRulesFilePath, { recursive: true })
if (type === "workflow") {
const localWorkflowsFilePath = path.resolve(cwd, GlobalFileNames.workflows)
const hasError = await ensureLocalClineDirExists(localWorkflowsFilePath, "default-workflows.md")
if (hasError === true) {
return { filePath: null, fileExists: false }
}
await fs.mkdir(localWorkflowsFilePath, { recursive: true })
filePath = path.join(localWorkflowsFilePath, filename)
} else {
// clinerules file creation
filePath = path.join(localClineRulesFilePath, filename)
}
}
const fileExists = await fileExistsAtPath(filePath)
if (fileExists) {
return { filePath, fileExists }
}
await fs.writeFile(filePath, "", "utf8")
return { filePath, fileExists: false }
} catch (error) {
return { filePath: null, fileExists: false }
}
}
/**
* Delete a rule file or workflow file
*/
export async function deleteRuleFile(
context: vscode.ExtensionContext,
rulePath: string,
isGlobal: boolean,
type: string,
): Promise<{ success: boolean; message: string }> {
try {
// Check if file exists
const fileExists = await fileExistsAtPath(rulePath)
if (!fileExists) {
return {
success: false,
message: `File does not exist: ${rulePath}`,
}
}
// Delete the file from disk
await fs.unlink(rulePath)
// Get the filename for messages
const fileName = path.basename(rulePath)
// Update the appropriate toggles
if (isGlobal) {
const toggles = ((await getGlobalState(context, "globalClineRulesToggles")) as ClineRulesToggles) || {}
delete toggles[rulePath]
await updateGlobalState(context, "globalClineRulesToggles", toggles)
} else {
if (type === "workflow") {
const toggles = ((await getWorkspaceState(context, "workflowToggles")) as ClineRulesToggles) || {}
delete toggles[rulePath]
await updateWorkspaceState(context, "workflowToggles", toggles)
} else if (type === "cursor") {
const toggles = ((await getWorkspaceState(context, "localCursorRulesToggles")) as ClineRulesToggles) || {}
delete toggles[rulePath]
await updateWorkspaceState(context, "localCursorRulesToggles", toggles)
} else if (type === "windsurf") {
const toggles = ((await getWorkspaceState(context, "localWindsurfRulesToggles")) as ClineRulesToggles) || {}
delete toggles[rulePath]
await updateWorkspaceState(context, "localWindsurfRulesToggles", toggles)
} else {
const toggles = ((await getWorkspaceState(context, "localClineRulesToggles")) as ClineRulesToggles) || {}
delete toggles[rulePath]
await updateWorkspaceState(context, "localClineRulesToggles", toggles)
}
}
return {
success: true,
message: `File "${fileName}" deleted successfully`,
}
} catch (error) {
const errorMessage = error instanceof Error ? error.message : String(error)
console.error(`Error deleting file: ${errorMessage}`, error)
return {
success: false,
message: `Failed to delete file.`,
}
}
}
@@ -0,0 +1,20 @@
import path from "path"
import { GlobalFileNames } from "@core/storage/disk"
import { ClineRulesToggles } from "@shared/cline-rules"
import { getWorkspaceState, updateWorkspaceState } from "@core/storage/state"
import * as vscode from "vscode"
import { synchronizeRuleToggles } from "@core/context/instructions/user-instructions/rule-helpers"
/**
* Refresh the workflow toggles
*/
export async function refreshWorkflowToggles(
context: vscode.ExtensionContext,
workingDirectory: string,
): Promise<ClineRulesToggles> {
const workflowRulesToggles = ((await getWorkspaceState(context, "workflowToggles")) as ClineRulesToggles) || {}
const workflowsDirPath = path.resolve(workingDirectory, GlobalFileNames.workflows)
const updatedWorkflowToggles = await synchronizeRuleToggles(workflowsDirPath, workflowRulesToggles)
await updateWorkspaceState(context, "workflowToggles", updatedWorkflowToggles)
return updatedWorkflowToggles
}

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