diff --git a/.changes/extensions/intellij/0.0.34.md b/.changes/extensions/intellij/0.0.34.md
deleted file mode 100644
index d4dc58b80..000000000
--- a/.changes/extensions/intellij/0.0.34.md
+++ /dev/null
@@ -1,8 +0,0 @@
-## 0.0.34 - 2024-03-03
-### Added
-* diff context provider
-### Changed
-* Allow LLM servers to handle templating
-### Fixed
-* Fix a few context providers / slash commands
-* Fixed issues preventing proper extension startup
diff --git a/.changes/extensions/intellij/0.0.38.md b/.changes/extensions/intellij/0.0.38.md
deleted file mode 100644
index 6c42fc737..000000000
--- a/.changes/extensions/intellij/0.0.38.md
+++ /dev/null
@@ -1,4 +0,0 @@
-## 0.0.38 - 2024-03-15
-### Added
-* Remote config server support
-* Autocomplete support in JetBrains
diff --git a/.changes/extensions/intellij/0.0.42.md b/.changes/extensions/intellij/0.0.42.md
deleted file mode 100644
index dbcdd3fab..000000000
--- a/.changes/extensions/intellij/0.0.42.md
+++ /dev/null
@@ -1,7 +0,0 @@
-## 0.0.42 - 2024-04-12
-### Added
-* Inline cmd/ctrl+I in JetBrains
-### Fixed
-* Fixed character encoding error causing display issues
-* Fixed error causing input to constantly demand focus
-* Fixed automatic reloading of config.json
diff --git a/.changes/extensions/intellij/0.0.53.md b/.changes/extensions/intellij/0.0.53.md
deleted file mode 100644
index bbc3605ec..000000000
--- a/.changes/extensions/intellij/0.0.53.md
+++ /dev/null
@@ -1,8 +0,0 @@
-## 0.0.53 - 2024-07-10
-### Added
-* Support for .prompt files
-* New onboarding experience
-### Fixed
-* Indexing fixes from VS Code versions merged into IntelliJ
-* Improved codebase indexing reliability and testing
-* Fixes for autocomplete text positioning and timing
diff --git a/.changes/extensions/intellij/0.0.54.md b/.changes/extensions/intellij/0.0.54.md
deleted file mode 100644
index 1f0e05f27..000000000
--- a/.changes/extensions/intellij/0.0.54.md
+++ /dev/null
@@ -1,6 +0,0 @@
-## 0.0.54 - 2024-07-13
-### Added
-* Partial autocomplete acceptance
-* Autocomplete status bar spinner
-### Fixed
-* Fixed duplicate completion bug and others
diff --git a/.changes/extensions/intellij/0.0.69.md b/.changes/extensions/intellij/0.0.69.md
deleted file mode 100644
index a4b67ca0c..000000000
--- a/.changes/extensions/intellij/0.0.69.md
+++ /dev/null
@@ -1,7 +0,0 @@
-## 0.0.69 - 2024-09-22
-### Added
-* Support for the "search" context provider
-### Fixed
-* Fixed bug where only first module would be recognized
-* Improved concurrency handling to avoid freezes
-* Made compatible with latest JetBrains versions
diff --git a/.changes/extensions/intellij/0.0.72.md b/.changes/extensions/intellij/0.0.72.md
deleted file mode 100644
index 2e8962e43..000000000
--- a/.changes/extensions/intellij/0.0.72.md
+++ /dev/null
@@ -1,7 +0,0 @@
-## 0.0.72 - 2024-10-04
-### Added
-* Listen for changes to Intellij settings without requiring window reload
-### Changed
-* Updated tutorial file
-### Fixed
-* Fix ability to load config.ts in JetBrains IDEs
diff --git a/.changes/extensions/intellij/0.0.92.md b/.changes/extensions/intellij/0.0.92.md
deleted file mode 100644
index 2d3774eec..000000000
--- a/.changes/extensions/intellij/0.0.92.md
+++ /dev/null
@@ -1,5 +0,0 @@
-## 0.0.92 - 2025-02-26
-### Fixed
-* Off-screen rendering to solve white flash on load and lack of changing cursor type
-* OSR-related fixes for non-Mac users
-* Fixes for inline edit in JetBrains
diff --git a/.changes/extensions/intellij/1.0.0.md b/.changes/extensions/intellij/1.0.0.md
deleted file mode 100644
index 43ea4a0ed..000000000
--- a/.changes/extensions/intellij/1.0.0.md
+++ /dev/null
@@ -1,7 +0,0 @@
-## 1.0.0 - 2025-02-26
-### Added
-* Introduces hub.continue.dev
-* Improved theme matching
-### Fixed
-* Fixes interference between SonarQube and Continue autocomplete
-* Numerous reliability improvements
diff --git a/.changes/extensions/intellij/v0.0.1.md b/.changes/extensions/intellij/v0.0.1.md
deleted file mode 100644
index 8cf2b6b68..000000000
--- a/.changes/extensions/intellij/v0.0.1.md
+++ /dev/null
@@ -1,5 +0,0 @@
-## v0.0.1 - 2023-09-01
-
-### Added
-
-- Initial scaffold created from [IntelliJ Platform Plugin Template](https://github.com/JetBrains/intellij-platform-plugin-template)
diff --git a/.changes/extensions/intellij/v0.0.19.md b/.changes/extensions/intellij/v0.0.19.md
deleted file mode 100644
index 5d76c7d7e..000000000
--- a/.changes/extensions/intellij/v0.0.19.md
+++ /dev/null
@@ -1,5 +0,0 @@
-## v0.0.19 - 2023-11-19
-
-### Changed
-
-- migrated to .json config file format
diff --git a/.changes/extensions/intellij/v0.0.21.md b/.changes/extensions/intellij/v0.0.21.md
deleted file mode 100644
index 7933cd1b4..000000000
--- a/.changes/extensions/intellij/v0.0.21.md
+++ /dev/null
@@ -1,5 +0,0 @@
-## v0.0.21 - 2023-12-05
-
-### Added
-
-- updated to match latest VS Code updates
diff --git a/.changes/extensions/intellij/v0.0.25.md b/.changes/extensions/intellij/v0.0.25.md
deleted file mode 100644
index 67da2d004..000000000
--- a/.changes/extensions/intellij/v0.0.25.md
+++ /dev/null
@@ -1,5 +0,0 @@
-## v0.0.25 - 2023-12-25
-
-### Changed
-
-- Intellij extension no longer relies on the Continue Python server
diff --git a/.changes/extensions/intellij/v0.0.26.md b/.changes/extensions/intellij/v0.0.26.md
deleted file mode 100644
index 1ef77ba62..000000000
--- a/.changes/extensions/intellij/v0.0.26.md
+++ /dev/null
@@ -1,5 +0,0 @@
-## v0.0.26 - 2023-12-28
-### Added
-* auto-reloading of config on save
-### Fixed
-* Fixed /edit bug for versions without Python server
diff --git a/.changes/extensions/vscode/0.8.14.md b/.changes/extensions/vscode/0.8.14.md
deleted file mode 100644
index d42d9640c..000000000
--- a/.changes/extensions/vscode/0.8.14.md
+++ /dev/null
@@ -1,10 +0,0 @@
-## 0.8.14 - 2024-03-03
-### Added
-* Image support
-* Full-text search index for retrieval
-* Docs context provider
-* CodeLlama-70b support
-### Changed
-* config.ts only runs in NodeJS, not browser
-### Fixed
-* Fixed proxy setting in config.json
diff --git a/.changes/extensions/vscode/0.8.15.md b/.changes/extensions/vscode/0.8.15.md
deleted file mode 100644
index 0bee662f3..000000000
--- a/.changes/extensions/vscode/0.8.15.md
+++ /dev/null
@@ -1,3 +0,0 @@
-## 0.8.15 - 2024-03-05
-### Added
-* Tab-autocomplete in beta
diff --git a/.changes/extensions/vscode/0.8.24.md b/.changes/extensions/vscode/0.8.24.md
deleted file mode 100644
index 62c32d5e5..000000000
--- a/.changes/extensions/vscode/0.8.24.md
+++ /dev/null
@@ -1,5 +0,0 @@
-## 0.8.24 - 2024-04-12
-### Added
-* Support for improved retrieval models (Voyage embeddings/reranking)
-* New @code context provider
-* Personal usage analytics
diff --git a/.changes/extensions/vscode/0.8.42.md b/.changes/extensions/vscode/0.8.42.md
deleted file mode 100644
index 52bf46f18..000000000
--- a/.changes/extensions/vscode/0.8.42.md
+++ /dev/null
@@ -1,16 +0,0 @@
-## 0.8.42 - 2024-07-02
-
-### Added
-
-- Support for Gemini 1.5 Pro
-- Link to code in the sidebar when using codebase retrieval
-- Smoother onboarding experience
-- .prompt files, a way of saving and sharing slash commands
-- Support for Claude 3.5 Sonnet, Deepseek Coder v2, and other new models
-- Support for comments in config.json
-- Specify multiple autocomplete models and switch between them
-- Improved bracket matching strategy reduces noisy completions
-
-### Fixed
-
-- Numerous reliability upgrades to codebase indexing
diff --git a/.changes/extensions/vscode/0.8.43.md b/.changes/extensions/vscode/0.8.43.md
deleted file mode 100644
index ca3a4c9c6..000000000
--- a/.changes/extensions/vscode/0.8.43.md
+++ /dev/null
@@ -1,4 +0,0 @@
-## 0.8.43 - 2024-07-08
-### Added
-* Improved indexing reliability and testing
-* Quick Actions: use CodeLens to quickly take common actions like adding docstrings
diff --git a/.changes/extensions/vscode/0.8.45.md b/.changes/extensions/vscode/0.8.45.md
deleted file mode 100644
index bdeb5b698..000000000
--- a/.changes/extensions/vscode/0.8.45.md
+++ /dev/null
@@ -1,12 +0,0 @@
-## 0.8.45 - 2024-08-05
-### Added
-* Support for Llama 3.1 and gpt-4o-mini
-* Support for WatsonX+Granite models
-### Changed
-* Significant improvements to indexing performance
-* Improved @codebase quality by more accurately searching over file names and paths
-* Improved @codebase accuracy
-* Further improvements to indexing performance
-### Fixed
-* Improved docs indexing and management
-* Fixed Gemini embeddings provider
diff --git a/.changes/extensions/vscode/0.8.46.md b/.changes/extensions/vscode/0.8.46.md
deleted file mode 100644
index 176439b9e..000000000
--- a/.changes/extensions/vscode/0.8.46.md
+++ /dev/null
@@ -1,6 +0,0 @@
-## 0.8.46 - 2024-08-11
-### Added
-* new /onboard slash command
-### Fixed
-* Fixed problem loading config.ts
-* Fixed bug causing duplicate indexing work
diff --git a/.changes/extensions/vscode/0.8.47.md b/.changes/extensions/vscode/0.8.47.md
deleted file mode 100644
index 363081c3c..000000000
--- a/.changes/extensions/vscode/0.8.47.md
+++ /dev/null
@@ -1,8 +0,0 @@
-## 0.8.47 - 2024-08-27
-### Added
-* Use headless browser for crawling to get better results
-* TTS support in the chat window
-### Changed
-* Improved support for WatsonX models
-### Fixed
-* Fixed several small indexing bugs
diff --git a/.changes/extensions/vscode/0.8.48.md b/.changes/extensions/vscode/0.8.48.md
deleted file mode 100644
index 93e144168..000000000
--- a/.changes/extensions/vscode/0.8.48.md
+++ /dev/null
@@ -1,8 +0,0 @@
-## 0.8.48 - 2024-09-01
-### Added
-* Improved indexing progress UI
-* Improved @codebase using repomap
-* Repo map context provider
-### Fixed
-* Many small UI improvements
-* Fixes db.search not a function
diff --git a/.changes/extensions/vscode/0.8.49.md b/.changes/extensions/vscode/0.8.49.md
deleted file mode 100644
index b0100f493..000000000
--- a/.changes/extensions/vscode/0.8.49.md
+++ /dev/null
@@ -1,3 +0,0 @@
-## 0.8.49 - 2024-09-01
-### Fixed
-* Hotfix: submenu context providers
diff --git a/.changes/extensions/vscode/0.8.50.md b/.changes/extensions/vscode/0.8.50.md
deleted file mode 100644
index 41abe2817..000000000
--- a/.changes/extensions/vscode/0.8.50.md
+++ /dev/null
@@ -1,3 +0,0 @@
-## 0.8.50 - 2024-09-02
-### Fixed
-* Hotfix for ability to use more than one inline context provider
diff --git a/.changes/extensions/vscode/0.8.51.md b/.changes/extensions/vscode/0.8.51.md
deleted file mode 100644
index 2fbbbeb96..000000000
--- a/.changes/extensions/vscode/0.8.51.md
+++ /dev/null
@@ -1,3 +0,0 @@
-## 0.8.51 - 2024-09-05
-### Fixed
-* Fixed CRLF bug causing diff streams to treat every line as changed on Windows
diff --git a/.changes/extensions/vscode/0.8.52.md b/.changes/extensions/vscode/0.8.52.md
deleted file mode 100644
index 481f5e023..000000000
--- a/.changes/extensions/vscode/0.8.52.md
+++ /dev/null
@@ -1,4 +0,0 @@
-## 0.8.52 - 2024-09-16
-### Changed
-* Use Chromium only as a fallback after asking user
-* Redesigned onboarding flow
diff --git a/.changes/extensions/vscode/0.8.53.md b/.changes/extensions/vscode/0.8.53.md
deleted file mode 100644
index 575a3b91d..000000000
--- a/.changes/extensions/vscode/0.8.53.md
+++ /dev/null
@@ -1,12 +0,0 @@
-## 0.8.53 - 2024-10-11
-### Added
-* Improved loading/accept/reject UI for apply
-* Polished chat sidebar, especially context dropdown
-* Further prompt caching with Anthropic
-### Changed
-* Updated tutorial file
-* Improved styling on "More" page
-### Fixed
-* Continue for teams auth bug fix
-* Fixed a number of apply bugs
-* Fixed autoscrolling behavior
diff --git a/.changes/extensions/vscode/0.8.54.md b/.changes/extensions/vscode/0.8.54.md
deleted file mode 100644
index 90466954c..000000000
--- a/.changes/extensions/vscode/0.8.54.md
+++ /dev/null
@@ -1,3 +0,0 @@
-## 0.8.54 - 2024-10-15
-### Fixed
-* Hotfix: throttle transformers.js embeddings provider
diff --git a/.changes/extensions/vscode/0.8.55.md b/.changes/extensions/vscode/0.8.55.md
deleted file mode 100644
index 4800ad907..000000000
--- a/.changes/extensions/vscode/0.8.55.md
+++ /dev/null
@@ -1,9 +0,0 @@
-## 0.8.55 - 2024-10-25
-### Added
-* Web context provider
-* Cerebras inference provider
-* Automatic descriptions for previous chats
-* Discord context provider
-* Improved full screen UI
-### Changed
-* Easier way to accept/reject/re-prompt after cmd/ctrl+I
diff --git a/.changes/extensions/vscode/0.8.56.md b/.changes/extensions/vscode/0.8.56.md
deleted file mode 100644
index d1c81fd34..000000000
--- a/.changes/extensions/vscode/0.8.56.md
+++ /dev/null
@@ -1,4 +0,0 @@
-## 0.8.56 - 2024-11-08
-### Added
-* New Edit mode in sidebar (cmd/ctrl+I)
-* Significantly faster and more accurate docs crawler by default
diff --git a/.changes/extensions/vscode/0.8.58.md b/.changes/extensions/vscode/0.8.58.md
deleted file mode 100644
index 98c845b97..000000000
--- a/.changes/extensions/vscode/0.8.58.md
+++ /dev/null
@@ -1,25 +0,0 @@
-## 0.8.58 - 2024-11-22
-### Added
-* OpenAI predicted outputs support
-* Improve codebase retrieval with BM25
-* Support for Grok from xAI
-* Chat enhancements including sticking input to bottom
-* New UI for cmd+I in sidebar
-* Support for Nebius LLM provider
-* Support for Ask Sage LLM provider
-* Improved reference for config.json
-* New @web context provider
-* Updates for llama3.2
-* .continuerules file to set system prompt
-* .prompt files v2
-* Dedicated UI for docs indexing
-* Clickable code symbols in chat
-* Use clipboard content as autocomplete context
-### Changed
-* Improved @docs crawler
-* Many improvements to make autocomplete more eager
-* Near complete type definition retrieval for TypeScript autocomplete
-* Remove footer from chat sidebar
-### Fixed
-* Brought back the Apply button for all code blocks
-* Automatically update codebase index on removed files
diff --git a/.changes/extensions/vscode/0.8.59.md b/.changes/extensions/vscode/0.8.59.md
deleted file mode 100644
index 9f6dfbd04..000000000
--- a/.changes/extensions/vscode/0.8.59.md
+++ /dev/null
@@ -1,3 +0,0 @@
-## 0.8.59 - 2024-11-25
-### Fixed
-* Hotfix for Ollama onboarding
diff --git a/.changes/extensions/vscode/0.8.62.md b/.changes/extensions/vscode/0.8.62.md
deleted file mode 100644
index c258fd285..000000000
--- a/.changes/extensions/vscode/0.8.62.md
+++ /dev/null
@@ -1,6 +0,0 @@
-## 0.8.62 - 2024-12-10
-### Added
-* Tool use
-* Support for Model Context Protocol
-### Fixed
-* hotfix: context providers no longer hidden when not in edit mode
diff --git a/.changes/extensions/vscode/0.8.66.md b/.changes/extensions/vscode/0.8.66.md
deleted file mode 100644
index 4a1930978..000000000
--- a/.changes/extensions/vscode/0.8.66.md
+++ /dev/null
@@ -1,9 +0,0 @@
-## 0.8.66 - 2024-12-20
-### Changed
-* Improved autocomplete in untitled files
-### Fixed
-* Display more mid-line completions
-* Restored syntax highlighting
-* Fix tool use bug for models that don't support tools
-* Autodetect mistral API key type
-* Fixes Azure OpenAI regressions
diff --git a/.changes/extensions/vscode/1.0.0.md b/.changes/extensions/vscode/1.0.0.md
deleted file mode 100644
index cea7899ff..000000000
--- a/.changes/extensions/vscode/1.0.0.md
+++ /dev/null
@@ -1,6 +0,0 @@
-## 1.0.0 - 2025-02-26
-### Added
-* Introduces hub.continue.dev
-* Improved apply quality
-### Fixed
-* Numerous reliability improvements
diff --git a/.changes/extensions/vscode/v0.5.0.md b/.changes/extensions/vscode/v0.5.0.md
deleted file mode 100644
index 7df6df9ee..000000000
--- a/.changes/extensions/vscode/v0.5.0.md
+++ /dev/null
@@ -1,9 +0,0 @@
-## v0.5.0 - 2023-11-09
-
-### Added
-
-- Codebase Retrieval: Use /codebase or cmd+enter and Continue will automatically gather the most important context
-
-### Changed
-
-- Switch from Websockets to Socket.io
diff --git a/.changes/extensions/vscode/v0.6.0.md b/.changes/extensions/vscode/v0.6.0.md
deleted file mode 100644
index ee58a295c..000000000
--- a/.changes/extensions/vscode/v0.6.0.md
+++ /dev/null
@@ -1,11 +0,0 @@
-## v0.6.0 - 2023-11-10
-
-### Added
-
-- Full screen mode
-- StackOverflow slash command to augment with web search
-- VS Code context menus: right click to add code to context, debug the terminal, or share your Continue session
-
-### Fixed
-
-- Reliability improvements to JetBrains by bringing up-to-date with the socket.io refactor
diff --git a/.changes/extensions/vscode/v0.6.16.md b/.changes/extensions/vscode/v0.6.16.md
deleted file mode 100644
index e5d7e491e..000000000
--- a/.changes/extensions/vscode/v0.6.16.md
+++ /dev/null
@@ -1,6 +0,0 @@
-## v0.6.16 - 2023-12-25
-
-### Changed
-
-- Context items are now kept around as a part of past messages, instead of staying at the main input
-- No more Python server - Continue runs entirely in Typescript
diff --git a/.changes/extensions/vscode/v0.6.19.md b/.changes/extensions/vscode/v0.6.19.md
deleted file mode 100644
index d338fbf43..000000000
--- a/.changes/extensions/vscode/v0.6.19.md
+++ /dev/null
@@ -1,11 +0,0 @@
-## v0.6.19 - 2024-01-05
-
-### Added
-
-- support for .continuerc.json in root of workspace to override config.json
-- Inline context providers
-- cmd+shift+L with new diff streaming UI for edits
-
-### Changed
-
-- Allow certain LLM servers to handle templating
diff --git a/.changes/extensions/vscode/v0.6.4.md b/.changes/extensions/vscode/v0.6.4.md
deleted file mode 100644
index 9194b537d..000000000
--- a/.changes/extensions/vscode/v0.6.4.md
+++ /dev/null
@@ -1,5 +0,0 @@
-## v0.6.4 - 2023-11-19
-
-### Changed
-
-- migrated to .json config file format
diff --git a/.changes/extensions/vscode/v0.8.1.md b/.changes/extensions/vscode/v0.8.1.md
deleted file mode 100644
index 1a7a061ac..000000000
--- a/.changes/extensions/vscode/v0.8.1.md
+++ /dev/null
@@ -1,9 +0,0 @@
-## v0.8.1 - 2024-01-08
-
-### Added
-
-- disableSessionTitles option in config.json
-
-### Changed
-
-- Use Ollama /chat endpoint instead of raw completions by default, and /show endpoint to gather model parameters like context length and stop tokens
diff --git a/.changes/extensions/vscode/v0.8.2.md b/.changes/extensions/vscode/v0.8.2.md
deleted file mode 100644
index 40ada41a6..000000000
--- a/.changes/extensions/vscode/v0.8.2.md
+++ /dev/null
@@ -1,8 +0,0 @@
-## v0.8.2 - 2024-01-23
-### Added
-* Add codellama and gemini to free trial, using new server
-* Local codebase syncing and embeddings using LanceDB
-* Improved VS Code theme matching
-### Changed
-* Updates to packaging to download native modules for current platform (lancedb, sqlite, onnxruntime, tree-sitter wasms)
-* Context providers now run from the extension side (in Node.js instead of browser javascript)
diff --git a/.changes/header.tpl.md b/.changes/header.tpl.md
deleted file mode 100644
index 811d6f896..000000000
--- a/.changes/header.tpl.md
+++ /dev/null
@@ -1,5 +0,0 @@
-All notable changes to this project will be documented in this file.
-
-The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
-adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html),
-and is generated by [Changie](https://github.com/miniscruff/changie).
diff --git a/.changes/unreleased/.gitkeep b/.changes/unreleased/.gitkeep
deleted file mode 100644
index e69de29bb..000000000
diff --git a/.changie.yaml b/.changie.yaml
deleted file mode 100644
index 7a11e254d..000000000
--- a/.changie.yaml
+++ /dev/null
@@ -1,35 +0,0 @@
-changesDir: .changes
-unreleasedDir: unreleased
-headerPath: header.tpl.md
-changelogPath: CHANGELOG.md
-versionExt: md
-versionFormat: '## {{.Version}} - {{.Time.Format "2006-01-02"}}'
-kindFormat: "### {{.Kind}}"
-changeFormat: "* {{.Body}}"
-kinds:
- - label: Added
- auto: minor
- - label: Changed
- auto: major
- - label: Deprecated
- auto: minor
- - label: Removed
- auto: major
- - label: Fixed
- auto: patch
- - label: Security
- auto: patch
-newlines:
- afterChangelogHeader: 1
- beforeChangelogVersion: 1
- endOfVersion: 1
-envPrefix: CHANGIE_
-
-projects:
- - label: extensions/intellij
- key: extensions/intellij
- changelog: extensions/intellij/CHANGELOG.md
-
- - label: extensions/vscode
- key: extensions/vscode
- changelog: extensions/vscode/CHANGELOG.md
diff --git a/.continue/rules/bigger-picture-description-rules.yaml b/.continue/rules/bigger-picture-description-rules.yaml
new file mode 100644
index 000000000..4e076e88a
--- /dev/null
+++ b/.continue/rules/bigger-picture-description-rules.yaml
@@ -0,0 +1,13 @@
+name: bigger-picture-description-rules
+version: 0.0.1
+schema: v1
+rules:
+ - name: bigger-picture-description-rules
+ rule: >-
+ When a user asks how a certain part of the code works:
+
+ 1. Describe what the code does in isolation.
+
+ 2. If the code interacts with other parts of the codebase, describe how the code is imported and used in other parts of the codebase.
+
+ 3. When describing each use-case, include the parent function for clarity.
diff --git a/.continue/rules/colors.yaml b/.continue/rules/colors.yaml
new file mode 100644
index 000000000..8ca60672e
--- /dev/null
+++ b/.continue/rules/colors.yaml
@@ -0,0 +1,27 @@
+name: GUI
+version: 0.0.1
+schema: v1
+rules:
+ - name: Extension Color Themes
+ rule: |
+ When adding colors to components, use tailwind color classes.
+ Do NOT use explicit colors like text-gray-400. Instead, use theme colors.
+
+ The common available theme colors are:
+ - For normal text: foreground, description, description-muted
+ - For other text, icons, etc: success, warning, error, accent, link
+ - For general components background, border, border-focus
+ - For specific components:
+ - Button: primary, primary-foreground, primary-hover, secondary, secondary-foreground, secondary-hover
+ - Input: input, input-foreground, input-border, input-placeholder
+ - Badge: badge, badge-foreground
+ - List/Dropdown items: list-hover, list-active, list-active-foreground
+ - Code Editor: editor, editor-foreground
+
+ Any of these colors can be used in tailwind e.g. bg-primary, text-success, border-error, hover:bg-list-hover, etc.
+ globs: "gui/**/*.tsx"
+# Excluding the following less-used colors:
+# Command (only used by tip-tap): command, command-foreground, command-border, command-border-focus
+# Find widget colors: find-match, find-match-selected
+# table-oddRow
+
diff --git a/.continue/rules/continue-specificity.md b/.continue/rules/continue-specificity.md
new file mode 100644
index 000000000..4579e2444
--- /dev/null
+++ b/.continue/rules/continue-specificity.md
@@ -0,0 +1,9 @@
+---
+globs: /**/*.
+description: General questions about code completion should be answered specific to Continue
+---
+
+# Continue Specificity
+
+- In chat mode, if the user asks generally about code completion or developer tools, answer specifically regarding Continue and not other similar software.
+- Keep all suggestions and comments concentrated on Continue, unless the user asks otherwise. If the user does this, answer with no particular specificity to Continue.
diff --git a/.continue/rules/documentation-standards.md b/.continue/rules/documentation-standards.md
new file mode 100644
index 000000000..ff7235857
--- /dev/null
+++ b/.continue/rules/documentation-standards.md
@@ -0,0 +1,16 @@
+---
+globs: docs/**/*.{md,mdx}
+description: Standards for writing and maintaining Continue Docs
+---
+
+# Continue Docs Standards
+
+- Follow Docusaurus documentation standards
+- Include YAML frontmatter with title, description, and keywords
+- Use consistent heading hierarchy starting with h2 (##)
+- Include relevant Admonition components for tips, warnings, and info
+- Use descriptive alt text for images
+- Include cross-references to related documentation
+- Reference other docs with relative paths
+- Keep paragraphs concise and scannable
+- Use code blocks with appropriate language tags
\ No newline at end of file
diff --git a/.continue/rules/intellij-plugin-test-execution.yaml b/.continue/rules/intellij-plugin-test-execution.yaml
new file mode 100644
index 000000000..386a72a2b
--- /dev/null
+++ b/.continue/rules/intellij-plugin-test-execution.yaml
@@ -0,0 +1,15 @@
+name: IntelliJ Plugin Test Execution
+version: 0.0.1
+schema: v1
+rules:
+ - name: IntelliJ Plugin Test Execution
+ rule: |-
+ Run IntelliJ plugin tests using Gradle with the fully qualified test class or method name:
+ ```bash
+ # Run test class
+ ./gradlew test --tests "com.github.continuedev.continueintellijextension.unit.ApplyToFileHandlerTest"
+
+ # Run specific test method
+ ./gradlew test --tests "com.github.continuedev.continueintellijextension.unit.ApplyToFileHandlerTest.should*"
+ ```
+ globs: extensions/intellij/**/*Test.kt
diff --git a/.continue/rules/intellij-test-standards.yaml b/.continue/rules/intellij-test-standards.yaml
new file mode 100644
index 000000000..f706757e2
--- /dev/null
+++ b/.continue/rules/intellij-test-standards.yaml
@@ -0,0 +1,10 @@
+name: IntelliJ Test Standards
+version: 0.0.1
+schema: v1
+rules:
+ - name: IntelliJ Test Standards
+ rule: When writing tests for the IntelliJ plugin, use the mockk library for
+ mocking. Prefer mockk's idiomatic syntax for creating and verifying mocks.
+ Always structure tests with clear Arrange-Act-Assert patterns and use
+ descriptive test names that indicate the scenario being tested.
+ globs: "**/test/**/*.kt"
diff --git a/.continue/rules/llm-specificity.md b/.continue/rules/llm-specificity.md
new file mode 100644
index 000000000..4ff15c9e7
--- /dev/null
+++ b/.continue/rules/llm-specificity.md
@@ -0,0 +1,11 @@
+---
+globs: core/llm/llms/**/*.{ts,test.ts}
+description: Tailor recommendations for LLM code based on which specific LLM is being used.
+---
+
+# LLM Model Specificity
+
+- Refer to the file name and names of big classes to determine which LLM is being used in a file.
+- Ground all observations and recommendations with knowledge of that LLM.
+- Consider items such as context length, architecture, speed, and such.
+- Pay attention to the parent classes in these files.
diff --git a/.continue/rules/unit-testing-rules.yaml b/.continue/rules/unit-testing-rules.yaml
new file mode 100644
index 000000000..ec22e9467
--- /dev/null
+++ b/.continue/rules/unit-testing-rules.yaml
@@ -0,0 +1,30 @@
+name: unit-testing-rules
+version: 0.0.1
+schema: v1
+rules:
+ - name: unit-testing-rules
+ rule: >-
+ For unit testing in this project:
+
+
+ 1. The project uses Jest as the testing framework
+
+ 2. Run tests using `npm test` from within the specific package/module
+ directory
+
+ 3. Command structure: `cd [directory] && npm test -- [test file path]`
+
+ 4. The test script uses experimental VM modules via NODE_OPTIONS flag
+
+ 5. Test files follow the pattern `*.test.ts`
+
+ 6. Tests must import Jest with `import { jest } from "@jest/globals";`
+
+ 7. Run tests from within the specific package directory (e.g., `cd core`
+ for core module tests)
+
+ 8. Write tests as top-level `test()` functions - DO NOT use `describe()`
+ blocks
+
+ 9. Include the function name being tested in the test description for
+ clarity
diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md
index a005cffd7..2497e28dc 100644
--- a/.github/pull_request_template.md
+++ b/.github/pull_request_template.md
@@ -12,6 +12,6 @@
[ For visual changes, include screenshots. Screen recordings are particularly helpful, and appreciated! ]
-## Testing instructions
+## Tests
-[ For new or modified features, provide step-by-step testing instructions to validate the intended behavior of the change, including any relevant tests to run. ]
+[ What tests were added or updated to ensure the changes work as expected? ]
diff --git a/.github/workflows/cla.yaml b/.github/workflows/cla.yaml
new file mode 100644
index 000000000..1c170855c
--- /dev/null
+++ b/.github/workflows/cla.yaml
@@ -0,0 +1,30 @@
+name: "CLA Assistant"
+on:
+ issue_comment:
+ types: [created]
+ pull_request_target:
+ types: [opened, closed, synchronize]
+
+permissions:
+ actions: write
+ contents: write
+ pull-requests: write
+ statuses: write
+
+jobs:
+ CLAAssistant:
+ runs-on: ubuntu-latest
+ # Only run this workflow on the main repository (continuedev/continue)
+ if: github.repository == 'continuedev/continue'
+ steps:
+ - name: "CLA Assistant"
+ if: (contains(github.event.comment.body, 'recheck') || contains(github.event.comment.body, 'I have read the CLA Document and I hereby sign the CLA')) || github.event_name == 'pull_request_target'
+ uses: contributor-assistant/github-action@v2.6.1
+ env:
+ GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
+ with:
+ path-to-signatures: "signatures/version1/cla.json"
+ path-to-document: "https://github.com/continuedev/continue/blob/main/docs/docs/CLA.md"
+ branch: cla-signatures
+ allowlist: dependabot[bot]
+ signed-commit-message: "CLA signed in $pullRequestNo"
diff --git a/.github/workflows/jetbrains-release.yaml b/.github/workflows/jetbrains-release.yaml
index d1303995e..8ea3d2ebb 100644
--- a/.github/workflows/jetbrains-release.yaml
+++ b/.github/workflows/jetbrains-release.yaml
@@ -63,7 +63,7 @@ jobs:
- name: Bump version in gradle.properties
run: |
- cd extensions/intelllij
+ cd extensions/intellij
awk '/pluginVersion=/{split($0,a,"="); split(a[2],b,"."); b[3]+=1; printf "%s=%s.%s.%s\n",a[1],b[1],b[2],b[3];next}1' gradle.properties > tmp && mv tmp gradle.properties
rm -rf tmp
NEW_VERSION=$(grep 'pluginVersion=' gradle.properties | cut -d'=' -f2)
diff --git a/.github/workflows/main.yaml b/.github/workflows/main.yaml
index 29965a305..0c300bf17 100644
--- a/.github/workflows/main.yaml
+++ b/.github/workflows/main.yaml
@@ -235,7 +235,7 @@ jobs:
- name: Publish to VS Code Marketplace
run: |
cd extensions/vscode
- npx vsce publish --packagePath ../../vsix-artifacts/*.vsix
+ npx @vscode/vsce publish --packagePath ../../vsix-artifacts/*.vsix
env:
VSCE_PAT: ${{ secrets.VSCE_TOKEN }}
diff --git a/.github/workflows/metrics.yaml b/.github/workflows/metrics.yaml
new file mode 100644
index 000000000..1ee476aaf
--- /dev/null
+++ b/.github/workflows/metrics.yaml
@@ -0,0 +1,75 @@
+name: Monthly issue metrics
+on:
+ workflow_dispatch:
+ schedule:
+ # Runs every Monday at 9:00 AM PST (17:00 UTC)
+ - cron: "0 17 * * 1"
+
+ push:
+ branches:
+ - nate/metrics-action
+
+permissions:
+ contents: read
+
+jobs:
+ build:
+ name: issue metrics
+ runs-on: ubuntu-latest
+ permissions:
+ issues: write
+ pull-requests: read
+ steps:
+ - name: Get dates for last month
+ shell: bash
+ run: |
+ # Calculate the first day of the previous month
+ first_day=$(date -d "last month" +%Y-%m-01)
+
+ # Calculate the last day of the previous month
+ last_day=$(date -d "$first_day +1 month -1 day" +%Y-%m-%d)
+
+ #Set an environment variable with the date range
+ echo "$first_day..$last_day"
+ echo "last_month=$first_day..$last_day" >> "$GITHUB_ENV"
+
+ - name: Run issue-metrics tool
+ uses: github/issue-metrics@v3
+ env:
+ GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
+ SEARCH_QUERY: 'repo:continuedev/continue created:${{ env.last_month }} -reason:"not planned"'
+
+ - name: Read metrics file content
+ id: read-metrics
+ run: |
+ content=$(cat ./issue_metrics.md)
+ # This prepares the content in a way that can be used in GitHub Actions
+ content="${content//'%'/'%25'}"
+ content="${content//$'\n'/'%0A'}"
+ # content="${content//$'\r'/'%0D'}"
+ echo "metrics_content=$content" >> "$GITHUB_OUTPUT"
+
+ - name: Post a message in a channel
+ uses: slackapi/slack-github-action@v2.1.0
+ with:
+ webhook: ${{ secrets.ISSUE_PR_METRICS_SLACK_WEBHOOK_URL }}
+ webhook-type: incoming-webhook
+ payload: |
+ text: "Issue / PR Metrics Report"
+ blocks:
+ - type: "header"
+ text:
+ type: "plain_text"
+ text: "Monthly Issue Metrics Report"
+ emoji: true
+ - type: "section"
+ text:
+ type: "mrkdwn"
+ text: |
+ ${{ steps.read-metrics.outputs.metrics_content }}
+
+ - name: Upload metrics report as artifact
+ uses: actions/upload-artifact@v4
+ with:
+ name: issue-metrics-report
+ path: ./issue_metrics.md
diff --git a/.github/workflows/pr_checks.yaml b/.github/workflows/pr_checks.yaml
index c490373a0..eec79f4c6 100644
--- a/.github/workflows/pr_checks.yaml
+++ b/.github/workflows/pr_checks.yaml
@@ -235,10 +235,11 @@ jobs:
cd packages/config-yaml
npm run build
- - name: Type check
+ - name: Type check and lint
run: |
cd gui
npx tsc --noEmit
+ npm run lint
binary-checks:
needs: [install-root, install-core, install-config-yaml]
@@ -670,13 +671,6 @@ jobs:
cd extensions/vscode
rm -rf e2e/.test-extensions/continue*
- - name: Upload e2e test screenshots
- if: failure()
- uses: actions/upload-artifact@v4
- with:
- name: e2e-failure-screenshots
- path: extensions/vscode/e2e/storage/screenshots
-
- name: Sanitize test file name
id: sanitize_filename
if: always()
@@ -685,6 +679,13 @@ jobs:
SANITIZED_FILENAME="${FILENAME//\//-}" # Replace / with - using bash parameter expansion
echo "sanitized_test_file=${SANITIZED_FILENAME}" >> $GITHUB_OUTPUT
+ - name: Upload e2e test screenshots
+ if: failure()
+ uses: actions/upload-artifact@v4
+ with:
+ name: e2e-failure-screenshots-${{ steps.sanitize_filename.outputs.sanitized_test_file || 'unknown' }}-${{ matrix.command == 'e2e:ci:run-yaml' && 'yaml' || 'json' }}
+ path: extensions/vscode/e2e/storage/screenshots
+
- name: Find e2e log file
if: always()
run: |
diff --git a/.github/workflows/preview.yaml b/.github/workflows/preview.yaml
index 23ea26bf6..19dafeb41 100644
--- a/.github/workflows/preview.yaml
+++ b/.github/workflows/preview.yaml
@@ -232,7 +232,7 @@ jobs:
- name: Publish to VS Code Marketplace
run: |
cd extensions/vscode
- npx vsce publish --pre-release --packagePath ../../vsix-artifacts/*.vsix
+ npx @vscode/vsce publish --pre-release --packagePath ../../vsix-artifacts/*.vsix
env:
VSCE_PAT: ${{ secrets.VSCE_TOKEN }}
diff --git a/.gitignore b/.gitignore
index 2ca914069..d3ad46eaf 100644
--- a/.gitignore
+++ b/.gitignore
@@ -144,6 +144,7 @@ Icon?
.continuerc.json
.aider*
+*.notes.md
notes.md
manual-testing-sandbox/.idea/**
@@ -162,5 +163,9 @@ extensions/.continue-debug/
*.vsix
+# intellij module library files
+*.iml
+
.continuerules
-**/.continue/assistants/
\ No newline at end of file
+**/.continue/assistants/
+keys
\ No newline at end of file
diff --git a/.idea/jsLinters/eslint.xml b/.idea/jsLinters/eslint.xml
new file mode 100644
index 000000000..541945bb0
--- /dev/null
+++ b/.idea/jsLinters/eslint.xml
@@ -0,0 +1,6 @@
+
+
+
+
+
+
\ No newline at end of file
diff --git a/.idea/prettier.xml b/.idea/prettier.xml
index b0c1c68fb..0c83ac4e8 100644
--- a/.idea/prettier.xml
+++ b/.idea/prettier.xml
@@ -2,5 +2,6 @@
+
\ No newline at end of file
diff --git a/.idea/runConfigurations/config_yaml_tests.xml b/.idea/runConfigurations/config_yaml_tests.xml
new file mode 100644
index 000000000..69aaa8bb3
--- /dev/null
+++ b/.idea/runConfigurations/config_yaml_tests.xml
@@ -0,0 +1,22 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/.idea/runConfigurations/core_tests.xml b/.idea/runConfigurations/core_tests.xml
new file mode 100644
index 000000000..0fd435646
--- /dev/null
+++ b/.idea/runConfigurations/core_tests.xml
@@ -0,0 +1,12 @@
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/.idea/runConfigurations/openai_adapters_configuration.xml b/.idea/runConfigurations/openai_adapters_configuration.xml
new file mode 100644
index 000000000..b50fa94c5
--- /dev/null
+++ b/.idea/runConfigurations/openai_adapters_configuration.xml
@@ -0,0 +1,25 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/.idea/vcs.xml b/.idea/vcs.xml
index 35eb1ddfb..7ddfc9ed4 100644
--- a/.idea/vcs.xml
+++ b/.idea/vcs.xml
@@ -1,5 +1,11 @@
+
+
+
+
+
+
diff --git a/.vscode/extensions.json b/.vscode/extensions.json
index 2e93694c0..2b440ff66 100644
--- a/.vscode/extensions.json
+++ b/.vscode/extensions.json
@@ -5,6 +5,7 @@
"dbaeumer.vscode-eslint",
"esbenp.prettier-vscode",
"bradlc.vscode-tailwindcss",
- "YoavBls.pretty-ts-errors"
+ "YoavBls.pretty-ts-errors",
+ "github.vscode-github-actions"
]
}
diff --git a/.vscode/settings.json b/.vscode/settings.json
index db2967d2e..d17afc5ae 100644
--- a/.vscode/settings.json
+++ b/.vscode/settings.json
@@ -45,6 +45,7 @@
"extensions/.continue-debug": true
// "sync/**": true
},
+ "editor.formatOnSave": true,
"eslint.workingDirectories": ["./core"],
"typescript.tsdk": "node_modules/typescript/lib",
"conventionalCommits.showNewVersionNotes": false,
diff --git a/CHANGELOG.md b/CHANGELOG.md
deleted file mode 100644
index 268bbe613..000000000
--- a/CHANGELOG.md
+++ /dev/null
@@ -1,6 +0,0 @@
-# Changelog
-
-Separate changelogs are kept for each extension:
-
-- [VS Code Extension](./extensions/vscode/CHANGELOG.md)
-- [JetBrains Extension](./extensions/intellij/CHANGELOG.md)
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 5b730190a..1b981a612 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -22,6 +22,7 @@
- [Our Git Workflow](#our-git-workflow)
- [Development workflow](#development-workflow)
- [Formatting](#formatting)
+ - [Theme Colors](#theme-colors)
- [Testing](#testing)
- [Review Process](#review-process)
- [Getting help](#getting-help)
@@ -31,16 +32,21 @@
- [📐 Continue Architecture](#-continue-architecture)
- [Continue VS Code Extension](#continue-vs-code-extension)
- [Continue JetBrains Extension](#continue-jetbrains-extension)
+ - [Contibutor License Agreement](#contributor-license-agreement-cla)
# ❤️ Ways to Contribute
## 👋 Continue Contribution Ideas
-[This GitHub project board](https://github.com/orgs/continuedev/projects/2) is a list of ideas for how you can contribute to Continue. These aren't the only ways, but are a great starting point if you are new to the project.
+[This GitHub project board](https://github.com/orgs/continuedev/projects/2) is a list of ideas for how you can
+contribute to Continue. These aren't the only ways, but are a great starting point if you are new to the project. You
+can also browse the list
+of [good first issues](https://github.com/continuedev/continue/issues?q=is:issue%20state:open%20label:good-first-issue).
## 🐛 Report Bugs
-If you find a bug, please [create an issue](https://github.com/continuedev/continue/issues) to report it! A great bug report includes:
+If you find a bug, please [create an issue](https://github.com/continuedev/continue/issues) to report it! A great bug
+report includes:
- A description of the bug
- Steps to reproduce
@@ -50,7 +56,8 @@ If you find a bug, please [create an issue](https://github.com/continuedev/conti
## ✨ Suggest Enhancements
-Continue is quickly adding features, and we'd love to hear which are the most important to you. The best ways to suggest an enhancement are:
+Continue is quickly adding features, and we'd love to hear which are the most important to you. The best ways to suggest
+an enhancement are:
- Create an issue
@@ -62,7 +69,9 @@ Continue is quickly adding features, and we'd love to hear which are the most im
## 📖 Updating / Improving Documentation
-Continue is continuously improving, but a feature isn't complete until it is reflected in the documentation! If you see something out-of-date or missing, you can help by clicking "Edit this page" at the bottom of any page on [docs.continue.dev](https://docs.continue.dev).
+Continue is continuously improving, but a feature isn't complete until it is reflected in the documentation! If you see
+something out-of-date or missing, you can help by clicking "Edit this page" at the bottom of any page
+on [docs.continue.dev](https://docs.continue.dev).
### Running the Documentation Server Locally
@@ -70,7 +79,8 @@ You can run the documentation server locally using either of the following metho
#### Method 1: NPM Script
-1. Open your terminal and navigate to the `docs` subdirectory of the project. The `docusaurus.config.js` file you'll see there is a sign you're in the right place.
+1. Open your terminal and navigate to the `docs` subdirectory of the project. The `docusaurus.config.js` file you'll see
+ there is a sign you're in the right place.
2. Run the following command to install the necessary dependencies for the documentation server:
@@ -92,17 +102,22 @@ You can run the documentation server locally using either of the following metho
3. Look for the `docs:start` task and select it.
-This will start a local server and you can see the documentation rendered in your default browser, typically accessible at `http://localhost:3000`.
+This will start a local server and you can see the documentation rendered in your default browser, typically accessible
+at `http://localhost:3000`.
## 🧑💻 Contributing Code
-We welcome contributions from developers of all experience levels - from first-time contributors to seasoned open source maintainers. While we aim to maintain high standards for reliability and maintainability, our goal is to keep the process as welcoming and straightforward as possible.
+We welcome contributions from developers of all experience levels - from first-time contributors to seasoned open source
+maintainers. While we aim to maintain high standards for reliability and maintainability, our goal is to keep the
+process as welcoming and straightforward as possible.
### Environment Setup
#### Pre-requisites
-You should have Node.js version 20.19.0 (LTS) or higher installed. You can get it on [nodejs.org](https://nodejs.org/en/download) or, if you are using NVM (Node Version Manager), you can set the correct version of Node.js for this project by running the following command in the root of the project:
+You should have Node.js version 20.19.0 (LTS) or higher installed. You can get it
+on [nodejs.org](https://nodejs.org/en/download) or, if you are using NVM (Node Version Manager), you can set the correct
+version of Node.js for this project by running the following command in the root of the project:
```bash
nvm use
@@ -114,13 +129,15 @@ nvm use
2. Clone your forked repository to your local machine. Use: `git clone https://github.com/YOUR_USERNAME/continue.git`
-3. Navigate to the cloned directory and make sure you are on the main branch. Create your feature/fix branch from there, like so: `git checkout -b 123-my-feature-branch`
+3. Navigate to the cloned directory and make sure you are on the main branch. Create your feature/fix branch from there,
+ like so: `git checkout -b 123-my-feature-branch`
4. Send your pull request to the main branch.
#### VS Code
-1. Open the VS Code command pallet (`cmd/ctrl+shift+p`) and select `Tasks: Run Task` and then select `install-all-dependencies`
+1. Open the VS Code command pallet (`cmd/ctrl+shift+p`) and select `Tasks: Run Task` and then select
+ `install-all-dependencies`
2. Start debugging:
@@ -131,15 +148,20 @@ nvm use
1. The new VS Code window with the extension is referred to as the _Host VS Code_
2. The window you started debugging from is referred to as the _Main VS Code_
-3. To package the extension, run `npm run package` in the `extensions/vscode` directory, select `Tasks: Run Task` and then select `vscode-extension:package`. This will generate `extensions/vscode/build/continue-{VERSION}.vsix`, which you can install by right-clicking and selecting "Install Extension VSIX".
+3. To package the extension, run `npm run package` in the `extensions/vscode` directory, select `Tasks: Run Task` and
+ then select `vscode-extension:package`. This will generate `extensions/vscode/build/continue-{VERSION}.vsix`, which
+ you can install by right-clicking and selecting "Install Extension VSIX".
##### Debugging
-**Breakpoints** can be used in both the `core` and `extensions/vscode` folders while debugging, but are not currently supported inside of `gui` code.
+**Breakpoints** can be used in both the `core` and `extensions/vscode` folders while debugging, but are not currently
+supported inside of `gui` code.
-**Hot-reloading** is enabled with Vite, so if you make any changes to the `gui`, they should be automatically reflected without rebuilding. In some cases, you may need to refresh the _Host VS Code_ window to see the changes.
+**Hot-reloading** is enabled with Vite, so if you make any changes to the `gui`, they should be automatically reflected
+without rebuilding. In some cases, you may need to refresh the _Host VS Code_ window to see the changes.
-Similarly, any changes to `core` or `extensions/vscode` will be automatically included by just reloading the _Host VS Code_ window with cmd/ctrl+shift+p "Reload Window".
+Similarly, any changes to `core` or `extensions/vscode` will be automatically included by just reloading the _Host VS
+Code_ window with cmd/ctrl+shift+p "Reload Window".
#### JetBrains
@@ -147,11 +169,20 @@ See [`intellij/CONTRIBUTING.md`](./extensions/intellij/CONTRIBUTING.md) for the
### Our Git Workflow
-We keep a single permanent branch: `main`. When we are ready to create a "pre-release" version, we create a tag on the `main` branch titled `v0.9.x-vscode`, which automatically triggers the workflow in [preview.yaml](./.github/workflows/preview.yaml), which builds and releases a version of the VS Code extension. When a release has been sufficiently tested, we will create a new release titled `v0.8.x-vscode`, triggering a similar workflow in [main.yaml](./.github/workflows/main.yaml), which will build and release a main release of the VS Code extension. Any hotfixes can be made by creating a feature branch from the tag for the release in question. This workflow is well explained by .
+We keep a single permanent branch: `main`. When we are ready to create a "pre-release" version, we create a tag on the
+`main` branch titled `v1.1.x-vscode`, which automatically triggers the workflow
+in [preview.yaml](./.github/workflows/preview.yaml), which builds and releases a version of the VS Code extension. When
+a release has been sufficiently tested, we will create a new release titled `v1.0x-vscode`, triggering a similar
+workflow in [main.yaml](./.github/workflows/main.yaml), which will build and release a main release of the VS Code
+extension. Any hotfixes can be made by creating a feature branch from the tag for the release in question. This workflow
+is well explained by .
-### Development workflow
+### What makes a good PR?
-- Open a new issue or comment on an existing one before writing code. This ensures your proposed changes are aligned with the project direction.
+To keep the Continue codebase clean and maintainable, we expect the following from our own team and all contributors:
+
+- Open a new issue or comment on an existing one before writing code. This ensures your proposed changes are aligned
+ with the project direction
- Keep changes focused. Multiple unrelated fixes should be opened as separate PRs
- Write or update tests for new functionality
- Update relevant documentation in the `docs` folder
@@ -159,18 +190,38 @@ We keep a single permanent branch: `main`. When we are ready to create a "pre-re
### Formatting
-Continue uses [Prettier](https://marketplace.visualstudio.com/items?itemName=esbenp.prettier-vscode) to format JavaScript/TypeScript. Please install the Prettier extension in VS Code and enable "Format on Save" in your settings.
+Continue uses [Prettier](https://marketplace.visualstudio.com/items?itemName=esbenp.prettier-vscode) to format
+JavaScript/TypeScript. Please install the Prettier extension in VS Code and enable "Format on Save" in your settings.
+
+### Theme Colors
+
+Continue has a set of named theme colors that we map to extension colors and tailwind classes, which can be found in [gui/src/styles/theme.ts](gui/src/styles/theme.ts)
+
+Guidelines for using theme colors:
+
+- Use Tailwind colors whenever possible. If developing in VS Code, download the [Tailwind CSS Intellisense extension](https://marketplace.visualstudio.com/items?itemName=bradlc.vscode-tailwindcss) for great suggestions
+- Avoid using any explicit classes and CSS variables outside the theme (e.g. `text-yellow-400`)
+
+Guidelines for adding/updating theme colors:
+
+- Choose sensible VS Code variables to add/update in [gui/src/styles/theme.ts](gui/src/styles/theme.ts) (see [here](https://code.visualstudio.com/api/references/theme-color) and [here](https://www.notion.so/1fa1d55165f78097b551e3bc296fcf76?pvs=25) for inspiration)
+- Choose sensible Jetbrains named colors to add/update in `GetTheme.kt` (flagship LLMs can give you good suggestions to try)
+- Update `tailwind.config.js` if needed
+- Use the Theme Test Page to check colors. This can be accessed by going to `Settings` -> `Help` -> `Theme Test Page` in dev/debug mode.
### Testing
-We have a mix of unit, functional, and e2e test suites, with a primary focus on functional testing. These tests run on each pull request. If your PR causes one of these tests to fail, we will ask that you to resolve the issue before we merge.
+We have a mix of unit, functional, and e2e test suites, with a primary focus on functional testing. These tests run on
+each pull request. If your PR causes one of these tests to fail, we will ask that you to resolve the issue before we
+merge.
When contributing, please update or create the appropriate tests to help verify the correctness of your implementaiton.
### Review Process
- **Initial Review** - A maintainer will be assigned as primary reviewer
-- **Feedback Loop** - The reviewer may request changes. We value your work, but also want to ensure the code is maintainable and follows our patterns.
+- **Feedback Loop** - The reviewer may request changes. We value your work, but also want to ensure the code is
+ maintainable and follows our patterns.
- **Approval & Merge** - Once the PR is approved, it will be merged into the `main` branch.
### Getting help
@@ -181,42 +232,53 @@ Join [#contribute on Discord](https://discord.gg/vapESyrFmJ) to engage with main
### Adding an LLM Provider
-Continue has support for more than a dozen different LLM "providers", making it easy to use models running on OpenAI, Ollama, Together, LM Studio, Msty, and more. You can find all of the existing providers [here](https://github.com/continuedev/continue/tree/main/core/llm/llms), and if you see one missing, you can add it with the following steps:
-
-1. Create a new file in the `core/llm/llms` directory. The name of the file should be the name of the provider, and it should export a class that extends `BaseLLM`. This class should contain the following minimal implementation. We recommend viewing pre-existing providers for more details. The [LlamaCpp Provider](./core/llm/llms/LlamaCpp.ts) is a good simple example.
-
-- `providerName` - the identifier for your provider.
-- At least one of `_streamComplete` or `_streamChat` - This is the function that makes the request to the API and returns the streamed response. You only need to implement one because Continue can automatically convert between "chat" and "raw completion".
+Continue has support for more than a dozen different LLM "providers", making it easy to use models running on OpenAI,
+Ollama, Together, LM Studio, Msty, and more. You can find all of the existing
+providers [here](https://github.com/continuedev/continue/tree/main/core/llm/llms), and if you see one missing, you can
+add it with the following steps:
+1. Create a new file in the `core/llm/llms` directory. The name of the file should be the name of the provider, and it
+ should export a class that extends `BaseLLM`. This class should contain the following minimal implementation. We
+ recommend viewing pre-existing providers for more details. The [LlamaCpp Provider](./core/llm/llms/LlamaCpp.ts) is a
+ good simple example.
2. Add your provider to the `LLMs` array in [core/llm/llms/index.ts](./core/llm/llms/index.ts).
-3. If your provider supports images, add it to the `PROVIDER_SUPPORTS_IMAGES` array in [core/llm/autodetect.ts](./core/llm/autodetect.ts).
-4. Add the necessary JSON Schema types to [`config_schema.json`](./extensions/vscode/config_schema.json). This makes sure that Intellisense shows users what options are available for your provider when they are editing `config.json`.
-5. Add a documentation page for your provider in [`docs/docs/customize/model-providers`](./docs/docs/customize/model-providers). This should show an example of configuring your provider in `config.json` and explain what options are available.
+3. If your provider supports images, add it to the `PROVIDER_SUPPORTS_IMAGES` array
+ in [core/llm/autodetect.ts](./core/llm/autodetect.ts).
+4. Add a documentation page for your provider in [
+ `docs/docs/customize/model-providers/more`](./docs/docs/customize/model-providers/more). This should show an example
+ of configuring your provider in `config.yaml` and explain what options are available.
### Adding Models
-While any model that works with a supported provider can be used with Continue, we keep a list of recommended models that can be automatically configured from the UI or `config.json`. The following files should be updated when adding a model:
+While any model that works with a supported provider can be used with Continue, we keep a list of recommended models
+that can be automatically configured from the UI or `config.json`. The following files should be updated when adding a
+model:
-- [config_schema.json](./extensions/vscode/config_schema.json) - This is the JSON Schema definition that is used to validate `config.json`. You'll notice a number of rules defined in "definitions.ModelDescription.allOf". Here is where you write rules that can specify something like "for the provider 'anthropic', only models 'claude-2' and 'claude-instant-1' are allowed. Look through all of these rules and make sure that your model is included for providers that support it.
-- [AddNewModel page](./gui/src/pages/AddNewModel) - This directory defines which model options are shown in the side bar model selection UI. To add a new model:
- 1. Add a `ModelPackage` entry for the model into [configs/models.ts](./gui/src/pages/AddNewModel/configs/models.ts), following the lead of the many examples near the top of the file
- 2. Add the model within its provider's array to [AddNewModel.tsx](./gui/src/pages/AddNewModel/AddNewModel.tsx) (add provider if needed)
-- [index.d.ts](./core/index.d.ts) - This file defines the TypeScript types used throughout Continue. You'll find a `ModelName` type. Be sure to add the name of your model to this.
-- LLM Providers: Since many providers use their own custom strings to identify models, you'll have to add the translation from Continue's model name (the one you added to `index.d.ts`) and the model string for each of these providers: [Ollama](./core/llm/llms/Ollama.ts), [Together](./core/llm/llms/Together.ts), and [Replicate](./core/llm/llms/Replicate.ts). You can find their full model lists here: [Ollama](https://ollama.ai/library), [Together](https://docs.together.ai/docs/inference-models), [Replicate](https://replicate.com/collections/streaming-language-models).
-- [Prompt Templates](./core/llm/index.ts) - In this file you'll find the `autodetectTemplateType` function. Make sure that for the model name you just added, this function returns the correct template type. This is assuming that the chat template for that model is already built in Continue. If not, you will have to add the template type and corresponding edit and chat templates.
+- [AddNewModel page](./gui/src/pages/AddNewModel/configs/) - This directory defines which model options are shown in the
+ side bar model selection UI. To add a new model:
+ 1. Add a `ModelPackage` entry for the model into [configs/models.ts](./gui/src/pages/AddNewModel/configs/models.ts),
+ following the lead of the many examples near the top of the file
+ 2. Add the model within its provider's array
+ to [configs/providers.ts](./gui/src/pages/AddNewModel/configs/providers.ts) (add provider if needed)
+- LLM Providers: Since many providers use their own custom strings to identify models, you'll have to add the
+ translation from Continue's model name (the one you added to `index.d.ts`) and the model string for each of these
+ providers: [Ollama](./core/llm/llms/Ollama.ts), [Together](./core/llm/llms/Together.ts),
+ and [Replicate](./core/llm/llms/Replicate.ts). You can find their full model lists
+ here: [Ollama](https://ollama.ai/library), [Together](https://docs.together.ai/docs/inference-models), [Replicate](https://replicate.com/collections/streaming-language-models).
+- [Prompt Templates](./core/llm/autodetect.ts) - In this file you'll find the `autodetectTemplateType` function. Make
+ sure that for the model name you just added, this function returns the correct template type. This is assuming that
+ the chat template for that model is already built in Continue. If not, you will have to add the template type and
+ corresponding edit and chat templates.
-## 📐 Continue Architecture
+## Contributor License Agreement (CLA)
-Continue consists of 2 parts that are split so that it can be extended to work in other IDEs as easily as possible:
+We require all contributors to accept the CLA and have made it as easy as commenting on your PR:
-1. **Continue GUI** - The Continue GUI is a React application that gives the user control over Continue. It displays the current chat history, allows the user to ask questions, invoke slash commands, and use context providers. The GUI also handles most state and holds as much of the logic as possible so that it can be reused between IDEs.
+1. Open your pull request.
+2. Paste the following comment (or reply `recheck` if you’ve signed before):
-2. **Continue Extension** - The Continue Extension is a plugin for the IDE which implements the [IDE Interface](./core/index.d.ts#L229). This allows the GUI to request information from or actions to be taken within the IDE. This same interface is used regardless of IDE. The first Continue extensions we have built are for VS Code and JetBrains, but we plan to build clients for other IDEs in the future. The IDE Client must 1. implement IDE Interface, as is done [here](./extensions/vscode/src/VsCodeIde.ts) for VS Code and 2. display the Continue GUI in a sidebar, like [here](./extensions/vscode/src/ContinueGUIWebviewViewProvider.ts).
+ ```text
+ I have read the CLA Document and I hereby sign the CLA
+ ```
-### Continue VS Code Extension
-
-The starting point for the VS Code extension is [activate.ts](./extensions/vscode/src/activation/activate.ts). The `activateExtension` function here will register all commands and load the Continue GUI in the sidebar of the IDE as a webview.
-
-### Continue JetBrains Extension
-
-The JetBrains extension is currently in alpha testing. Please reach out on [Discord](https://discord.gg/vapESyrFmJ) if you are interested in contributing to its development.
+3. The CLA‑Assistant bot records your signature in the repo and marks the status check as passed.
diff --git a/README.md b/README.md
index a7a9eabb3..bc5df9c83 100644
--- a/README.md
+++ b/README.md
@@ -8,7 +8,10 @@
-**[Continue](https://docs.continue.dev) enables developers to create, share, and use custom AI code assistants with our open-source [VS Code](https://marketplace.visualstudio.com/items?itemName=Continue.continue) and [JetBrains](https://plugins.jetbrains.com/plugin/22707-continue-extension) extensions and [hub of models, rules, prompts, docs, and other building blocks](https://hub.continue.dev)**
+**[Continue](https://docs.continue.dev) enables developers to create, share, and use custom AI code assistants with our
+open-source [VS Code](https://marketplace.visualstudio.com/items?itemName=Continue.continue)
+and [JetBrains](https://plugins.jetbrains.com/plugin/22707-continue-extension) extensions
+and [hub of models, rules, prompts, docs, and other building blocks](https://hub.continue.dev)**
@@ -20,15 +23,25 @@
+
+
+
+## Agent
+
+[Agent](https://continue.dev/docs/agent/how-to-use-it) enables you to make more substantial changes to your codebase
+
+
+
## Chat
-[Chat](https://continue.dev/docs/chat/how-to-use-it) makes it easy to ask for help from an LLM without needing to leave the IDE
+[Chat](https://continue.dev/docs/chat/how-to-use-it) makes it easy to ask for help from an LLM without needing to leave
+the IDE

@@ -40,15 +53,11 @@
## Edit
-[Edit](https://continue.dev/docs/edit/how-to-use-it) is a convenient way to modify code without leaving your current file
+[Edit](https://continue.dev/docs/edit/how-to-use-it) is a convenient way to modify code without leaving your current
+file

-## Agent
-
-[Agent](https://continue.dev/docs/agent/how-to-use-it) enables you to make more substantial changes to your codebase
-
-
@@ -58,7 +67,8 @@ Learn about how to install and use Continue in the docs [here](https://continue.
## Contributing
-Read the [contributing guide](https://github.com/continuedev/continue/blob/main/CONTRIBUTING.md), and join [#contribute on Discord](https://discord.gg/vapESyrFmJ).
+Read the [contributing guide](https://github.com/continuedev/continue/blob/main/CONTRIBUTING.md), and
+join [#contribute on Discord](https://discord.gg/vapESyrFmJ).
## License
diff --git a/binary/build.js b/binary/build.js
index 91e0f304e..b67afb94f 100644
--- a/binary/build.js
+++ b/binary/build.js
@@ -8,13 +8,15 @@ const {
execCmdSync,
autodetectPlatformAndArch,
} = require("../scripts/util");
+const { downloadRipgrep } = require("./utils/ripgrep");
+const { ALL_TARGETS, TARGET_TO_LANCEDB } = require("./utils/targets");
const bin = path.join(__dirname, "bin");
const out = path.join(__dirname, "out");
const build = path.join(__dirname, "build");
function cleanSlate() {
-// Clean slate
+ // Clean slate
rimrafSync(bin);
rimrafSync(out);
rimrafSync(build);
@@ -25,13 +27,7 @@ function cleanSlate() {
}
const esbuildOutputFile = "out/index.js";
-let targets = [
- "darwin-x64",
- "darwin-arm64",
- "linux-x64",
- "linux-arm64",
- "win32-x64",
-];
+let targets = [...ALL_TARGETS];
const [currentPlatform, currentArch] = autodetectPlatformAndArch();
@@ -50,15 +46,6 @@ for (let i = 2; i < process.argv.length; i++) {
}
}
-const targetToLanceDb = {
- "darwin-arm64": "@lancedb/vectordb-darwin-arm64",
- "darwin-x64": "@lancedb/vectordb-darwin-x64",
- "linux-arm64": "@lancedb/vectordb-linux-arm64-gnu",
- "linux-x64": "@lancedb/vectordb-linux-x64-gnu",
- "win32-x64": "@lancedb/vectordb-win32-x64-msvc",
- "win32-arm64": "@lancedb/vectordb-win32-arm64-msvc",
-};
-
// Bundles the extension into one file
async function buildWithEsbuild() {
console.log("[info] Building with esbuild...");
@@ -77,7 +64,7 @@ async function buildWithEsbuild() {
format: "cjs",
platform: "node",
sourcemap: true,
- minify: true,
+ minify: !esbuildOnly,
treeShaking: true,
loader: {
// eslint-disable-next-line @typescript-eslint/naming-convention
@@ -89,7 +76,6 @@ async function buildWithEsbuild() {
inject: ["./importMetaUrl.js"],
define: { "import.meta.url": "importMetaUrl" },
});
-
}
async function installNodeModuleInTempDirAndCopyToCurrent(packageName, toCopy) {
@@ -153,13 +139,31 @@ async function installNodeModuleInTempDirAndCopyToCurrent(packageName, toCopy) {
}
}
+/**
+ * Downloads and installs ripgrep binaries for the specified target
+ *
+ * @param {string} target - Target platform-arch (e.g., 'darwin-x64')
+ * @param {string} targetDir - Directory to install ripgrep to
+ * @returns {Promise}
+ */
+async function downloadRipgrepForTarget(target, targetDir) {
+ console.log(`[info] Downloading ripgrep for ${target}...`);
+ try {
+ await downloadRipgrep(target, targetDir);
+ console.log(`[info] Successfully installed ripgrep for ${target}`);
+ } catch (error) {
+ console.error(`[error] Failed to download ripgrep for ${target}:`, error);
+ throw error;
+ }
+}
+
(async () => {
if (esbuildOnly) {
await buildWithEsbuild();
return;
}
- cleanSlate()
+ cleanSlate();
// Informs of where to look for node_sqlite3.node https://www.npmjs.com/package/bindings#:~:text=The%20searching%20for,file%20is%20found
// This is only needed for our `pkg` command at build time
@@ -179,10 +183,10 @@ async function installNodeModuleInTempDirAndCopyToCurrent(packageName, toCopy) {
console.log("[info] Downloading prebuilt lancedb...");
for (const target of targets) {
- if (targetToLanceDb[target]) {
+ if (TARGET_TO_LANCEDB[target]) {
console.log(`[info] Downloading for ${target}...`);
await installNodeModuleInTempDirAndCopyToCurrent(
- targetToLanceDb[target],
+ TARGET_TO_LANCEDB[target],
"@lancedb",
);
}
@@ -290,10 +294,13 @@ async function installNodeModuleInTempDirAndCopyToCurrent(packageName, toCopy) {
// copy @lancedb to bin folders
console.log("[info] Copying @lancedb files to bin");
fs.copyFileSync(
- `node_modules/${targetToLanceDb[target]}/index.node`,
+ `node_modules/${TARGET_TO_LANCEDB[target]}/index.node`,
`${targetDir}/index.node`,
);
+ // Download and install ripgrep for the target
+ await downloadRipgrepForTarget(target, targetDir);
+
// Informs the `continue-binary` of where to look for node_sqlite3.node
// https://www.npmjs.com/package/bindings#:~:text=The%20searching%20for,file%20is%20found
fs.writeFileSync(`${targetDir}/package.json`, "");
@@ -310,6 +317,7 @@ async function installNodeModuleInTempDirAndCopyToCurrent(packageName, toCopy) {
`${targetDir}/continue-binary${exe}`,
`${targetDir}/index.node`, // @lancedb
`${targetDir}/build/Release/node_sqlite3.node`,
+ `${targetDir}/rg${exe}`, // ripgrep binary
);
}
diff --git a/binary/package-lock.json b/binary/package-lock.json
index 5e864aaf7..abb11ce8e 100644
--- a/binary/package-lock.json
+++ b/binary/package-lock.json
@@ -10,6 +10,7 @@
"license": "Apache-2.0",
"dependencies": {
"@octokit/rest": "^20.0.2",
+ "adm-zip": "^0.5.16",
"commander": "^12.0.0",
"core": "file:../core",
"follow-redirects": "^1.15.5",
@@ -18,6 +19,7 @@
"node-fetch": "^3.3.2",
"posthog-node": "^3.6.3",
"system-ca": "^1.0.2",
+ "tar": "^7.4.3",
"uuid": "^9.0.1",
"vectordb": "^0.4.20",
"win-ca": "^3.5.1"
@@ -31,6 +33,7 @@
"@types/jest": "^29.5.12",
"@types/uuid": "^9.0.8",
"@vercel/ncc": "^0.38.1",
+ "cross-env": "^7.0.3",
"esbuild": "0.19.11",
"jest": "^29.7.0",
"pkg": "^5.8.1",
@@ -49,10 +52,10 @@
"@aws-sdk/credential-providers": "^3.778.0",
"@continuedev/config-types": "^1.0.13",
"@continuedev/config-yaml": "file:../packages/config-yaml",
- "@continuedev/fetch": "^1.0.4",
+ "@continuedev/fetch": "^1.0.10",
"@continuedev/llm-info": "^1.0.8",
- "@continuedev/openai-adapters": "^1.0.19",
- "@modelcontextprotocol/sdk": "^1.5.0",
+ "@continuedev/openai-adapters": "^1.0.25",
+ "@modelcontextprotocol/sdk": "^1.12.0",
"@mozilla/readability": "^0.5.0",
"@octokit/rest": "^20.1.1",
"@typescript-eslint/eslint-plugin": "^7.8.0",
@@ -90,6 +93,7 @@
"p-limit": "^6.1.0",
"partial-json": "^0.1.7",
"pg": "^8.11.3",
+ "plist": "^3.1.0",
"posthog-node": "^3.6.3",
"puppeteer": "^22.4.0",
"puppeteer-chromium-resolver": "^23.0.0",
@@ -126,6 +130,7 @@
"@types/mustache": "^4.2.5",
"@types/node-fetch": "^2.6.11",
"@types/pg": "^8.11.6",
+ "@types/plist": "^3.0.5",
"@types/request": "^2.48.12",
"@types/tar": "^6.1.13",
"@types/uuid": "^9.0.7",
@@ -1526,6 +1531,18 @@
"node": ">=12"
}
},
+ "node_modules/@isaacs/fs-minipass": {
+ "version": "4.0.1",
+ "resolved": "https://registry.npmjs.org/@isaacs/fs-minipass/-/fs-minipass-4.0.1.tgz",
+ "integrity": "sha512-wgm9Ehl2jpeqP3zw/7mo3kRHFp5MEDhqAdwy1fTGkHAwnkGOVsgpvQhL8B5n1qlb01jV3n/bI0ZfZp5lWA1k4w==",
+ "license": "ISC",
+ "dependencies": {
+ "minipass": "^7.0.4"
+ },
+ "engines": {
+ "node": ">=18.0.0"
+ }
+ },
"node_modules/@istanbuljs/load-nyc-config": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/@istanbuljs/load-nyc-config/-/load-nyc-config-1.1.0.tgz",
@@ -2434,6 +2451,15 @@
"ncc": "dist/ncc/cli.js"
}
},
+ "node_modules/adm-zip": {
+ "version": "0.5.16",
+ "resolved": "https://registry.npmjs.org/adm-zip/-/adm-zip-0.5.16.tgz",
+ "integrity": "sha512-TGw5yVi4saajsSEgz25grObGHEUaDrniwvA2qwSC060KfqGPdglhvPMA2lPIoxs3PQIItj2iag35fONcQqgUaQ==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=12.0"
+ }
+ },
"node_modules/agent-base": {
"version": "6.0.2",
"resolved": "https://registry.npmjs.org/agent-base/-/agent-base-6.0.2.tgz",
@@ -2563,9 +2589,9 @@
}
},
"node_modules/axios": {
- "version": "1.7.9",
- "resolved": "https://registry.npmjs.org/axios/-/axios-1.7.9.tgz",
- "integrity": "sha512-LhLcE7Hbiryz8oMDdDptSrWowmB4Bl6RCt6sIJKpRB4XtVf0iEgewX3au/pJqm+Py1kCASkb/FFKjxQaLtxJvw==",
+ "version": "1.9.0",
+ "resolved": "https://registry.npmjs.org/axios/-/axios-1.9.0.tgz",
+ "integrity": "sha512-re4CqKTJaURpzbLHtIi6XpDv20/CnpXOtjRY5/CU32L8gU8ek9UIivcfvSWvmKEngmVbrUtPpdDwWDWL7DNHvg==",
"license": "MIT",
"dependencies": {
"follow-redirects": "^1.15.6",
@@ -3173,6 +3199,25 @@
"node": "^14.15.0 || ^16.10.0 || >=18.0.0"
}
},
+ "node_modules/cross-env": {
+ "version": "7.0.3",
+ "resolved": "https://registry.npmjs.org/cross-env/-/cross-env-7.0.3.tgz",
+ "integrity": "sha512-+/HKd6EgcQCJGh2PSjZuUitQBQynKor4wrFbRg4DtAgS1aWO+gU52xpH7M9ScGgXSYmAVS9bIJ8EzuaGw0oNAw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "cross-spawn": "^7.0.1"
+ },
+ "bin": {
+ "cross-env": "src/bin/cross-env.js",
+ "cross-env-shell": "src/bin/cross-env-shell.js"
+ },
+ "engines": {
+ "node": ">=10.14",
+ "npm": ">=6",
+ "yarn": ">=1"
+ }
+ },
"node_modules/cross-spawn": {
"version": "7.0.6",
"resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz",
@@ -5222,14 +5267,41 @@
}
},
"node_modules/minipass": {
- "version": "7.1.1",
- "resolved": "https://registry.npmjs.org/minipass/-/minipass-7.1.1.tgz",
- "integrity": "sha512-UZ7eQ+h8ywIRAW1hIEl2AqdwzJucU/Kp59+8kkZeSvafXhZjul247BvIJjEVFVeON6d7lM46XX1HXCduKAS8VA==",
- "dev": true,
+ "version": "7.1.2",
+ "resolved": "https://registry.npmjs.org/minipass/-/minipass-7.1.2.tgz",
+ "integrity": "sha512-qOOzS1cBTWYF4BH8fVePDBOO9iptMnGUEZwNc/cMWnTV2nVLZ7VoNWEPHkYczZA0pdoA7dl6e7FL659nX9S2aw==",
+ "license": "ISC",
"engines": {
"node": ">=16 || 14 >=14.17"
}
},
+ "node_modules/minizlib": {
+ "version": "3.0.2",
+ "resolved": "https://registry.npmjs.org/minizlib/-/minizlib-3.0.2.tgz",
+ "integrity": "sha512-oG62iEk+CYt5Xj2YqI5Xi9xWUeZhDI8jjQmC5oThVH5JGCTgIjr7ciJDzC7MBzYd//WvR1OTmP5Q38Q8ShQtVA==",
+ "license": "MIT",
+ "dependencies": {
+ "minipass": "^7.1.2"
+ },
+ "engines": {
+ "node": ">= 18"
+ }
+ },
+ "node_modules/mkdirp": {
+ "version": "3.0.1",
+ "resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-3.0.1.tgz",
+ "integrity": "sha512-+NsyUUAZDmo6YVHzL/stxSu3t9YS1iljliy3BSDrXJ/dkn1KYdmtZODGGjLcc9XLgVVpH4KshHB8XmZgMhaBXg==",
+ "license": "MIT",
+ "bin": {
+ "mkdirp": "dist/cjs/src/bin.js"
+ },
+ "engines": {
+ "node": ">=10"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/isaacs"
+ }
+ },
"node_modules/mkdirp-classic": {
"version": "0.5.3",
"resolved": "https://registry.npmjs.org/mkdirp-classic/-/mkdirp-classic-0.5.3.tgz",
@@ -5340,6 +5412,7 @@
"version": "3.3.2",
"resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-3.3.2.tgz",
"integrity": "sha512-dRB78srN/l6gqWulah9SrxeYnxeddIG30+GOqK/9OlLVyLg3HPnr6SqOWTWOXKRwC2eGYCkZ59NNuSgvSrpgOA==",
+ "license": "MIT",
"dependencies": {
"data-uri-to-buffer": "^4.0.0",
"fetch-blob": "^3.1.4",
@@ -6410,6 +6483,23 @@
"node": ">=12.17"
}
},
+ "node_modules/tar": {
+ "version": "7.4.3",
+ "resolved": "https://registry.npmjs.org/tar/-/tar-7.4.3.tgz",
+ "integrity": "sha512-5S7Va8hKfV7W5U6g3aYxXmlPoZVAwUMy9AOKyF2fVuZa2UD3qZjg578OrLRt8PcNN1PleVaL/5/yYATNL0ICUw==",
+ "license": "ISC",
+ "dependencies": {
+ "@isaacs/fs-minipass": "^4.0.0",
+ "chownr": "^3.0.0",
+ "minipass": "^7.1.2",
+ "minizlib": "^3.0.1",
+ "mkdirp": "^3.0.1",
+ "yallist": "^5.0.0"
+ },
+ "engines": {
+ "node": ">=18"
+ }
+ },
"node_modules/tar-fs": {
"version": "2.1.2",
"resolved": "https://registry.npmjs.org/tar-fs/-/tar-fs-2.1.2.tgz",
@@ -6453,6 +6543,24 @@
"node": ">= 6"
}
},
+ "node_modules/tar/node_modules/chownr": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/chownr/-/chownr-3.0.0.tgz",
+ "integrity": "sha512-+IxzY9BZOQd/XuYPRmrvEVjF/nqj5kgT4kEq7VofrDoM1MxoRjEWkrCC3EtLi59TVawxTAn+orJwFQcrqEN1+g==",
+ "license": "BlueOak-1.0.0",
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/tar/node_modules/yallist": {
+ "version": "5.0.0",
+ "resolved": "https://registry.npmjs.org/yallist/-/yallist-5.0.0.tgz",
+ "integrity": "sha512-YgvUTfwqyc7UXVMrB+SImsVYSmTS8X/tSrtdNZMImM+n7+QTriRXyXim0mBrTXNeqzVF0KWGgHPeiyViFFrNDw==",
+ "license": "BlueOak-1.0.0",
+ "engines": {
+ "node": ">=18"
+ }
+ },
"node_modules/test-exclude": {
"version": "6.0.0",
"resolved": "https://registry.npmjs.org/test-exclude/-/test-exclude-6.0.0.tgz",
diff --git a/binary/package.json b/binary/package.json
index 19dff8a6b..0e8949aa6 100644
--- a/binary/package.json
+++ b/binary/package.json
@@ -33,6 +33,7 @@
"@types/jest": "^29.5.12",
"@types/uuid": "^9.0.8",
"@vercel/ncc": "^0.38.1",
+ "cross-env": "^7.0.3",
"esbuild": "0.19.11",
"jest": "^29.7.0",
"pkg": "^5.8.1",
@@ -42,6 +43,7 @@
},
"dependencies": {
"@octokit/rest": "^20.0.2",
+ "adm-zip": "^0.5.16",
"commander": "^12.0.0",
"core": "file:../core",
"follow-redirects": "^1.15.5",
@@ -50,6 +52,7 @@
"node-fetch": "^3.3.2",
"posthog-node": "^3.6.3",
"system-ca": "^1.0.2",
+ "tar": "^7.4.3",
"uuid": "^9.0.1",
"vectordb": "^0.4.20",
"win-ca": "^3.5.1"
diff --git a/binary/prompt-logs.js b/binary/prompt-logs.js
index 68ee996f7..64a6eab1e 100644
--- a/binary/prompt-logs.js
+++ b/binary/prompt-logs.js
@@ -4,17 +4,35 @@ const path = require('path');
const logDirPath = path.join(__dirname, '..', 'extensions', '.continue-debug', 'logs');
const logFilePath = path.join(logDirPath, "prompt.log");
+// Ensure the log directory exists
if (!fs.existsSync(logDirPath)) {
fs.mkdirSync(logDirPath, { recursive: true });
+ console.log("Created log directory at " + logDirPath);
}
+// Create the log file if it doesn't exist
if (!fs.existsSync(logFilePath)) {
- fs.createWriteStream(logFilePath).end();
+ fs.writeFileSync(logFilePath, ''); // Create an empty file synchronously
+ console.log("Created empty log file at " + logFilePath);
}
-console.log("Watching logs at " + logFilePath)
+console.log("Watching logs at " + logFilePath);
-fs.watch(logFilePath, () => {
- // console.clear();
- fs.createReadStream(logFilePath).pipe(process.stdout);
-});
\ No newline at end of file
+// Set up the file watcher
+try {
+ fs.watch(logFilePath, () => {
+ try {
+ // console.clear();
+ const stream = fs.createReadStream(logFilePath);
+ stream.pipe(process.stdout);
+ stream.on('error', (err) => {
+ console.error('Error reading log file:', err.message);
+ });
+ } catch (err) {
+ console.error('Error while handling file change:', err.message);
+ }
+ });
+} catch (err) {
+ console.error('Error setting up file watcher:', err.message);
+ console.log('You may need to restart the script after the extension generates the first log entry.');
+}
\ No newline at end of file
diff --git a/binary/test/binary.test.ts b/binary/test/binary.test.ts
index fb1be39bb..307368ce8 100644
--- a/binary/test/binary.test.ts
+++ b/binary/test/binary.test.ts
@@ -226,6 +226,7 @@ describe("Test Suite", () => {
title: "Test Model",
provider: "openai",
model: "gpt-3.5-turbo",
+ underlyingProviderName: "openai",
};
await messenger.request("config/addModel", {
model,
@@ -252,6 +253,7 @@ describe("Test Suite", () => {
title: "Test Model",
provider: "mock",
model: "gpt-3.5-turbo",
+ underlyingProviderName: "mock",
};
await messenger.request("config/addModel", {
model,
diff --git a/binary/utils/ripgrep.js b/binary/utils/ripgrep.js
new file mode 100644
index 000000000..9a26ebe26
--- /dev/null
+++ b/binary/utils/ripgrep.js
@@ -0,0 +1,120 @@
+const fs = require("fs");
+const path = require("path");
+const { rimrafSync } = require("rimraf");
+const tar = require("tar");
+const { RIPGREP_VERSION, TARGET_TO_RIPGREP_RELEASE } = require("./targets");
+const AdmZip = require("adm-zip");
+
+const RIPGREP_BASE_URL = `https://github.com/BurntSushi/ripgrep/releases/download/${RIPGREP_VERSION}`;
+
+/**
+ * Downloads a file from a URL to a specified path
+ *
+ * @param {string} url - The URL to download from
+ * @param {string} destPath - The destination path for the downloaded file
+ * @returns {Promise}
+ */
+async function downloadFile(url, destPath) {
+ // Use the built-in fetch API instead of node-fetch
+ const response = await fetch(url, {
+ redirect: "follow", // Automatically follow redirects
+ });
+
+ if (!response.ok) {
+ throw new Error(`Failed to download file, status code: ${response.status}`);
+ }
+
+ // Get the response as an array buffer and write it to the file
+ const buffer = await response.arrayBuffer();
+ fs.writeFileSync(destPath, Buffer.from(buffer));
+}
+
+/**
+ * Extracts an archive to a specified directory
+ *
+ * @param {string} archivePath - Path to the archive file
+ * @param {string} targetDir - Directory to extract the archive to
+ * @param {string} platform - Platform identifier (e.g., 'darwin', 'linux', 'win32')
+ * @returns {Promise}
+ */
+async function extractArchive(archivePath, targetDir, platform) {
+ if (platform === "win32" || archivePath.endsWith(".zip")) {
+ // Simple zip extraction for Windows - extract rg.exe
+ const zip = new AdmZip(archivePath);
+
+ const rgEntry = zip
+ .getEntries()
+ .find((entry) => entry.entryName.endsWith("rg.exe"));
+
+ if (!rgEntry) {
+ throw new Error("Could not find rg.exe in the downloaded archive");
+ }
+
+ // Extract the found rg.exe file to the target directory
+ const entryData = rgEntry.getData();
+ fs.writeFileSync(path.join(targetDir, "rg.exe"), entryData);
+ } else {
+ await tar.extract({
+ file: archivePath,
+ cwd: targetDir,
+ strip: 1, // Strip the top-level directory
+ filter: (path) => path.endsWith("/rg"),
+ });
+ }
+}
+/**
+ * Downloads and installs ripgrep for the specified target
+ *
+ * @param {string} target - Target platform-arch (e.g., 'darwin-x64')
+ * @param {string} targetDir - Directory to install ripgrep to
+ * @returns {Promise} - Path to the installed ripgrep binary
+ */
+async function downloadRipgrep(target, targetDir) {
+ // Get the ripgrep release file name for the target
+ const releaseFile = TARGET_TO_RIPGREP_RELEASE[target];
+ if (!releaseFile) {
+ throw new Error(`Unsupported target: ${target}`);
+ }
+
+ const platform = target.split("-")[0];
+ const downloadUrl = `${RIPGREP_BASE_URL}/${releaseFile}`;
+ const tempDir = path.join(targetDir, "temp");
+
+ // Create temp directory
+ fs.mkdirSync(tempDir, { recursive: true });
+
+ const archivePath = path.join(tempDir, releaseFile);
+
+ try {
+ // Download the ripgrep release
+ console.log(`[info] Downloading ripgrep from ${downloadUrl}`);
+ await downloadFile(downloadUrl, archivePath);
+
+ // Extract the archive
+ console.log(`[info] Extracting ripgrep to ${targetDir}`);
+ await extractArchive(archivePath, targetDir, platform);
+
+ // Make the binary executable on Unix-like systems
+ if (platform !== "win32") {
+ const rgPath = path.join(targetDir, "rg");
+ fs.chmodSync(rgPath, 0o755);
+ }
+
+ // Clean up
+ rimrafSync(tempDir);
+
+ // Return the path to the ripgrep binary
+ const binName = platform === "win32" ? "rg.exe" : "rg";
+ return path.join(targetDir, binName);
+ } catch (error) {
+ console.error(`[error] Failed to download ripgrep for ${target}:`, error);
+ // Clean up temp directory on error
+ rimrafSync(tempDir);
+ throw error;
+ }
+}
+
+module.exports = {
+ downloadRipgrep,
+ RIPGREP_VERSION,
+};
diff --git a/binary/utils/targets.js b/binary/utils/targets.js
new file mode 100644
index 000000000..548328a59
--- /dev/null
+++ b/binary/utils/targets.js
@@ -0,0 +1,42 @@
+const RIPGREP_VERSION = "14.1.1";
+
+/**
+ * All supported platform-architecture targets
+ */
+const ALL_TARGETS = [
+ "darwin-x64",
+ "darwin-arm64",
+ "linux-x64",
+ "linux-arm64",
+ "win32-x64",
+];
+
+/**
+ * Mapping from target triplets to ripgrep release file names
+ */
+const TARGET_TO_RIPGREP_RELEASE = {
+ "darwin-x64": `ripgrep-${RIPGREP_VERSION}-x86_64-apple-darwin.tar.gz`,
+ "darwin-arm64": `ripgrep-${RIPGREP_VERSION}-aarch64-apple-darwin.tar.gz`,
+ "linux-x64": `ripgrep-${RIPGREP_VERSION}-x86_64-unknown-linux-musl.tar.gz`,
+ "linux-arm64": `ripgrep-${RIPGREP_VERSION}-aarch64-unknown-linux-gnu.tar.gz`,
+ "win32-x64": `ripgrep-${RIPGREP_VERSION}-x86_64-pc-windows-msvc.zip`,
+};
+
+/**
+ * Mapping from target triplets to LanceDB package names
+ */
+const TARGET_TO_LANCEDB = {
+ "darwin-arm64": "@lancedb/vectordb-darwin-arm64",
+ "darwin-x64": "@lancedb/vectordb-darwin-x64",
+ "linux-arm64": "@lancedb/vectordb-linux-arm64-gnu",
+ "linux-x64": "@lancedb/vectordb-linux-x64-gnu",
+ "win32-x64": "@lancedb/vectordb-win32-x64-msvc",
+ "win32-arm64": "@lancedb/vectordb-win32-arm64-msvc",
+};
+
+module.exports = {
+ ALL_TARGETS,
+ TARGET_TO_RIPGREP_RELEASE,
+ TARGET_TO_LANCEDB,
+ RIPGREP_VERSION,
+};
\ No newline at end of file
diff --git a/core/autocomplete/CompletionProvider.ts b/core/autocomplete/CompletionProvider.ts
index fd9cf2923..171a6df98 100644
--- a/core/autocomplete/CompletionProvider.ts
+++ b/core/autocomplete/CompletionProvider.ts
@@ -244,7 +244,7 @@ export class CompletionProvider {
prefix,
suffix,
prompt,
- modelProvider: llm.providerName,
+ modelProvider: llm.underlyingProviderName,
modelName: llm.model,
completionOptions,
cacheHit,
diff --git a/core/autocomplete/filtering/streamTransforms/StreamTransformPipeline.ts b/core/autocomplete/filtering/streamTransforms/StreamTransformPipeline.ts
index fdf8c3026..01688b694 100644
--- a/core/autocomplete/filtering/streamTransforms/StreamTransformPipeline.ts
+++ b/core/autocomplete/filtering/streamTransforms/StreamTransformPipeline.ts
@@ -72,7 +72,8 @@ export class StreamTransformPipeline {
fullStop,
);
- const timeoutValue = helper.options.showWhateverWeHaveAtXMs;
+ const timeoutValue = helper.options.modelTimeout;
+
lineGenerator = showWhateverWeHaveAtXMs(lineGenerator, timeoutValue!);
diff --git a/core/autocomplete/filtering/streamTransforms/lineStream.test.ts b/core/autocomplete/filtering/streamTransforms/lineStream.test.ts
index 5cb05d2c3..5bb59c660 100644
--- a/core/autocomplete/filtering/streamTransforms/lineStream.test.ts
+++ b/core/autocomplete/filtering/streamTransforms/lineStream.test.ts
@@ -2,6 +2,7 @@ import { jest } from "@jest/globals";
import * as lineStream from "./lineStream";
+// eslint-disable-next-line max-lines-per-function
describe("lineStream", () => {
let mockFullStop: jest.Mock;
@@ -204,6 +205,33 @@ describe("lineStream", () => {
});
describe("filterCodeBlockLines", () => {
+ it("should handle unfenced code", async () => {
+ const linesGenerator = await getLineGenerator(["const x = 5;"]);
+
+ const result = lineStream.filterCodeBlockLines(linesGenerator);
+ const filteredLines = await getFilteredLines(result);
+
+ expect(filteredLines).toEqual(["const x = 5;"]);
+ });
+
+ it("should handle unfenced code with a code block", async () => {
+ const linesGenerator = await getLineGenerator(["const x = 5;","```bash","ls -al","```"]);
+
+ const result = lineStream.filterCodeBlockLines(linesGenerator);
+ const filteredLines = await getFilteredLines(result);
+
+ expect(filteredLines).toEqual(["const x = 5;","```bash","ls -al","```"]);
+ });
+
+ it("should handle unfenced code with two code blocks", async () => {
+ const linesGenerator = await getLineGenerator(["const x = 5;","```bash","ls -al","```","```bash","ls -al","```"]);
+
+ const result = lineStream.filterCodeBlockLines(linesGenerator);
+ const filteredLines = await getFilteredLines(result);
+
+ expect(filteredLines).toEqual(["const x = 5;","```bash","ls -al","```","```bash","ls -al","```"]);
+ });
+
it("should remove lines before the first valid line", async () => {
const linesGenerator = await getLineGenerator(["```ts", "const x = 5;"]);
@@ -213,7 +241,59 @@ describe("lineStream", () => {
expect(filteredLines).toEqual(["const x = 5;"]);
});
- it.todo("Need some sample inputs to properly test this");
+ it("should remove outer blocks", async () => {
+ const linesGenerator = await getLineGenerator(["```ts", "const x = 5;","```"]);
+
+ const result = lineStream.filterCodeBlockLines(linesGenerator);
+ const filteredLines = await getFilteredLines(result);
+
+ expect(filteredLines).toEqual(["const x = 5;"]);
+ });
+
+ it("should leave inner blocks intact", async () => {
+ const linesGenerator = await getLineGenerator(["```md", "const x = 5;", "```bash","ls -al","```","```"]);
+
+ const result = lineStream.filterCodeBlockLines(linesGenerator);
+ const filteredLines = await getFilteredLines(result);
+
+ expect(filteredLines).toEqual(["const x = 5;","```bash","ls -al","```"]);
+ });
+
+ it("should handle included inner ticks", async () => {
+ const linesGenerator = await getLineGenerator(["```md", "const x = 5;", "```bash","echo ```test```","```","```"]);
+
+ const result = lineStream.filterCodeBlockLines(linesGenerator);
+ const filteredLines = await getFilteredLines(result);
+
+ expect(filteredLines).toEqual(["const x = 5;","```bash","echo ```test```","```"]);
+ });
+
+ it("should leave single inner blocks intact but not return trailing text", async () => {
+ const linesGenerator = await getLineGenerator(["```md", "const x = 5;", "```bash","ls -al","```","```","trailing text"]);
+
+ const result = lineStream.filterCodeBlockLines(linesGenerator);
+ const filteredLines = await getFilteredLines(result);
+
+ expect(filteredLines).toEqual(["const x = 5;","```bash","ls -al","```"]);
+ });
+
+ it("should leave double inner blocks intact but not return trailing text", async () => {
+ const linesGenerator = await getLineGenerator(["```md", "const x = 5;", "```bash","ls -al","```","const y = 10;","```sh","echo `hello world`","```","```","trailing text"]);
+
+ const result = lineStream.filterCodeBlockLines(linesGenerator);
+ const filteredLines = await getFilteredLines(result);
+
+ expect(filteredLines).toEqual(["const x = 5;","```bash","ls -al","```","const y = 10;","```sh","echo `hello world`","```"]);
+ });
+
+ it("should leave inner blocks intact but not return trailing or leading text", async () => {
+ const linesGenerator = await getLineGenerator(["[CODE]", "const x = 5;", "```bash","ls -al","```","[/CODE]","trailing text"]);
+
+ const result = lineStream.filterCodeBlockLines(linesGenerator);
+ const filteredLines = await getFilteredLines(result);
+
+ expect(filteredLines).toEqual(["const x = 5;","```bash","ls -al","```"]);
+ });
});
describe("filterEnglishLinesAtStart", () => {
diff --git a/core/autocomplete/filtering/streamTransforms/lineStream.ts b/core/autocomplete/filtering/streamTransforms/lineStream.ts
index edad1febc..2d7ec2d17 100644
--- a/core/autocomplete/filtering/streamTransforms/lineStream.ts
+++ b/core/autocomplete/filtering/streamTransforms/lineStream.ts
@@ -55,8 +55,8 @@ function shouldChangeLineAndStop(line: string): string | undefined {
return line;
}
- if (line.includes(CODE_START_BLOCK)) {
- return line.split(CODE_START_BLOCK)[0].trimEnd();
+ if (line.includes(CODE_STOP_BLOCK)) {
+ return line.split(CODE_STOP_BLOCK)[0].trimEnd();
}
return undefined;
@@ -71,9 +71,9 @@ function isUselessLine(line: string): boolean {
return hasUselessLine || trimmed.startsWith("// end");
}
-export const USELESS_LINES = ["", "```"];
+export const USELESS_LINES = [""];
export const CODE_KEYWORDS_ENDING_IN_SEMICOLON = ["def"];
-export const CODE_START_BLOCK = "[/CODE]";
+export const CODE_STOP_BLOCK = "[/CODE]";
export const BRACKET_ENDING_CHARS = [")", "]", "}", ";"];
export const PREFIXES_TO_SKIP = [""];
export const LINES_TO_STOP_AT = ["# End of file.", " 0) {
+ // Inside a block including the outer block
+ const changedEndLine = shouldChangeLineAndStop(line);
+ if (typeof changedEndLine === "string") {
+ // Ending a block with just backticks (```) or STOP
+ nestCount--;
+ if (nestCount === 0) {
+ // if we are closing the outer block then exit early
+ // only exit early if the outer block was started with a block
+ // it it was text, we will never exit early
+ return;
+ } else {
+ // otherwise just yield the line
+ yield line;
+ }
+ } else if (line.startsWith("```")) {
+ // Going into a nested codeblock
+ nestCount++;
+ yield line;
+ } else {
+ // otherwise just yield the line
+ yield line;
+ }
}
}
}
diff --git a/core/autocomplete/generation/CompletionStreamer.ts b/core/autocomplete/generation/CompletionStreamer.ts
index d44957d15..fdaa09eb5 100644
--- a/core/autocomplete/generation/CompletionStreamer.ts
+++ b/core/autocomplete/generation/CompletionStreamer.ts
@@ -3,6 +3,7 @@ import { StreamTransformPipeline } from "../filtering/streamTransforms/StreamTra
import { HelperVars } from "../util/HelperVars";
import { GeneratorReuseManager } from "./GeneratorReuseManager";
+import { stopAfterMaxProcessingTime } from "./utils";
export class CompletionStreamer {
private streamTransformPipeline = new StreamTransformPipeline();
@@ -22,23 +23,37 @@ export class CompletionStreamer {
completionOptions: Partial | undefined,
helper: HelperVars,
) {
+ // Full stop means to stop the LLM's generation, instead of just truncating the displayed completion
+ const fullStop = () =>
+ this.generatorReuseManager.currentGenerator?.cancel();
+
// Try to reuse pending requests if what the user typed matches start of completion
const generator = this.generatorReuseManager.getGenerator(
prefix,
- (abortSignal: AbortSignal) =>
- llm.supportsFim()
+ (abortSignal: AbortSignal) => {
+ const generator = llm.supportsFim()
? llm.streamFim(prefix, suffix, abortSignal, completionOptions)
: llm.streamComplete(prompt, abortSignal, {
...completionOptions,
raw: true,
- }),
+ });
+
+ /**
+ * This transformer applies even on reused generator. We are deliberately
+ * not using streamTransformPipeline because we want to capture and stop
+ * the request even if the generator is being reused.
+ */
+ return helper.options.transform
+ ? stopAfterMaxProcessingTime(
+ generator,
+ helper.options.modelTimeout * 2.5,
+ fullStop,
+ )
+ : generator;
+ },
multiline,
);
- // Full stop means to stop the LLM's generation, instead of just truncating the displayed completion
- const fullStop = () =>
- this.generatorReuseManager.currentGenerator?.cancel();
-
// LLM
const generatorWithCancellation = async function* () {
for await (const update of generator) {
diff --git a/core/autocomplete/generation/utils.test.ts b/core/autocomplete/generation/utils.test.ts
new file mode 100644
index 000000000..40326177a
--- /dev/null
+++ b/core/autocomplete/generation/utils.test.ts
@@ -0,0 +1,138 @@
+import { jest } from "@jest/globals";
+import { stopAfterMaxProcessingTime } from "./utils";
+
+describe("stopAfterMaxProcessingTime", () => {
+ beforeEach(() => {
+ jest.useFakeTimers();
+ });
+
+ afterEach(() => {
+ jest.useRealTimers();
+ });
+
+ async function* createMockStream(chunks: string[]): AsyncGenerator {
+ for (const chunk of chunks) {
+ yield chunk;
+ }
+ }
+
+ async function streamToString(
+ stream: AsyncGenerator,
+ ): Promise {
+ let result = "";
+ for await (const chunk of stream) {
+ result += chunk;
+ }
+ return result;
+ }
+
+ it("should yield all chunks when maxTimeMs is not reached", async () => {
+ const mockStream = createMockStream(["Hello", " world", "!"]);
+ const fullStop = jest.fn();
+ const result = stopAfterMaxProcessingTime(mockStream, 1000, fullStop);
+
+ const output = await streamToString(result);
+
+ expect(output).toBe("Hello world!");
+ expect(fullStop).not.toHaveBeenCalled();
+ });
+
+ it.only("should stop processing after max time is reached", async () => {
+ // Mock implementation of Date.now
+ let currentTime = 0;
+ const originalDateNow = Date.now;
+ Date.now = jest.fn(() => currentTime);
+
+ // Create a generator that we can control
+ async function* controlledGenerator(): AsyncGenerator {
+ for (let i = 0; i < 100; i++) {
+ // After yielding 10 chunks, simulate time passing beyond our limit
+ if (i === 10) {
+ currentTime = 1000; // This exceeds our 500ms limit
+ }
+ yield `chunk-${i}`;
+ }
+ }
+
+ const fullStop = jest.fn();
+ const maxTimeMs = 500;
+
+ const transformedGenerator = stopAfterMaxProcessingTime(
+ controlledGenerator(),
+ maxTimeMs,
+ fullStop,
+ );
+
+ // Consume the generator and collect outputs
+ const outputs: string[] = [];
+ for await (const chunk of transformedGenerator) {
+ outputs.push(chunk);
+ }
+
+ // We expect:
+ // 1. Not all chunks were processed (less than 100)
+ // 2. fullStop was called
+ // 3. We processed at least the chunks before time was exceeded
+ expect(outputs.length).toBeLessThan(100);
+ expect(outputs.length).toBeGreaterThanOrEqual(10); // We should get at least the first 10 chunks
+ expect(fullStop).toHaveBeenCalled();
+
+ // Restore Date.now
+ Date.now = originalDateNow;
+ });
+
+ it("should check time only periodically based on checkInterval", async () => {
+ const chunks = Array(100).fill("x");
+ const mockStream = createMockStream(chunks);
+ const fullStop = jest.fn();
+
+ // Spy on Date.now to count how many times it's called
+ const dateSpy = jest.spyOn(Date, "now");
+
+ // Stream should complete normally (not hitting the timeout)
+ await streamToString(
+ stopAfterMaxProcessingTime(mockStream, 10000, fullStop),
+ );
+
+ // The first call is to set startTime, then once every checkInterval (10) chunks
+ // So for 100 chunks, we expect startTime + ~10 checks = ~11 calls
+ // We use a range because implementation details might vary slightly
+ expect(dateSpy.mock.calls.length).toBeGreaterThanOrEqual(1);
+ expect(dateSpy.mock.calls.length).toBeLessThanOrEqual(15);
+
+ dateSpy.mockRestore();
+ });
+
+ it("should handle empty stream gracefully", async () => {
+ const mockStream = createMockStream([]);
+ const fullStop = jest.fn();
+ const result = stopAfterMaxProcessingTime(mockStream, 1000, fullStop);
+
+ const output = await streamToString(result);
+
+ expect(output).toBe("");
+ expect(fullStop).not.toHaveBeenCalled();
+ });
+
+ it("should pass through all chunks if there's no timeout", async () => {
+ const chunks = Array(100).fill("test chunk");
+ const mockStream = createMockStream(chunks);
+ const fullStop = jest.fn();
+
+ // Use undefined as timeout to simulate no timeout
+ const result = stopAfterMaxProcessingTime(
+ mockStream,
+ undefined as any,
+ fullStop,
+ );
+
+ // Process the stream
+ const processedChunks = [];
+ for await (const chunk of result) {
+ processedChunks.push(chunk);
+ }
+
+ expect(processedChunks.length).toBe(chunks.length);
+ expect(fullStop).not.toHaveBeenCalled();
+ });
+});
diff --git a/core/autocomplete/generation/utils.ts b/core/autocomplete/generation/utils.ts
new file mode 100644
index 000000000..b5c94d9a9
--- /dev/null
+++ b/core/autocomplete/generation/utils.ts
@@ -0,0 +1,27 @@
+export async function* stopAfterMaxProcessingTime(
+ stream: AsyncGenerator,
+ maxTimeMs: number,
+ fullStop: () => void,
+): AsyncGenerator {
+ const startTime = Date.now();
+ /**
+ * Check every 10 chunks to avoid performance overhead.
+ */
+ const checkInterval = 10;
+ let chunkCount = 0;
+ let totalCharCount = 0;
+
+ for await (const chunk of stream) {
+ yield chunk;
+
+ chunkCount++;
+ totalCharCount += chunk.length;
+
+ if (chunkCount % checkInterval === 0) {
+ if (Date.now() - startTime > maxTimeMs) {
+ fullStop();
+ return;
+ }
+ }
+ }
+}
diff --git a/core/autocomplete/snippets/getAllSnippets.ts b/core/autocomplete/snippets/getAllSnippets.ts
index dce9c9ff4..4446df85a 100644
--- a/core/autocomplete/snippets/getAllSnippets.ts
+++ b/core/autocomplete/snippets/getAllSnippets.ts
@@ -1,4 +1,4 @@
-import { IDE } from "../../index";
+import { IDE, IdeInfo } from "../../index";
import { findUriInDirs } from "../../util/uri";
import { ContextRetrievalService } from "../context/ContextRetrievalService";
import { GetLspDefinitionsFunction } from "../types";
@@ -112,13 +112,22 @@ const getClipboardSnippets = async (
const getDiffSnippets = async (
ide: IDE,
+ ideInfo: IdeInfo | undefined,
): Promise => {
- const currentTimestamp = ide.getLastFileSaveTimestamp ?
- ide.getLastFileSaveTimestamp() :
- Math.floor(Date.now() / 10000) * 10000; // Defaults to update once in every 10 seconds
+ if (ideInfo?.ideType !== "vscode") {
+ // Disabling for non-vscode IDEs for now
+ // See https://github.com/continuedev/continue/issues/4130
+ // https://github.com/continuedev/continue/issues/5819
+ return [];
+ }
+ const currentTimestamp = ide.getLastFileSaveTimestamp
+ ? ide.getLastFileSaveTimestamp()
+ : Math.floor(Date.now() / 10000) * 10000; // Defaults to update once in every 10 seconds
// Check cache first
- const cached = diffSnippetsCache.get(currentTimestamp) as AutocompleteDiffSnippet[];
+ const cached = diffSnippetsCache.get(
+ currentTimestamp,
+ ) as AutocompleteDiffSnippet[];
if (cached) {
return cached;
@@ -131,13 +140,15 @@ const getDiffSnippets = async (
console.error("Error getting diff for autocomplete", e);
}
- return diffSnippetsCache.set(currentTimestamp, diff.map((item) => {
- return {
- content: item,
- type: AutocompleteSnippetType.Diff,
- };
- }));
-
+ return diffSnippetsCache.set(
+ currentTimestamp,
+ diff.map((item) => {
+ return {
+ content: item,
+ type: AutocompleteSnippetType.Diff,
+ };
+ }),
+ );
};
export const getAllSnippets = async ({
@@ -162,9 +173,13 @@ export const getAllSnippets = async ({
clipboardSnippets,
] = await Promise.all([
racePromise(contextRetrievalService.getRootPathSnippets(helper)),
- racePromise(contextRetrievalService.getSnippetsFromImportDefinitions(helper)),
- IDE_SNIPPETS_ENABLED ? racePromise(getIdeSnippets(helper, ide, getDefinitionsFromLsp)) : [],
- racePromise(getDiffSnippets(ide)),
+ racePromise(
+ contextRetrievalService.getSnippetsFromImportDefinitions(helper),
+ ),
+ IDE_SNIPPETS_ENABLED
+ ? racePromise(getIdeSnippets(helper, ide, getDefinitionsFromLsp))
+ : [],
+ racePromise(getDiffSnippets(ide, helper.ideInfo)),
racePromise(getClipboardSnippets(ide)),
]);
diff --git a/core/autocomplete/templating/AutocompleteTemplate.ts b/core/autocomplete/templating/AutocompleteTemplate.ts
index 6385fa22b..39c653792 100644
--- a/core/autocomplete/templating/AutocompleteTemplate.ts
+++ b/core/autocomplete/templating/AutocompleteTemplate.ts
@@ -71,6 +71,21 @@ const qwenCoderFimTemplate: AutocompleteTemplate = {
},
};
+const seedCoderFimTemplate: AutocompleteTemplate = {
+ template: "<[fim-prefix]>{{{prefix}}}<[fim-suffix]>{{{suffix}}}<[fim-middle]>",
+ completionOptions: {
+ stop: [
+ "<[end▁of▁sentence]>",
+ "<[fim-prefix]>",
+ "<[fim-middle]>",
+ "<[fim-suffix]>",
+ "<[PAD▁TOKEN]>",
+ "<[SEP▁TOKEN]>",
+ "<[begin▁of▁sentence]>",
+ ],
+ },
+};
+
const codestralFimTemplate: AutocompleteTemplate = {
template: "[SUFFIX]{{{suffix}}}[PREFIX]{{{prefix}}}",
completionOptions: {
@@ -426,6 +441,10 @@ export function getTemplateForModel(model: string): AutocompleteTemplate {
return qwenCoderFimTemplate;
}
+ if (lowerCaseModel.includes("seed") && lowerCaseModel.includes("coder")) {
+ return seedCoderFimTemplate;
+ }
+
if (
lowerCaseModel.includes("starcoder") ||
lowerCaseModel.includes("star-coder") ||
diff --git a/core/autocomplete/util/AutocompleteDebouncer.ts b/core/autocomplete/util/AutocompleteDebouncer.ts
index f8bcc474f..2616acaef 100644
--- a/core/autocomplete/util/AutocompleteDebouncer.ts
+++ b/core/autocomplete/util/AutocompleteDebouncer.ts
@@ -1,32 +1,32 @@
import { v4 as uuidv4 } from "uuid";
+
export class AutocompleteDebouncer {
private debounceTimeout: NodeJS.Timeout | undefined = undefined;
- private debouncing = false;
- private lastUUID: string | undefined = undefined;
+ private currentRequestId: string | undefined = undefined;
async delayAndShouldDebounce(debounceDelay: number): Promise {
- // Debounce
- const uuid = uuidv4();
- this.lastUUID = uuid;
-
- // Debounce
- if (this.debouncing) {
- this.debounceTimeout?.refresh();
- const lastUUID = await new Promise((resolve) =>
- setTimeout(() => {
- resolve(this.lastUUID);
- }, debounceDelay),
- );
- if (uuid !== lastUUID) {
- return true;
- }
- } else {
- this.debouncing = true;
- this.debounceTimeout = setTimeout(async () => {
- this.debouncing = false;
- }, debounceDelay);
+ // Generate a unique ID for this request
+ const requestId = uuidv4();
+ this.currentRequestId = requestId;
+
+ // Clear any existing timeout
+ if (this.debounceTimeout) {
+ clearTimeout(this.debounceTimeout);
}
-
- return false;
+
+ // Create a new promise that resolves after the debounce delay
+ return new Promise((resolve) => {
+ this.debounceTimeout = setTimeout(() => {
+ // When the timeout completes, check if this is still the most recent request
+ const shouldDebounce = this.currentRequestId !== requestId;
+
+ // If this is the most recent request, it shouldn't be debounced
+ if (!shouldDebounce) {
+ this.currentRequestId = undefined;
+ }
+
+ resolve(shouldDebounce);
+ }, debounceDelay);
+ });
}
}
diff --git a/core/autocomplete/util/HelperVars.ts b/core/autocomplete/util/HelperVars.ts
index f92ef5a1d..361f7d847 100644
--- a/core/autocomplete/util/HelperVars.ts
+++ b/core/autocomplete/util/HelperVars.ts
@@ -1,4 +1,4 @@
-import { IDE, TabAutocompleteOptions } from "../..";
+import { IDE, IdeInfo, TabAutocompleteOptions } from "../..";
import {
countTokens,
pruneLinesFromBottom,
@@ -21,6 +21,7 @@ export class HelperVars {
lang: AutocompleteLanguageInfo;
treePath: AstPath | undefined;
workspaceUris: string[] = [];
+ ideInfo: IdeInfo | undefined;
private _fileContents: string | undefined;
private _fileLines: string[] | undefined;
@@ -43,7 +44,7 @@ export class HelperVars {
if (this._fileContents !== undefined) {
return;
}
-
+ this.ideInfo = await this.ide.getIdeInfo();
this.workspaceUris = await this.ide.getWorkspaceDirs();
this._fileContents =
diff --git a/core/commands/slash/http.ts b/core/commands/slash/http.ts
index 7a662561c..e92c7c3f1 100644
--- a/core/commands/slash/http.ts
+++ b/core/commands/slash/http.ts
@@ -1,6 +1,6 @@
+import { streamResponse } from "@continuedev/fetch";
import { SlashCommand } from "../../index.js";
import { removeQuotesAndEscapes } from "../../util/index.js";
-import { streamResponse } from "../../llm/stream.js";
const HttpSlashCommand: SlashCommand = {
name: "http",
diff --git a/core/config/ConfigHandler.ts b/core/config/ConfigHandler.ts
index a1588dd43..0d4d81b30 100644
--- a/core/config/ConfigHandler.ts
+++ b/core/config/ConfigHandler.ts
@@ -1,10 +1,6 @@
import { ConfigResult } from "@continuedev/config-yaml";
-import {
- ControlPlaneClient,
- ControlPlaneSessionInfo,
-} from "../control-plane/client.js";
-import { getControlPlaneEnv } from "../control-plane/env.js";
+import { ControlPlaneClient } from "../control-plane/client.js";
import {
BrowserSerializedContinueConfig,
ContinueConfig,
@@ -15,10 +11,15 @@ import {
} from "../index.js";
import { GlobalContext } from "../util/GlobalContext.js";
+import {
+ AuthType,
+ ControlPlaneSessionInfo,
+} from "../control-plane/AuthTypes.js";
+import { getControlPlaneEnv } from "../control-plane/env.js";
import { logger } from "../util/logger.js";
import {
ASSISTANTS,
- getAllDotContinueYamlFiles,
+ getAllDotContinueDefinitionFiles,
LoadAssistantFilesOptions,
} from "./loadLocalAssistants.js";
import LocalProfileLoader from "./profile/LocalProfileLoader.js";
@@ -136,8 +137,7 @@ export class ConfigHandler {
}
private async getOrgs(): Promise {
- const userId = await this.controlPlaneClient.userId;
- if (userId) {
+ if (await this.controlPlaneClient.isSignedIn()) {
const orgDescs = await this.controlPlaneClient.listOrganizations();
const personalHubOrg = await this.getPersonalHubOrg();
const hubOrgs = await Promise.all(
@@ -255,7 +255,7 @@ export class ConfigHandler {
if (currentProfile) {
this.globalContext.update("lastSelectedProfileForWorkspace", {
...selectedProfiles,
- [profileKey]: selectedProfiles.id ?? null,
+ [profileKey]: currentProfile.profileDescription.id,
});
}
@@ -270,6 +270,13 @@ export class ConfigHandler {
/**
* Users can define as many local assistants as they want in a `.continue/assistants` folder
*/
+
+ // Local customization disabled for on-premise deployments
+ const env = await getControlPlaneEnv(this.ide.getIdeSettings());
+ if (env.AUTH_TYPE === AuthType.OnPrem) {
+ return [];
+ }
+
const localProfiles: ProfileLifecycleManager[] = [];
if (options.includeGlobal) {
@@ -277,7 +284,7 @@ export class ConfigHandler {
}
if (options.includeWorkspace) {
- const assistantFiles = await getAllDotContinueYamlFiles(
+ const assistantFiles = await getAllDotContinueDefinitionFiles(
this.ide,
options,
ASSISTANTS,
diff --git a/core/config/load.ts b/core/config/load.ts
index 5a74aa6bb..9948071fb 100644
--- a/core/config/load.ts
+++ b/core/config/load.ts
@@ -51,7 +51,6 @@ import { LLMReranker } from "../llm/llms/llm";
import TransformersJsEmbeddingsProvider from "../llm/llms/TransformersJsEmbeddingsProvider";
import { slashCommandFromPromptFileV1 } from "../promptFiles/v1/slashCommandFromPromptFile";
import { getAllPromptFiles } from "../promptFiles/v2/getPromptFiles";
-import { allTools } from "../tools";
import { copyOf } from "../util";
import { GlobalContext } from "../util/GlobalContext";
import mergeJson from "../util/merge";
@@ -67,6 +66,7 @@ import {
} from "../util/paths";
import { localPathToUri } from "../util/pathToUri";
+import { baseToolDefinitions } from "../tools";
import { modifyAnyConfigWithSharedConfig } from "./sharedConfig";
import {
getModelByRole,
@@ -101,7 +101,14 @@ export function resolveSerializedConfig(
const configMergeKeys = {
models: (a: any, b: any) => a.title === b.title,
- contextProviders: (a: any, b: any) => a.name === b.name,
+ contextProviders: (a: any, b: any) => {
+ // If not HTTP providers, use the name only
+ if (a.name !== "http" || b.name !== "http") {
+ return a.name === b.name;
+ }
+ // For HTTP providers, consider them different if they have different URLs
+ return a.name === b.name && a.params?.url === b.params?.url;
+ },
slashCommands: (a: any, b: any) => a.name === b.name,
customCommands: (a: any, b: any) => a.name === b.name,
};
@@ -522,7 +529,7 @@ async function intermediateToFinalConfig({
const continueConfig: ContinueConfig = {
...config,
contextProviders,
- tools: [...allTools],
+ tools: [...baseToolDefinitions],
mcpServerStatuses: [],
slashCommands: config.slashCommands ?? [],
modelsByRole: {
@@ -620,6 +627,7 @@ async function intermediateToFinalConfig({
function llmToSerializedModelDescription(llm: ILLM): ModelDescription {
return {
provider: llm.providerName,
+ underlyingProviderName: llm.underlyingProviderName,
model: llm.model,
title: llm.title ?? llm.model,
apiKey: llm.apiKey,
@@ -970,6 +978,5 @@ export {
finalToBrowserConfig,
intermediateToFinalConfig,
loadContinueConfigFromJson,
- type BrowserSerializedContinueConfig
+ type BrowserSerializedContinueConfig,
};
-
diff --git a/core/config/loadLocalAssistants.ts b/core/config/loadLocalAssistants.ts
index 18e24f58d..90c5922a2 100644
--- a/core/config/loadLocalAssistants.ts
+++ b/core/config/loadLocalAssistants.ts
@@ -13,7 +13,7 @@ export const ASSISTANTS = "assistants";
export const ASSISTANTS_FOLDER = `.continue/${ASSISTANTS}`;
export function isLocalAssistantFile(uri: string): boolean {
- if (!uri.endsWith(".yaml") && !uri.endsWith(".yml")) {
+ if (!uri.endsWith(".yaml") && !uri.endsWith(".yml") && !uri.endsWith(".md")) {
return false;
}
@@ -21,7 +21,7 @@ export function isLocalAssistantFile(uri: string): boolean {
return normalizedUri.includes(`/${ASSISTANTS_FOLDER}/`);
}
-export async function listYamlFilesInDir(
+async function getDefinitionFilesInDir(
ide: IDE,
dir: string,
): Promise<{ path: string; content: string }[]> {
@@ -41,7 +41,7 @@ export async function listYamlFilesInDir(
source: "get assistant files",
});
const assistantFilePaths = uris.filter(
- (p) => p.endsWith(".yaml") || p.endsWith(".yml"),
+ (p) => p.endsWith(".yaml") || p.endsWith(".yml") || p.endsWith(".md"),
);
const results = assistantFilePaths.map(async (uri) => {
const content = await ide.readFile(uri); // make a try catch
@@ -86,7 +86,7 @@ export function getDotContinueSubDirs(
* This method searches in both ~/.continue and workspace .continue
* for all YAML files in the specified subdirctory, for example .continue/assistants or .continue/prompts
*/
-export async function getAllDotContinueYamlFiles(
+export async function getAllDotContinueDefinitionFiles(
ide: IDE,
options: LoadAssistantFilesOptions,
subDirName: string,
@@ -103,7 +103,7 @@ export async function getAllDotContinueYamlFiles(
// Get all assistant files from the directories
const assistantFiles = (
- await Promise.all(fullDirs.map((dir) => listYamlFilesInDir(ide, dir)))
+ await Promise.all(fullDirs.map((dir) => getDefinitionFilesInDir(ide, dir)))
).flat();
return await Promise.all(
diff --git a/core/config/markdown/loadMarkdownRules.ts b/core/config/markdown/loadMarkdownRules.ts
new file mode 100644
index 000000000..b0bbb8005
--- /dev/null
+++ b/core/config/markdown/loadMarkdownRules.ts
@@ -0,0 +1,47 @@
+import { ConfigValidationError } from "@continuedev/config-yaml";
+import { IDE, RuleWithSource } from "../..";
+import { getAllDotContinueDefinitionFiles } from "../loadLocalAssistants";
+import { convertMarkdownRuleToContinueRule } from "./parseMarkdownRule";
+
+/**
+ * Loads rules from markdown files in the .continue/rules directory
+ */
+export async function loadMarkdownRules(ide: IDE): Promise<{
+ rules: RuleWithSource[];
+ errors: ConfigValidationError[];
+}> {
+ const errors: ConfigValidationError[] = [];
+ const rules: RuleWithSource[] = [];
+
+ try {
+ // Get all .md files from .continue/rules
+ const markdownFiles = await getAllDotContinueDefinitionFiles(
+ ide,
+ { includeGlobal: true, includeWorkspace: true },
+ "rules",
+ );
+
+ // Filter to just .md files
+ const mdFiles = markdownFiles.filter((file) => file.path.endsWith(".md"));
+
+ // Process each markdown file
+ for (const file of mdFiles) {
+ try {
+ const rule = convertMarkdownRuleToContinueRule(file.path, file.content);
+ rules.push(rule);
+ } catch (e) {
+ errors.push({
+ fatal: false,
+ message: `Failed to parse markdown rule file ${file.path}: ${e instanceof Error ? e.message : e}`,
+ });
+ }
+ }
+ } catch (e) {
+ errors.push({
+ fatal: false,
+ message: `Error loading markdown rule files: ${e instanceof Error ? e.message : e}`,
+ });
+ }
+
+ return { rules, errors };
+}
diff --git a/core/config/markdown/parseMarkdownRule.test.ts b/core/config/markdown/parseMarkdownRule.test.ts
new file mode 100644
index 000000000..d05928574
--- /dev/null
+++ b/core/config/markdown/parseMarkdownRule.test.ts
@@ -0,0 +1,192 @@
+import {
+ convertMarkdownRuleToContinueRule,
+ parseMarkdownRule,
+} from "./parseMarkdownRule";
+
+describe("parseMarkdownRule", () => {
+ it("should correctly parse markdown with YAML frontmatter", () => {
+ const content = `---
+globs: "**/test/**/*.kt"
+---
+
+# Test Rule
+
+This is a test rule.`;
+
+ const result = parseMarkdownRule(content);
+ expect(result.frontmatter).toEqual({ globs: "**/test/**/*.kt" });
+ expect(result.markdown).toBe("# Test Rule\n\nThis is a test rule.");
+ });
+
+ it("should handle missing frontmatter", () => {
+ const content = `# Test Rule
+
+This is a test rule without frontmatter.`;
+
+ const result = parseMarkdownRule(content);
+ expect(result.frontmatter).toEqual({});
+ expect(result.markdown).toBe(content);
+ });
+
+ it("should handle empty frontmatter", () => {
+ const content = `---
+---
+
+# Test Rule
+
+This is a test rule with empty frontmatter.`;
+
+ const result = parseMarkdownRule(content);
+
+ // Log exact strings for debugging
+ console.log("Actual:", JSON.stringify(result.markdown));
+ console.log(
+ "Expected:",
+ JSON.stringify(
+ "# Test Rule\n\nThis is a test rule with empty frontmatter.",
+ ),
+ );
+
+ expect(result.frontmatter).toEqual({});
+ expect(result.markdown).toBe(
+ "# Test Rule\n\nThis is a test rule with empty frontmatter.",
+ );
+ });
+
+ it("should handle frontmatter with whitespace", () => {
+ const content = `---
+globs: "**/test/**/*.kt"
+---
+
+# Test Rule
+
+This is a test rule.`;
+
+ const result = parseMarkdownRule(content);
+ expect(result.frontmatter).toEqual({ globs: "**/test/**/*.kt" });
+ expect(result.markdown).toBe("# Test Rule\n\nThis is a test rule.");
+ });
+
+ it("should handle Windows line endings (CRLF)", () => {
+ // Using \r\n for CRLF line endings
+ const content = `---\r
+globs: "**/test/**/*.kt"\r
+---\r
+\r
+# Test Rule\r
+\r
+This is a test rule.`;
+
+ const result = parseMarkdownRule(content);
+ expect(result.frontmatter).toEqual({ globs: "**/test/**/*.kt" });
+ // The result should be normalized to \n
+ expect(result.markdown).toBe("# Test Rule\n\nThis is a test rule.");
+ });
+
+ it("should handle malformed frontmatter", () => {
+ const content = `---
+globs: - "**/test/**/*.kt"
+invalid: yaml: content
+---
+
+# Test Rule
+
+This is a test rule.`;
+
+ // Should treat as only markdown when frontmatter is malformed
+ const result = parseMarkdownRule(content);
+ expect(result.frontmatter).toEqual({});
+ expect(result.markdown).toBe(content);
+ });
+});
+
+describe("convertMarkdownRuleToContinueRule", () => {
+ it("should convert markdown with frontmatter to a rule", () => {
+ const content = `---
+globs: "**/test/**/*.kt"
+name: Custom Name
+---
+
+# Test Rule
+
+This is a test rule.`;
+
+ const result = convertMarkdownRuleToContinueRule(
+ "/path/to/rule.md",
+ content,
+ );
+ expect(result.rule).toBe("# Test Rule\n\nThis is a test rule.");
+ expect(result.globs).toBe("**/test/**/*.kt");
+ expect(result.name).toBe("Custom Name");
+ expect(result.source).toBe("rules-block");
+ expect(result.ruleFile).toBe("/path/to/rule.md");
+ });
+
+ it("should use the first heading as name if not in frontmatter", () => {
+ const content = `---
+globs: "**/test/**/*.kt"
+---
+
+# Test Rule Title
+
+This is a test rule.`;
+
+ const result = convertMarkdownRuleToContinueRule(
+ "/path/to/rule.md",
+ content,
+ );
+ expect(result.name).toBe("Test Rule Title");
+ });
+
+ it("should use filename as name if no heading or frontmatter name", () => {
+ const content = `---
+globs: "**/test/**/*.kt"
+---
+
+This is a test rule without a heading.`;
+
+ const result = convertMarkdownRuleToContinueRule(
+ "/path/to/custom-rule.md",
+ content,
+ );
+ expect(result.name).toBe("custom-rule");
+ });
+
+ it("should include description from frontmatter", () => {
+ const content = `---
+globs: "**/test/**/*.kt"
+name: Test Rule
+description: This is a rule description from frontmatter
+---
+
+# Test Rule
+
+This is the content of the rule.`;
+
+ const result = convertMarkdownRuleToContinueRule(
+ "/path/to/rule.md",
+ content,
+ );
+ expect(result.description).toBe(
+ "This is a rule description from frontmatter",
+ );
+ });
+
+ it("should include `alwaysApply` from frontmatter", () => {
+ const content = `---
+globs: "**/test/**/*.kt"
+name: Test Rule
+alwaysApply: false
+---
+
+# Test Rule
+
+This is a rule with alwaysApply explicitly set to false.`;
+
+ const result = convertMarkdownRuleToContinueRule(
+ "/path/to/rule.md",
+ content,
+ );
+ expect(result.alwaysApply).toBe(false);
+ });
+});
diff --git a/core/config/markdown/parseMarkdownRule.ts b/core/config/markdown/parseMarkdownRule.ts
new file mode 100644
index 000000000..a941f1237
--- /dev/null
+++ b/core/config/markdown/parseMarkdownRule.ts
@@ -0,0 +1,77 @@
+import { basename } from "path";
+import * as YAML from "yaml";
+import { RuleWithSource } from "../..";
+
+export interface RuleFrontmatter {
+ globs?: RuleWithSource["globs"];
+ name?: RuleWithSource["name"];
+ description?: RuleWithSource["description"];
+ alwaysApply?: RuleWithSource["alwaysApply"];
+}
+
+/**
+ * Parses markdown content with YAML frontmatter
+ */
+export function parseMarkdownRule(content: string): {
+ frontmatter: RuleFrontmatter;
+ markdown: string;
+} {
+ // Normalize line endings to \n
+ const normalizedContent = content.replace(/\r\n/g, "\n");
+
+ // More reliable frontmatter detection
+ const parts = normalizedContent.split(/^---\s*$/m);
+
+ // If we have at least 3 parts (before ---, frontmatter, after ---), we have frontmatter
+ if (parts.length >= 3) {
+ const frontmatterStr = parts[1];
+ // Join the remaining parts back together (in case there are more --- in the markdown)
+ const markdownContent = parts.slice(2).join("---");
+
+ try {
+ // Parse YAML frontmatter
+ const frontmatter = YAML.parse(frontmatterStr) || {}; // Handle empty frontmatter
+ return { frontmatter, markdown: markdownContent.trim() };
+ } catch (e) {
+ // Error parsing frontmatter, treat as markdown only
+ console.warn("Error parsing markdown frontmatter:", e);
+ return { frontmatter: {}, markdown: normalizedContent };
+ }
+ }
+
+ // No frontmatter found
+ return { frontmatter: {}, markdown: normalizedContent };
+}
+
+/**
+ * Converts a markdown file with YAML frontmatter to a RuleWithSource object
+ */
+export function convertMarkdownRuleToContinueRule(
+ path: string,
+ content: string,
+): RuleWithSource {
+ const { frontmatter, markdown } = parseMarkdownRule(content);
+
+ // Try to extract title from first heading if no name in frontmatter
+ let name = frontmatter.name;
+ if (!name) {
+ // Look for a heading in the markdown
+ const headingMatch = markdown.match(/^#\s+(.+)$/m);
+ if (headingMatch) {
+ name = headingMatch[1].trim();
+ } else {
+ // Fall back to filename
+ name = basename(path).replace(/\.md$/, "");
+ }
+ }
+
+ return {
+ name,
+ rule: markdown,
+ globs: frontmatter.globs,
+ description: frontmatter.description,
+ alwaysApply: frontmatter.alwaysApply,
+ source: "rules-block",
+ ruleFile: path,
+ };
+}
diff --git a/core/config/migrateSharedConfig.ts b/core/config/migrateSharedConfig.ts
index e1e66000d..67dfeeffd 100644
--- a/core/config/migrateSharedConfig.ts
+++ b/core/config/migrateSharedConfig.ts
@@ -173,6 +173,13 @@ export function migrateJsonSharedConfig(filepath: string, ide: IDE): void {
effected = true;
}
+ const { autoAcceptEditToolDiffs, ...withoutAutoApply } = migratedUI;
+ if (autoAcceptEditToolDiffs !== undefined) {
+ shareConfigUpdates.autoAcceptEditToolDiffs = autoAcceptEditToolDiffs;
+ migratedUI = withoutAutoApply;
+ effected = true;
+ }
+
const { showChatScrollbar, ...withoutShowChatScrollbar } = migratedUI;
if (showChatScrollbar !== undefined) {
shareConfigUpdates.showChatScrollbar = showChatScrollbar;
diff --git a/core/config/profile/doLoadConfig.ts b/core/config/profile/doLoadConfig.ts
index 1308ca2a0..863c4d447 100644
--- a/core/config/profile/doLoadConfig.ts
+++ b/core/config/profile/doLoadConfig.ts
@@ -25,6 +25,7 @@ import { ControlPlaneClient } from "../../control-plane/client.js";
import { getControlPlaneEnv } from "../../control-plane/env.js";
import { TeamAnalytics } from "../../control-plane/TeamAnalytics.js";
import ContinueProxy from "../../llm/llms/stubs/ContinueProxy";
+import { getConfigDependentToolDefinitions } from "../../tools";
import { encodeMCPToolUri } from "../../tools/callTool";
import { getConfigJsonPath, getConfigYamlPath } from "../../util/paths";
import { localPathOrUriToPath } from "../../util/pathToUri";
@@ -32,6 +33,7 @@ import { Telemetry } from "../../util/posthog";
import { TTS } from "../../util/tts";
import { getWorkspaceContinueRuleDotFiles } from "../getWorkspaceContinueRuleDotFiles";
import { loadContinueConfigFromJson } from "../load";
+import { loadMarkdownRules } from "../markdown/loadMarkdownRules";
import { migrateJsonSharedConfig } from "../migrateSharedConfig";
import { rectifySelectedModelsFromGlobalContext } from "../selectedModels";
import { loadContinueConfigFromYaml } from "../yaml/loadYaml";
@@ -128,6 +130,12 @@ export default async function doLoadConfig(options: {
newConfig.rules.unshift(...rules);
errors.push(...continueRulesErrors);
+ // Add rules from markdown files in .continue/rules
+ const { rules: markdownRules, errors: markdownRulesErrors } =
+ await loadMarkdownRules(ide);
+ newConfig.rules.unshift(...markdownRules);
+ errors.push(...markdownRulesErrors);
+
// Rectify model selections for each role
newConfig = rectifySelectedModelsFromGlobalContext(newConfig, profileId);
@@ -169,12 +177,21 @@ export default async function doLoadConfig(options: {
);
newConfig.slashCommands.push(...serverSlashCommands);
- const submenuItems = server.resources.map((resource) => ({
- title: resource.name,
- description: resource.description ?? resource.name,
- id: resource.uri,
- icon: server.faviconUrl,
- }));
+ const submenuItems = server.resources
+ .map((resource) => ({
+ title: resource.name,
+ description: resource.description ?? resource.name,
+ id: resource.uri,
+ icon: server.faviconUrl,
+ }))
+ .concat(
+ server.resourceTemplates.map((template) => ({
+ title: template.name,
+ description: template.description ?? template.name,
+ id: template.uriTemplate,
+ icon: server.faviconUrl,
+ })),
+ );
if (submenuItems.length > 0) {
const serverContextProvider = new MCPContextProvider({
submenuItems,
@@ -186,6 +203,12 @@ export default async function doLoadConfig(options: {
}
}
+ newConfig.tools.push(
+ ...getConfigDependentToolDefinitions({
+ rules: newConfig.rules,
+ }),
+ );
+
// Detect duplicate tool names
const counts: Record = {};
newConfig.tools.forEach((tool) => {
@@ -195,6 +218,7 @@ export default async function doLoadConfig(options: {
counts[tool.function.name] = 1;
}
});
+
Object.entries(counts).forEach(([toolName, count]) => {
if (count > 1) {
errors!.push({
@@ -204,6 +228,26 @@ export default async function doLoadConfig(options: {
}
});
+ const ruleCounts: Record = {};
+ newConfig.rules.forEach((rule) => {
+ if (rule.name) {
+ if (ruleCounts[rule.name]) {
+ ruleCounts[rule.name] = ruleCounts[rule.name] + 1;
+ } else {
+ ruleCounts[rule.name] = 1;
+ }
+ }
+ });
+
+ Object.entries(ruleCounts).forEach(([ruleName, count]) => {
+ if (count > 1) {
+ errors!.push({
+ fatal: false,
+ message: `Duplicate (${count}) rules named "${ruleName}" detected. This may cause unexpected behavior`,
+ });
+ }
+ });
+
newConfig.allowAnonymousTelemetry =
newConfig.allowAnonymousTelemetry && (await ide.isTelemetryEnabled());
diff --git a/core/config/sharedConfig.ts b/core/config/sharedConfig.ts
index ce16ea24f..439925188 100644
--- a/core/config/sharedConfig.ts
+++ b/core/config/sharedConfig.ts
@@ -18,6 +18,7 @@ export const sharedConfigSchema = z
useChromiumForDocsCrawling: z.boolean(),
readResponseTTS: z.boolean(),
promptPath: z.string(),
+ useCurrentFileAsContext: z.boolean(),
// `ui` in `ContinueConfig`
showSessionTabs: z.boolean(),
@@ -26,11 +27,14 @@ export const sharedConfigSchema = z
codeWrap: z.boolean(),
displayRawMarkdown: z.boolean(),
showChatScrollbar: z.boolean(),
+ autoAcceptEditToolDiffs: z.boolean(),
// `tabAutocompleteOptions` in `ContinueConfig`
useAutocompleteCache: z.boolean(),
useAutocompleteMultilineCompletions: z.enum(["always", "never", "auto"]),
disableAutocompleteInFiles: z.array(z.string()),
+ modelTimeout: z.number(),
+ debounceDelay: z.number(),
})
.partial();
@@ -103,6 +107,13 @@ export function modifyAnyConfigWithSharedConfig<
configCopy.tabAutocompleteOptions.disableInFiles =
sharedConfig.disableAutocompleteInFiles;
}
+ if (sharedConfig.modelTimeout !== undefined) {
+ configCopy.tabAutocompleteOptions.modelTimeout = sharedConfig.modelTimeout;
+ }
+ if (sharedConfig.debounceDelay !== undefined) {
+ configCopy.tabAutocompleteOptions.debounceDelay =
+ sharedConfig.debounceDelay;
+ }
configCopy.ui = {
...configCopy.ui,
@@ -124,6 +135,10 @@ export function modifyAnyConfigWithSharedConfig<
if (sharedConfig.showChatScrollbar !== undefined) {
configCopy.ui.showChatScrollbar = sharedConfig.showChatScrollbar;
}
+ if (sharedConfig.autoAcceptEditToolDiffs !== undefined) {
+ configCopy.ui.autoAcceptEditToolDiffs =
+ sharedConfig.autoAcceptEditToolDiffs;
+ }
if (sharedConfig.allowAnonymousTelemetry !== undefined) {
configCopy.allowAnonymousTelemetry = sharedConfig.allowAnonymousTelemetry;
@@ -152,6 +167,10 @@ export function modifyAnyConfigWithSharedConfig<
if (sharedConfig.readResponseTTS !== undefined) {
configCopy.experimental.readResponseTTS = sharedConfig.readResponseTTS;
}
+ if (sharedConfig.useCurrentFileAsContext !== undefined) {
+ configCopy.experimental.useCurrentFileAsContext =
+ sharedConfig.useCurrentFileAsContext;
+ }
return configCopy;
}
diff --git a/core/config/util.ts b/core/config/util.ts
index cc187fc55..9128fc0b5 100644
--- a/core/config/util.ts
+++ b/core/config/util.ts
@@ -77,6 +77,7 @@ export function addModel(
model: model.model,
apiKey: model.apiKey,
apiBase: model.apiBase,
+ maxStopWords: model.maxStopWords,
defaultCompletionOptions: model.completionOptions,
};
if (model.systemMessage) {
diff --git a/core/config/yaml/loadYaml.ts b/core/config/yaml/loadYaml.ts
index 95a4bdc30..daeecf57e 100644
--- a/core/config/yaml/loadYaml.ts
+++ b/core/config/yaml/loadYaml.ts
@@ -9,6 +9,7 @@ import {
PackageIdentifier,
RegistryClient,
Rule,
+ TEMPLATE_VAR_REGEX,
unrollAssistant,
validateConfigYaml,
} from "@continuedev/config-yaml";
@@ -35,14 +36,13 @@ import FreeTrial from "../../llm/llms/FreeTrial";
import TransformersJsEmbeddingsProvider from "../../llm/llms/TransformersJsEmbeddingsProvider";
import { slashCommandFromPromptFileV1 } from "../../promptFiles/v1/slashCommandFromPromptFile";
import { getAllPromptFiles } from "../../promptFiles/v2/getPromptFiles";
-import { allTools } from "../../tools";
import { GlobalContext } from "../../util/GlobalContext";
import { modifyAnyConfigWithSharedConfig } from "../sharedConfig";
import { getControlPlaneEnvSync } from "../../control-plane/env";
-import { logger } from "../../util/logger";
+import { baseToolDefinitions } from "../../tools";
import { getCleanUriPath } from "../../util/uri";
-import { getAllDotContinueYamlFiles } from "../loadLocalAssistants";
+import { getAllDotContinueDefinitionFiles } from "../loadLocalAssistants";
import { LocalPlatformClient } from "./LocalPlatformClient";
import { llmsFromModelConfig } from "./models";
@@ -71,8 +71,8 @@ function convertYamlMcpToContinueMcp(
command: server.command,
args: server.args ?? [],
env: server.env,
- },
- timeout: server.connectionTimeout
+ } as any, // TODO: Fix the mcpServers types in config-yaml (discriminated union)
+ timeout: server.connectionTimeout,
};
}
@@ -96,7 +96,7 @@ async function loadConfigYaml(options: {
// Add local .continue blocks
const allLocalBlocks: PackageIdentifier[] = [];
for (const blockType of BLOCK_TYPES) {
- const localBlocks = await getAllDotContinueYamlFiles(
+ const localBlocks = await getAllDotContinueDefinitionFiles(
ide,
{ includeGlobal: true, includeWorkspace: true },
blockType,
@@ -114,9 +114,9 @@ async function loadConfigYaml(options: {
? dirname(getCleanUriPath(packageIdentifier.filePath))
: undefined;
- logger.info(
- `Loading config.yaml from ${JSON.stringify(packageIdentifier)} with root path ${rootPath}`,
- );
+ // logger.info(
+ // `Loading config.yaml from ${JSON.stringify(packageIdentifier)} with root path ${rootPath}`,
+ // );
let config =
overrideConfigYaml ??
@@ -193,7 +193,7 @@ async function configYamlToContinueConfig(options: {
const continueConfig: ContinueConfig = {
slashCommands: [],
- tools: [...allTools],
+ tools: [...baseToolDefinitions],
mcpServerStatuses: [],
contextProviders: [],
modelsByRole: {
@@ -241,6 +241,21 @@ async function configYamlToContinueConfig(options: {
rootUrl: doc.rootUrl,
faviconUrl: doc.faviconUrl,
}));
+
+ config.mcpServers?.forEach((mcpServer) => {
+ const mcpArgVariables =
+ mcpServer.args?.filter((arg) => TEMPLATE_VAR_REGEX.test(arg)) ?? [];
+
+ if (mcpArgVariables.length === 0) {
+ return;
+ }
+
+ localErrors.push({
+ fatal: false,
+ message: `MCP server "${mcpServer.name}" has unsubstituted variables in args: ${mcpArgVariables.join(", ")}. Please refer to https://docs.continue.dev/hub/secrets/secret-types for managing hub secrets.`,
+ });
+ });
+
continueConfig.experimental = {
modelContextProtocolServers: config.mcpServers?.map(
convertYamlMcpToContinueMcp,
@@ -443,9 +458,9 @@ async function configYamlToContinueConfig(options: {
transport: {
type: "stdio",
args: [],
- ...server,
+ ...(server as any), // TODO: fix the types on mcpServers in config-yaml
},
- timeout: server.connectionTimeout
+ timeout: server.connectionTimeout,
})),
false,
);
diff --git a/core/context/mcp/MCPConnection.test.ts b/core/context/mcp/MCPConnection.test.ts
index f2b13ca10..f8f146f07 100644
--- a/core/context/mcp/MCPConnection.test.ts
+++ b/core/context/mcp/MCPConnection.test.ts
@@ -4,7 +4,7 @@ import MCPConnection from "./MCPConnection";
describe("MCPConnection", () => {
beforeEach(() => {
- jest.clearAllMocks();
+ jest.restoreAllMocks();
});
describe("constructor", () => {
@@ -64,10 +64,10 @@ describe("MCPConnection", () => {
url: "http://test.com/events",
requestOptions: {
headers: {
- "Authorization": "Bearer token123",
- "X-Custom-Header": "custom-value"
- }
- }
+ Authorization: "Bearer token123",
+ "X-Custom-Header": "custom-value",
+ },
+ },
},
};
@@ -111,6 +111,7 @@ describe("MCPConnection", () => {
errors: [],
prompts: [],
resources: [],
+ resourceTemplates: [],
tools: [],
status: "not-connected",
});
@@ -172,12 +173,12 @@ describe("MCPConnection", () => {
expect(mockConnect).toHaveBeenCalled();
});
- it('should handle custom connection timeout', async () => {
- const conn = new MCPConnection({ ...options, timeout: 11 });
+ it("should handle custom connection timeout", async () => {
+ const conn = new MCPConnection({ ...options, timeout: 1500 });
const mockConnect = jest
.spyOn(Client.prototype, "connect")
.mockImplementation(
- () => new Promise((resolve) => setTimeout(resolve, 10)),
+ () => new Promise((resolve) => setTimeout(resolve, 1000)),
);
const abortController = new AbortController();
@@ -199,7 +200,7 @@ describe("MCPConnection", () => {
await conn.connectClient(false, abortController.signal);
expect(conn.status).toBe("error");
- expect(conn.errors[0]).toContain("Failed to connect to MCP server");
+ expect(conn.errors[0]).toContain("Failed to connect");
expect(mockConnect).toHaveBeenCalled();
});
@@ -229,6 +230,38 @@ describe("MCPConnection", () => {
expect(conn.errors[0]).toContain('command "test-cmd" not found');
expect(mockConnect).toHaveBeenCalled();
});
+
+ it.skip("should include stderr output in error message when stdio command fails", async () => {
+ // Clear any existing mocks to ensure we get real behavior
+ jest.restoreAllMocks();
+
+ // Use a command that will definitely fail and produce stderr output
+ const failingOptions = {
+ name: "failing-mcp",
+ id: "failing-id",
+ transport: {
+ type: "stdio" as const,
+ command: "node",
+ args: [
+ "-e",
+ "console.error('Custom error message from stderr'); process.exit(1);",
+ ],
+ },
+ timeout: 5000, // Give enough time for the command to run and fail
+ };
+
+ const conn = new MCPConnection(failingOptions);
+ const abortController = new AbortController();
+
+ await conn.connectClient(false, abortController.signal);
+
+ expect(conn.status).toBe("error");
+ expect(conn.errors).toHaveLength(1);
+ expect(conn.errors[0]).toContain("Failed to connect");
+ expect(conn.errors[0]).toContain("Process output:");
+ expect(conn.errors[0]).toContain("STDERR:");
+ expect(conn.errors[0]).toContain("Custom error message from stderr");
+ });
});
describe.skip("actually connect to Filesystem MCP", () => {
diff --git a/core/context/mcp/MCPConnection.ts b/core/context/mcp/MCPConnection.ts
index 532bb273a..c66a93ed3 100644
--- a/core/context/mcp/MCPConnection.ts
+++ b/core/context/mcp/MCPConnection.ts
@@ -3,6 +3,7 @@ import { Transport } from "@modelcontextprotocol/sdk/shared/transport.js";
import { SSEClientTransport } from "@modelcontextprotocol/sdk/client/sse.js";
import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";
+import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
import { WebSocketClientTransport } from "@modelcontextprotocol/sdk/client/websocket.js";
import {
@@ -10,25 +11,40 @@ import {
MCPOptions,
MCPPrompt,
MCPResource,
+ MCPResourceTemplate,
MCPServerStatus,
MCPTool,
} from "../..";
+import { getEnvPathFromUserShell } from "../../util/shellPath";
const DEFAULT_MCP_TIMEOUT = 20_000; // 20 seconds
+// Commands that are batch scripts on Windows and need cmd.exe to execute
+const WINDOWS_BATCH_COMMANDS = [
+ "npx",
+ "uv",
+ "uvx",
+ "pnpx",
+ "dlx",
+ "nx",
+ "bunx",
+];
+
class MCPConnection {
public client: Client;
- private transport: Transport;
-
- private connectionPromise: Promise | null = null;
public abortController: AbortController;
-
public status: MCPConnectionStatus = "not-connected";
public errors: string[] = [];
-
public prompts: MCPPrompt[] = [];
public tools: MCPTool[] = [];
public resources: MCPResource[] = [];
+ public resourceTemplates: MCPResourceTemplate[] = [];
+ private transport: Transport;
+ private connectionPromise: Promise | null = null;
+ private stdioOutput: { stdout: string; stderr: string } = {
+ stdout: "",
+ stderr: "",
+ };
constructor(public options: MCPOptions) {
this.transport = this.constructTransport(options);
@@ -52,49 +68,13 @@ class MCPConnection {
await this.transport.close();
}
- private constructTransport(options: MCPOptions): Transport {
- switch (options.transport.type) {
- case "stdio":
- const env: Record = options.transport.env
- ? { ...options.transport.env }
- : {};
- if (process.env.PATH !== undefined) {
- env.PATH = process.env.PATH;
- }
- return new StdioClientTransport({
- command: options.transport.command,
- args: options.transport.args,
- env,
- });
- case "websocket":
- return new WebSocketClientTransport(new URL(options.transport.url));
- case "sse":
- return new SSEClientTransport(new URL(options.transport.url), {
- eventSourceInit: {
- fetch: (input, init) =>
- fetch(input, {
- ...init,
- headers: {
- ...init?.headers,
- ...(options.transport.requestOptions?.headers as Record | undefined),
- }
- }),
- },
- requestInit: { headers: options.transport.requestOptions?.headers }
- });
- default:
- throw new Error(
- `Unsupported transport type: ${(options.transport as any).type}`,
- );
- }
- }
-
getStatus(): MCPServerStatus {
return {
...this.options,
errors: this.errors,
prompts: this.prompts,
resources: this.resources,
+ resourceTemplates: this.resourceTemplates,
tools: this.tools,
status: this.status,
};
@@ -118,7 +98,9 @@ class MCPConnection {
this.tools = [];
this.prompts = [];
this.resources = [];
+ this.resourceTemplates = [];
this.errors = [];
+ this.stdioOutput = { stdout: "", stderr: "" };
this.abortController.abort();
this.abortController = new AbortController();
@@ -191,6 +173,23 @@ class MCPConnection {
}
this.errors.push(errorMessage);
}
+
+ // Resource templates
+ try {
+ const { resourceTemplates } =
+ await this.client.listResourceTemplates(
+ {},
+ { signal: timeoutController.signal },
+ );
+
+ this.resourceTemplates = resourceTemplates;
+ } catch (e) {
+ let errorMessage = `Error loading resource templates for MCP Server ${this.options.name}`;
+ if (e instanceof Error) {
+ errorMessage += `: ${e.message}`;
+ }
+ this.errors.push(errorMessage);
+ }
}
// Tools <—> Tools
@@ -232,14 +231,28 @@ class MCPConnection {
]);
} catch (error) {
// Otherwise it's a connection error
- let errorMessage = `Failed to connect to MCP server ${this.options.name}`;
+ let errorMessage = `Failed to connect to "${this.options.name}"\n`;
if (error instanceof Error) {
const msg = error.message.toLowerCase();
if (msg.includes("spawn") && msg.includes("enoent")) {
const command = msg.split(" ")[1];
- errorMessage += `command "${command}" not found. To use this MCP server, install the ${command} CLI.`;
+ errorMessage += `Error: command "${command}" not found. To use this MCP server, install the ${command} CLI.`;
} else {
- errorMessage += ": " + error.message;
+ errorMessage += "Error: " + error.message;
+ }
+ }
+
+ // Include stdio output if available for stdio transport
+ if (
+ this.options.transport.type === "stdio" &&
+ (this.stdioOutput.stdout || this.stdioOutput.stderr)
+ ) {
+ errorMessage += "\n\nProcess output:";
+ if (this.stdioOutput.stdout) {
+ errorMessage += `\nSTDOUT:\n${this.stdioOutput.stdout}`;
+ }
+ if (this.stdioOutput.stderr) {
+ errorMessage += `\nSTDERR:\n${this.stdioOutput.stderr}`;
}
}
@@ -254,6 +267,109 @@ class MCPConnection {
await this.connectionPromise;
}
+
+ /**
+ * Resolves the command and arguments for the current platform
+ * On Windows, batch script commands need to be executed via cmd.exe
+ * @param originalCommand The original command
+ * @param originalArgs The original command arguments
+ * @returns An object with the resolved command and arguments
+ */
+ private resolveCommandForPlatform(
+ originalCommand: string,
+ originalArgs: string[],
+ ): { command: string; args: string[] } {
+ // If not on Windows or not a batch command, return as-is
+ if (
+ process.platform !== "win32" ||
+ !WINDOWS_BATCH_COMMANDS.includes(originalCommand)
+ ) {
+ return { command: originalCommand, args: originalArgs };
+ }
+
+ // On Windows, we need to execute batch commands via cmd.exe
+ // Format: cmd.exe /c command [args]
+ return {
+ command: "cmd.exe",
+ args: ["/c", originalCommand, ...originalArgs],
+ };
+ }
+
+ private constructTransport(options: MCPOptions): Transport {
+ switch (options.transport.type) {
+ case "stdio":
+ const env: Record = options.transport.env
+ ? { ...options.transport.env }
+ : {};
+
+ if (process.env.PATH !== undefined) {
+ // Set the initial PATH from process.env
+ env.PATH = process.env.PATH;
+
+ // For non-Windows platforms, try to get the PATH from user shell
+ if (process.platform !== "win32") {
+ try {
+ const shellEnvPath = getEnvPathFromUserShell();
+ if (shellEnvPath && shellEnvPath !== process.env.PATH) {
+ env.PATH = shellEnvPath;
+ }
+ } catch (err) {
+ console.error("Error getting PATH:", err);
+ }
+ }
+ }
+
+ // Resolve the command and args for the current platform
+ const { command, args } = this.resolveCommandForPlatform(
+ options.transport.command,
+ options.transport.args || [],
+ );
+
+ const transport = new StdioClientTransport({
+ command,
+ args,
+ env,
+ stderr: "pipe",
+ });
+
+ // Capture stdio output for better error reporting
+
+ transport.stderr?.on("data", (data: Buffer) => {
+ this.stdioOutput.stderr += data.toString();
+ });
+
+ return transport;
+ case "websocket":
+ return new WebSocketClientTransport(new URL(options.transport.url));
+ case "sse":
+ return new SSEClientTransport(new URL(options.transport.url), {
+ eventSourceInit: {
+ fetch: (input, init) =>
+ fetch(input, {
+ ...init,
+ headers: {
+ ...init?.headers,
+ ...(options.transport.requestOptions?.headers as
+ | Record
+ | undefined),
+ },
+ }),
+ },
+ requestInit: { headers: options.transport.requestOptions?.headers },
+ });
+ case "streamable-http":
+ return new StreamableHTTPClientTransport(
+ new URL(options.transport.url),
+ {
+ requestInit: { headers: options.transport.requestOptions?.headers },
+ },
+ );
+ default:
+ throw new Error(
+ `Unsupported transport type: ${(options.transport as any).type}`,
+ );
+ }
+ }
}
export default MCPConnection;
diff --git a/core/context/providers/MCPContextProvider.ts b/core/context/providers/MCPContextProvider.ts
index 71f071f37..6465d6b63 100644
--- a/core/context/providers/MCPContextProvider.ts
+++ b/core/context/providers/MCPContextProvider.ts
@@ -20,6 +20,7 @@ class MCPContextProvider extends BaseContextProvider {
displayTitle: "MCP",
description: "Model Context Protocol",
type: "submenu",
+ renderInlineAs: "",
};
override get description(): ContextProviderDescription {
return {
@@ -27,6 +28,7 @@ class MCPContextProvider extends BaseContextProvider {
displayTitle: this.options["serverName"]
? `${this.options["serverName"]} resources`
: "MCP",
+ renderInlineAs: "",
description: "Model Context Protocol",
type: "submenu",
};
@@ -47,6 +49,18 @@ class MCPContextProvider extends BaseContextProvider {
super(options);
}
+ /**
+ * Continue experimentally supports resource templates (https://modelcontextprotocol.io/docs/concepts/resources#resource-templates)
+ * by allowing specifically just the "query" variable in the template, which we will update with the full input of the user in the input box
+ */
+ private insertInputToUriTemplate(uri: string, query: string): string {
+ const TEMPLATE_VAR = "query";
+ if (uri.includes(`{${TEMPLATE_VAR}}`)) {
+ return uri.replace(`{${TEMPLATE_VAR}}`, encodeURIComponent(query));
+ }
+ return uri;
+ }
+
async getContextItems(
query: string,
extras: ContextProviderExtras,
@@ -58,7 +72,9 @@ class MCPContextProvider extends BaseContextProvider {
throw new Error(`No MCP connection found for ${mcpId}`);
}
- const { contents } = await connection.client.readResource({ uri });
+ const { contents } = await connection.client.readResource({
+ uri: this.insertInputToUriTemplate(uri, extras.fullInput),
+ });
return await Promise.all(
contents.map(async (resource) => {
diff --git a/core/control-plane/AuthTypes.ts b/core/control-plane/AuthTypes.ts
new file mode 100644
index 000000000..3b79d91ae
--- /dev/null
+++ b/core/control-plane/AuthTypes.ts
@@ -0,0 +1,51 @@
+export interface HubSessionInfo {
+ AUTH_TYPE: AuthType.WorkOsProd | AuthType.WorkOsStaging;
+ accessToken: string;
+ account: {
+ label: string;
+ id: string;
+ };
+}
+
+export interface OnPremSessionInfo {
+ AUTH_TYPE: AuthType.OnPrem;
+}
+
+export type ControlPlaneSessionInfo = HubSessionInfo | OnPremSessionInfo;
+
+export function isOnPremSession(
+ sessionInfo: ControlPlaneSessionInfo | undefined,
+): sessionInfo is OnPremSessionInfo {
+ return sessionInfo !== undefined && sessionInfo.AUTH_TYPE === AuthType.OnPrem;
+}
+
+export enum AuthType {
+ WorkOsProd = "continue",
+ WorkOsStaging = "continue-staging",
+ OnPrem = "on-prem",
+}
+
+export interface HubEnv {
+ DEFAULT_CONTROL_PLANE_PROXY_URL: string;
+ CONTROL_PLANE_URL: string;
+ AUTH_TYPE: AuthType.WorkOsProd | AuthType.WorkOsStaging;
+ WORKOS_CLIENT_ID: string;
+ APP_URL: string;
+}
+
+export interface OnPremEnv {
+ AUTH_TYPE: AuthType.OnPrem;
+ DEFAULT_CONTROL_PLANE_PROXY_URL: string;
+ CONTROL_PLANE_URL: string;
+ APP_URL: string;
+}
+
+export type ControlPlaneEnv = HubEnv | OnPremEnv;
+
+export function isHubEnv(env: ControlPlaneEnv): env is HubEnv {
+ return (
+ "AUTH_TYPE" in env &&
+ env.AUTH_TYPE !== "on-prem" &&
+ "WORKOS_CLIENT_ID" in env
+ );
+}
diff --git a/core/control-plane/auth/index.ts b/core/control-plane/auth/index.ts
index a3441ab65..5e8748ab9 100644
--- a/core/control-plane/auth/index.ts
+++ b/core/control-plane/auth/index.ts
@@ -1,5 +1,6 @@
import { v4 as uuidv4 } from "uuid";
import { IdeSettings } from "../..";
+import { isHubEnv } from "../AuthTypes";
import { getControlPlaneEnv } from "../env";
export async function getAuthUrlForTokenPage(
@@ -7,6 +8,11 @@ export async function getAuthUrlForTokenPage(
useOnboarding: boolean,
): Promise {
const env = await getControlPlaneEnv(ideSettingsPromise);
+
+ if (!isHubEnv(env)) {
+ throw new Error("Sign in disabled");
+ }
+
const url = new URL("https://api.workos.com/user_management/authorize");
const params = {
response_type: "code",
diff --git a/core/control-plane/client.ts b/core/control-plane/client.ts
index 77a3dc108..d2653e246 100644
--- a/core/control-plane/client.ts
+++ b/core/control-plane/client.ts
@@ -12,16 +12,9 @@ import fetch, { RequestInit, Response } from "node-fetch";
import { OrganizationDescription } from "../config/ProfileLifecycleManager.js";
import { IdeSettings, ModelDescription } from "../index.js";
+import { ControlPlaneSessionInfo, isOnPremSession } from "./AuthTypes.js";
import { getControlPlaneEnv } from "./env.js";
-export interface ControlPlaneSessionInfo {
- accessToken: string;
- account: {
- label: string;
- id: string;
- };
-}
-
export interface ControlPlaneWorkspace {
id: string;
name: string;
@@ -45,8 +38,7 @@ export class ControlPlaneClient {
fqsns: FQSN[],
orgScopeId: string | null,
): Promise<(SecretResult | undefined)[]> {
- const userId = await this.userId;
- if (!userId) {
+ if (!(await this.isSignedIn())) {
return fqsns.map((fqsn) => ({
found: false,
fqsn,
@@ -64,19 +56,23 @@ export class ControlPlaneClient {
return (await resp.json()) as any;
}
- get userId(): Promise {
- return this.sessionInfoPromise.then(
- (sessionInfo) => sessionInfo?.account.id,
- );
+ async isSignedIn(): Promise {
+ const sessionInfo = await this.sessionInfoPromise;
+ return !!sessionInfo;
}
async getAccessToken(): Promise {
- return (await this.sessionInfoPromise)?.accessToken;
+ const sessionInfo = await this.sessionInfoPromise;
+ return isOnPremSession(sessionInfo) ? undefined : sessionInfo?.accessToken;
}
private async request(path: string, init: RequestInit): Promise {
+ const sessionInfo = await this.sessionInfoPromise;
+ const onPremSession = isOnPremSession(sessionInfo);
const accessToken = await this.getAccessToken();
- if (!accessToken) {
+
+ // Bearer token not necessary for on-prem auth type
+ if (!accessToken && !onPremSession) {
throw new Error("No access token");
}
@@ -99,22 +95,6 @@ export class ControlPlaneClient {
return resp;
}
- public async listWorkspaces(): Promise {
- const userId = await this.userId;
- if (!userId) {
- return [];
- }
-
- try {
- const resp = await this.request("workspaces", {
- method: "GET",
- });
- return (await resp.json()) as any;
- } catch (e) {
- return [];
- }
- }
-
public async listAssistants(organizationId: string | null): Promise<
{
configResult: ConfigResult;
@@ -124,8 +104,7 @@ export class ControlPlaneClient {
rawYaml: string;
}[]
> {
- const userId = await this.userId;
- if (!userId) {
+ if (!(await this.isSignedIn())) {
return [];
}
@@ -144,9 +123,7 @@ export class ControlPlaneClient {
}
public async listOrganizations(): Promise> {
- const userId = await this.userId;
-
- if (!userId) {
+ if (!(await this.isSignedIn())) {
return [];
}
@@ -164,8 +141,7 @@ export class ControlPlaneClient {
public async listAssistantFullSlugs(
organizationId: string | null,
): Promise {
- const userId = await this.userId;
- if (!userId) {
+ if (!(await this.isSignedIn())) {
return null;
}
@@ -183,16 +159,4 @@ export class ControlPlaneClient {
return null;
}
}
-
- async getSettingsForWorkspace(workspaceId: string): Promise {
- const userId = await this.userId;
- if (!userId) {
- throw new Error("No user id");
- }
-
- const resp = await this.request(`workspaces/${workspaceId}`, {
- method: "GET",
- });
- return ((await resp.json()) as any).settings;
- }
}
diff --git a/core/control-plane/env.ts b/core/control-plane/env.ts
index acbc20b59..2d76017d2 100644
--- a/core/control-plane/env.ts
+++ b/core/control-plane/env.ts
@@ -4,27 +4,18 @@ import {
getLocalEnvironmentDotFilePath,
getStagingEnvironmentDotFilePath,
} from "../util/paths";
-
-export interface ControlPlaneEnv {
- DEFAULT_CONTROL_PLANE_PROXY_URL: string;
- CONTROL_PLANE_URL: string;
- AUTH_TYPE: string;
- WORKOS_CLIENT_ID: string;
- APP_URL: string;
-}
+import { AuthType, ControlPlaneEnv } from "./AuthTypes";
+import { getMdmKeys } from "./mdm";
export const EXTENSION_NAME = "continue";
const WORKOS_CLIENT_ID_PRODUCTION = "client_01J0FW6XN8N2XJAECF7NE0Y65J";
const WORKOS_CLIENT_ID_STAGING = "client_01J0FW6XCPMJMQ3CG51RB4HBZQ";
-const WORKOS_ENV_ID_PRODUCTION = "continue";
-const WORKOS_ENV_ID_STAGING = "continue-staging";
-
const PRODUCTION_HUB_ENV: ControlPlaneEnv = {
DEFAULT_CONTROL_PLANE_PROXY_URL: "https://api.continue.dev/",
CONTROL_PLANE_URL: "https://api.continue.dev/",
- AUTH_TYPE: WORKOS_ENV_ID_PRODUCTION,
+ AUTH_TYPE: AuthType.WorkOsProd,
WORKOS_CLIENT_ID: WORKOS_CLIENT_ID_PRODUCTION,
APP_URL: "https://hub.continue.dev/",
};
@@ -32,7 +23,7 @@ const PRODUCTION_HUB_ENV: ControlPlaneEnv = {
const STAGING_ENV: ControlPlaneEnv = {
DEFAULT_CONTROL_PLANE_PROXY_URL: "https://api.continue-stage.tools/",
CONTROL_PLANE_URL: "https://api.continue-stage.tools/",
- AUTH_TYPE: WORKOS_ENV_ID_STAGING,
+ AUTH_TYPE: AuthType.WorkOsStaging,
WORKOS_CLIENT_ID: WORKOS_CLIENT_ID_STAGING,
APP_URL: "https://hub.continue-stage.tools/",
};
@@ -40,7 +31,7 @@ const STAGING_ENV: ControlPlaneEnv = {
const TEST_ENV: ControlPlaneEnv = {
DEFAULT_CONTROL_PLANE_PROXY_URL: "https://api-test.continue.dev/",
CONTROL_PLANE_URL: "https://api-test.continue.dev/",
- AUTH_TYPE: WORKOS_ENV_ID_STAGING,
+ AUTH_TYPE: AuthType.WorkOsStaging,
WORKOS_CLIENT_ID: WORKOS_CLIENT_ID_STAGING,
APP_URL: "https://app-test.continue.dev/",
};
@@ -48,7 +39,7 @@ const TEST_ENV: ControlPlaneEnv = {
const LOCAL_ENV: ControlPlaneEnv = {
DEFAULT_CONTROL_PLANE_PROXY_URL: "http://localhost:3001/",
CONTROL_PLANE_URL: "http://localhost:3001/",
- AUTH_TYPE: WORKOS_ENV_ID_STAGING,
+ AUTH_TYPE: AuthType.WorkOsStaging,
WORKOS_CLIENT_ID: WORKOS_CLIENT_ID_STAGING,
APP_URL: "http://localhost:3000/",
};
@@ -67,6 +58,18 @@ export async function getControlPlaneEnv(
export function getControlPlaneEnvSync(
ideTestEnvironment: IdeSettings["continueTestEnvironment"],
): ControlPlaneEnv {
+ // MDM override
+ const mdmKeys = getMdmKeys();
+ if (mdmKeys) {
+ const { apiUrl } = mdmKeys;
+ return {
+ AUTH_TYPE: AuthType.OnPrem,
+ DEFAULT_CONTROL_PLANE_PROXY_URL: apiUrl,
+ CONTROL_PLANE_URL: apiUrl,
+ APP_URL: "https://hub.continue.dev/",
+ };
+ }
+
// Note .local overrides .staging
if (fs.existsSync(getLocalEnvironmentDotFilePath())) {
return LOCAL_ENV;
diff --git a/core/control-plane/mdm.test.ts b/core/control-plane/mdm.test.ts
new file mode 100644
index 000000000..18fbe846a
--- /dev/null
+++ b/core/control-plane/mdm.test.ts
@@ -0,0 +1,127 @@
+import * as crypto from "crypto";
+import { LicenseData, validateLicenseKey } from "./mdm";
+
+// We'll create a real key pair once for all tests
+const testKeyPair = crypto.generateKeyPairSync("rsa", {
+ modulusLength: 2048,
+ publicKeyEncoding: {
+ type: "spki",
+ format: "pem",
+ },
+ privateKeyEncoding: {
+ type: "pkcs8",
+ format: "pem",
+ },
+});
+
+// Custom function to create test licenses (replaces the original mock-dependent one)
+function createTestLicense(
+ licenseData: LicenseData,
+ useValidSignature: boolean = true,
+): string {
+ // Convert license data to a string
+ const licenseDataStr = JSON.stringify(licenseData);
+
+ // Create a signature with our generated private key
+ const sign = crypto.createSign("SHA256");
+ sign.update(licenseDataStr);
+ sign.end();
+
+ let signature: string;
+ if (useValidSignature) {
+ signature = sign.sign(testKeyPair.privateKey, "base64");
+ } else {
+ // For invalid tests, create an intentionally wrong signature by signing different data
+ const wrongSign = crypto.createSign("SHA256");
+ wrongSign.update(licenseDataStr + "tampered");
+ wrongSign.end();
+ signature = wrongSign.sign(testKeyPair.privateKey, "base64");
+ }
+ // Combine data and signature into a license key
+ const licenseKeyObj = {
+ data: licenseDataStr,
+ signature: signature,
+ };
+
+ return Buffer.from(JSON.stringify(licenseKeyObj)).toString("base64");
+}
+
+// We need to test the actual implementation - which we can't mock with ESM
+// Instead, we'll have tests that bypass validation or are expected to fail
+// depending on what we're testing
+
+test("validateLicenseKey returns false for malformed license key", () => {
+ // Test with a completely invalid license key
+ const invalidLicenseKey = "not-a-valid-license-key";
+
+ // Test - no mocks, real validation
+ const result = validateLicenseKey(invalidLicenseKey);
+
+ // Assert
+ expect(result).toBe(false);
+});
+
+test("validateLicenseKey returns false for invalid JSON in license key", () => {
+ // Create a malformed but base64-encoded string
+ const malformedLicenseKey = Buffer.from("this is not valid JSON").toString(
+ "base64",
+ );
+
+ // Test - no mocks, real validation
+ const result = validateLicenseKey(malformedLicenseKey);
+
+ // Assert
+ expect(result).toBe(false);
+});
+
+test("validateLicenseKey returns false for expired license", () => {
+ // Without mocking, we expect this to fail signature verification
+ // We're testing the date logic by itself
+ const licenseData: LicenseData = {
+ customerId: "customer123",
+ createdAt: new Date(Date.now() - 2000 * 60 * 60 * 24).toISOString(), // Created 2 days ago
+ expiresAt: new Date(Date.now() - 1000 * 60 * 60 * 24).toISOString(), // Expired 1 day ago
+ };
+
+ // Create a license key - will fail verification but test logic still works
+ const expiredLicenseKey = createTestLicense(licenseData);
+
+ // Test - expect false, either due to signature or expiration - both are valid test cases
+ const result = validateLicenseKey(expiredLicenseKey);
+
+ // Assert
+ expect(result).toBe(false);
+});
+
+test("validateLicenseKey returns false for invalid signature", () => {
+ // Create license data with valid dates
+ const licenseData: LicenseData = {
+ customerId: "customer123",
+ createdAt: new Date().toISOString(),
+ expiresAt: new Date(Date.now() + 1000 * 60 * 60 * 24).toISOString(), // Valid for 1 day
+ };
+
+ // Create a license with an invalid signature
+ const invalidSignatureKey = createTestLicense(licenseData, false);
+
+ // Test - no mocks, real validation
+ const result = validateLicenseKey(invalidSignatureKey);
+
+ // Assert
+ expect(result).toBe(false);
+});
+
+test("validateLicenseKey handles JSON parsing errors gracefully", () => {
+ // Create a base64 string that decodes to valid JSON but lacks required fields
+ const invalidStructureKey = Buffer.from(
+ JSON.stringify({
+ notTheRightField: "wrong structure",
+ }),
+ ).toString("base64");
+
+ // Test - no mocks, real validation
+ const result = validateLicenseKey(invalidStructureKey);
+
+ // Assert
+ expect(result).toBe(false);
+});
diff --git a/core/control-plane/mdm.ts b/core/control-plane/mdm.ts
new file mode 100644
index 000000000..81599fea0
--- /dev/null
+++ b/core/control-plane/mdm.ts
@@ -0,0 +1,262 @@
+import * as crypto from "crypto";
+import * as fs from "fs";
+import * as os from "os";
+import * as path from "path";
+import * as plist from "plist";
+
+export interface MdmKeys {
+ licenseKey: string;
+ apiUrl: string;
+}
+
+const CONTINUE_PUBLIC_KEY = `-----BEGIN PUBLIC KEY-----
+MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAz1pFVzsW2UScSnaPAwFp
+93QU4+txtyJj8AOC3Kx7YkX1d48DGU2Fy1he7SXPHgcuhXYIqfWGn/Vy/4yJxXD7
+HlU8RM7LlWHRk7ecAvF4WtxZDjPE0OSG5T69w5f7tMCtQPQseInCKqleJuCjxrvA
+zyTWTwKA1S6e+KxXS/kbqsumriljFujNr6Gmh8ygDnpF055Xo0vTenkMipVw/oYn
+U0EHx5ic+Fmcob3EyOj25lu/CVYtU1Rn8jPbrBOMiIq5sePh2QXOwGRsuTiZk2mP
+LXSsjLbeWHifRrQ18wj/PC990E33QaFGNFp0NcBXMPbq5eKYKEzKZ0GsxtLoGxar
+FQIDAQAB
+-----END PUBLIC KEY-----`;
+
+export interface LicenseData {
+ customerId: string;
+ createdAt: string;
+ expiresAt: string;
+}
+
+export function validateLicenseKey(licenseKey: string): boolean {
+ try {
+ // Decode the base64 license key
+ const decodedString = Buffer.from(licenseKey, "base64").toString("utf8");
+ const { data, signature } = JSON.parse(decodedString);
+
+ // Verify the signature
+ const verify = crypto.createVerify("SHA256");
+ verify.update(data);
+ verify.end();
+
+ const isValid = verify.verify(CONTINUE_PUBLIC_KEY, signature, "base64");
+
+ if (!isValid) return false;
+
+ // Check license expiration
+ const licenseData: LicenseData = JSON.parse(data);
+ const expirationDate = new Date(licenseData.expiresAt);
+ const now = new Date();
+
+ return expirationDate > now;
+ } catch (error) {
+ console.error("License validation error:", error);
+ return false;
+ }
+}
+
+function extractConfigFromArray(config: any[]): Record {
+ const configObj: Record = {};
+
+ for (let i = 0; i < config.length; i += 2) {
+ if (i + 1 < config.length) {
+ const key = config[i];
+ const value = config[i + 1];
+ if (typeof key === "string") {
+ configObj[key] = value as string;
+ }
+ }
+ }
+
+ return configObj;
+}
+
+const MACOS_MDM_PATHS = [
+ // Organization-specific MDM plist
+ "/Library/Managed Preferences/dev.continue.app.plist",
+ // User-specific MDM plist
+ path.join(os.homedir(), "Library/Managed Preferences/dev.continue.app.plist"),
+];
+
+function readMdmKeysMacOS(): MdmKeys | undefined {
+ try {
+ // MDM configuration is typically stored in /Library/Managed Preferences/ on macOS
+ // The filename is often the bundle identifier of the application
+
+ // Try to find a valid MDM configuration file
+ for (const mdmPath of MACOS_MDM_PATHS) {
+ if (fs.existsSync(mdmPath)) {
+ // Read the file content
+ const fileContent = fs.readFileSync(mdmPath, "utf8");
+
+ try {
+ // Parse the plist file using the plist package
+ const config = plist.parse(fileContent);
+
+ // Extract the relevant fields from the config
+ // Config is an array of alternating keys and values
+ if (Array.isArray(config)) {
+ const configObj = extractConfigFromArray(config);
+
+ // Check if required keys are present
+ if (configObj.licenseKey && configObj.apiUrl) {
+ return {
+ licenseKey: configObj.licenseKey,
+ apiUrl: configObj.apiUrl,
+ };
+ }
+ }
+ } catch (parseError) {
+ console.error(`Error parsing MDM configuration: ${parseError}`);
+ }
+ }
+ }
+
+ return undefined;
+ } catch (error) {
+ console.error("Error reading macOS MDM keys:", error);
+ return undefined;
+ }
+}
+
+function readMdmKeysWindows(): MdmKeys | undefined {
+ try {
+ // For Windows, we need to read from the registry
+ // Using regedit or another synchronous registry access module
+ const { execSync } = require("child_process");
+
+ // Path to the registry where MDM configuration is stored
+ const regPath = "HKLM\\Software\\Continue\\MDM";
+ const userRegPath = "HKCU\\Software\\Continue\\MDM";
+
+ // Try to read from HKEY_LOCAL_MACHINE first
+ try {
+ // Use REG QUERY command to read registry values
+ const licenseKeyCmd = `reg query "${regPath}" /v licenseKey`;
+ const apiUrlCmd = `reg query "${regPath}" /v apiUrl`;
+
+ const licenseKeyOutput = execSync(licenseKeyCmd, { encoding: "utf8" });
+ const apiUrlOutput = execSync(apiUrlCmd, { encoding: "utf8" });
+
+ // Extract values from command output
+ const licenseKey = extractRegValue(licenseKeyOutput);
+ const apiUrl = extractRegValue(apiUrlOutput);
+
+ if (licenseKey && apiUrl) {
+ return { licenseKey, apiUrl };
+ }
+ } catch (error) {
+ // Registry key might not exist, fallback to HKEY_CURRENT_USER
+ }
+
+ // Try HKEY_CURRENT_USER if not found in HKEY_LOCAL_MACHINE
+ try {
+ const licenseKeyCmd = `reg query "${userRegPath}" /v licenseKey`;
+ const apiUrlCmd = `reg query "${userRegPath}" /v apiUrl`;
+
+ const licenseKeyOutput = execSync(licenseKeyCmd, { encoding: "utf8" });
+ const apiUrlOutput = execSync(apiUrlCmd, { encoding: "utf8" });
+
+ // Extract values from command output
+ const licenseKey = extractRegValue(licenseKeyOutput);
+ const apiUrl = extractRegValue(apiUrlOutput);
+
+ if (licenseKey && apiUrl) {
+ return { licenseKey, apiUrl };
+ }
+ } catch (error) {
+ // Registry key might not exist in HKCU either
+ }
+
+ return undefined;
+ } catch (error) {
+ console.error("Error reading Windows MDM keys:", error);
+ return undefined;
+ }
+}
+
+// Helper function to extract registry values from reg query output
+function extractRegValue(output: string): string | undefined {
+ const match = output.match(/REG_SZ\s+(.+)$/m);
+ return match ? match[1].trim() : undefined;
+}
+
+// Common locations for MDM configurations in Linux systems
+const LINUX_MDM_PATHS = [
+ // System-wide configuration
+ "/etc/continue/mdm.json",
+ "/var/lib/continue/mdm.json",
+ // User-specific configuration
+ path.join(os.homedir(), ".config/continue/mdm.json"),
+];
+
+function readMdmKeysLinux(): MdmKeys | undefined {
+ try {
+ // Try to find a valid MDM configuration file
+ for (const mdmPath of LINUX_MDM_PATHS) {
+ if (fs.existsSync(mdmPath)) {
+ // Read the file content
+ const fileContent = fs.readFileSync(mdmPath, "utf8");
+
+ try {
+ // Parse the JSON configuration file
+ const config = JSON.parse(fileContent);
+
+ // Check if required keys are present
+ if (config.licenseKey && config.apiUrl) {
+ return {
+ licenseKey: config.licenseKey,
+ apiUrl: config.apiUrl,
+ };
+ }
+ } catch (parseError) {
+ console.error(`Error parsing Linux MDM configuration: ${parseError}`);
+ }
+ }
+ }
+
+ return undefined;
+ } catch (error) {
+ console.error("Error reading Linux MDM keys:", error);
+ return undefined;
+ }
+}
+
+function readMdmKeys(): MdmKeys | undefined {
+ const platform = os.platform();
+
+ switch (platform) {
+ case "darwin":
+ return readMdmKeysMacOS();
+
+ case "win32":
+ return readMdmKeysWindows();
+
+ case "linux":
+ return readMdmKeysLinux();
+
+ default:
+ console.error(`MDM keys not supported on platform: ${platform}`);
+ return undefined;
+ }
+}
+
+/**
+ * Read and validate MDM keys from the operating system's configuration files or registry.
+ */
+export function getMdmKeys(): MdmKeys | undefined {
+ try {
+ const mdmKeys = readMdmKeys();
+
+ if (mdmKeys) {
+ if (!validateLicenseKey(mdmKeys.licenseKey)) {
+ console.error("Invalid license key found: ", mdmKeys.licenseKey);
+ return undefined;
+ }
+
+ return mdmKeys;
+ }
+
+ return undefined;
+ } catch (e) {
+ console.warn("Error reading MDM keys: ", e);
+ return undefined;
+ }
+}
diff --git a/core/control-plane/schema.ts b/core/control-plane/schema.ts
index 66b0837ab..c860d99ee 100644
--- a/core/control-plane/schema.ts
+++ b/core/control-plane/schema.ts
@@ -26,6 +26,7 @@ const modelDescriptionSchema = z.object({
apiKey: z.string().optional(),
apiBase: z.string().optional(),
contextLength: z.number().optional(),
+ maxStopWords: z.number().optional(),
template: z
.enum([
"llama2",
diff --git a/core/core.ts b/core/core.ts
index 9ca9108df..497e64c66 100644
--- a/core/core.ts
+++ b/core/core.ts
@@ -35,7 +35,6 @@ import { TTS } from "./util/tts";
import {
ContextItemWithId,
- DiffLine,
IdeSettings,
ModelDescription,
RangeInFile,
@@ -62,61 +61,7 @@ import { LLMLogger } from "./llm/logger";
import { llmStreamChat } from "./llm/streamChat";
import type { FromCoreProtocol, ToCoreProtocol } from "./protocol";
import type { IMessenger, Message } from "./protocol/messenger";
-
-// This function is used for jetbrains inline edit and apply
-async function* streamDiffLinesGenerator(
- configHandler: ConfigHandler,
- abortedMessageIds: Set,
- msg: Message,
-): AsyncGenerator {
- const {
- highlighted,
- prefix,
- suffix,
- input,
- language,
- modelTitle,
- includeRulesInSystemMessage,
- } = msg.data;
-
- const { config } = await configHandler.loadConfig();
- if (!config) {
- throw new Error("Failed to load config");
- }
-
- // Title can be an edit, chat, or apply model
- // Fall back to chat
- const llm =
- config.modelsByRole.edit.find((m) => m.title === modelTitle) ??
- config.modelsByRole.apply.find((m) => m.title === modelTitle) ??
- config.modelsByRole.chat.find((m) => m.title === modelTitle) ??
- config.selectedModelByRole.chat;
-
- if (!llm) {
- throw new Error("No model selected");
- }
-
- // rules included for edit, NOT apply
- const rules = includeRulesInSystemMessage ? config.rules : undefined;
-
- for await (const diffLine of streamDiffLines({
- highlighted,
- prefix,
- suffix,
- llm,
- rulesToInclude: rules,
- input,
- language,
- onlyOneInsertion: false,
- overridePrompt: undefined,
- })) {
- if (abortedMessageIds.has(msg.messageId)) {
- abortedMessageIds.delete(msg.messageId);
- break;
- }
- yield diffLine;
- }
-}
+import { StreamAbortManager } from "./util/abortManager";
export class Core {
configHandler: ConfigHandler;
@@ -132,7 +77,18 @@ export class Core {
this.globalContext.get("indexingPaused") === true,
);
- private abortedMessageIds: Set = new Set();
+ private messageAbortControllers = new Map();
+ private addMessageAbortController(id: string): AbortController {
+ const controller = new AbortController();
+ this.messageAbortControllers.set(id, controller);
+ controller.signal.addEventListener("abort", () => {
+ this.messageAbortControllers.delete(id);
+ });
+ return controller;
+ }
+ private abortById(messageId: string) {
+ this.messageAbortControllers.get(messageId)?.abort();
+ }
invoke(
messageType: T,
@@ -301,7 +257,7 @@ export class Core {
});
on("abort", (msg) => {
- this.abortedMessageIds.add(msg.messageId);
+ this.abortById(msg.data ?? msg.messageId);
});
on("ping", (msg) => {
@@ -470,27 +426,28 @@ export class Core {
}
});
- on("llm/streamChat", (msg) =>
- llmStreamChat(
+ on("llm/streamChat", (msg) => {
+ const abortController = this.addMessageAbortController(msg.messageId);
+ return llmStreamChat(
this.configHandler,
- this.abortedMessageIds,
+ abortController,
msg,
this.ide,
this.messenger,
- ),
- );
+ );
+ });
on("llm/complete", async (msg) => {
- const model = (await this.configHandler.loadConfig()).config
- ?.selectedModelByRole.chat;
-
+ const { config } = await this.configHandler.loadConfig();
+ const model = config?.selectedModelByRole.chat;
if (!model) {
throw new Error("No chat model selected");
}
+ const abortController = this.addMessageAbortController(msg.messageId);
const completion = await model.complete(
msg.data.prompt,
- new AbortController().signal,
+ abortController.signal,
msg.data.completionOptions,
);
return completion;
@@ -532,9 +489,47 @@ export class Core {
this.completionProvider.cancel();
});
- on("streamDiffLines", (msg) =>
- streamDiffLinesGenerator(this.configHandler, this.abortedMessageIds, msg),
- );
+ on("streamDiffLines", async (msg) => {
+ const { config } = await this.configHandler.loadConfig();
+ if (!config) {
+ throw new Error("Failed to load config");
+ }
+
+ const { data } = msg;
+
+ // Title can be an edit, chat, or apply model
+ // Fall back to chat
+ const llm =
+ config.modelsByRole.edit.find((m) => m.title === data.modelTitle) ??
+ config.modelsByRole.apply.find((m) => m.title === data.modelTitle) ??
+ config.modelsByRole.chat.find((m) => m.title === data.modelTitle) ??
+ config.selectedModelByRole.chat;
+
+ if (!llm) {
+ throw new Error("No model selected");
+ }
+
+ return streamDiffLines({
+ highlighted: data.highlighted,
+ prefix: data.prefix,
+ suffix: data.suffix,
+ llm,
+ // rules included for edit, NOT apply
+ rulesToInclude: data.includeRulesInSystemMessage
+ ? config.rules
+ : undefined,
+ input: data.input,
+ language: data.language,
+ onlyOneInsertion: false,
+ overridePrompt: undefined,
+ abortControllerId: data.fileUri ?? "current-file-stream", // not super important since currently cancelling apply will cancel all streams it's one file at a time
+ });
+ });
+
+ on("cancelApply", async (msg) => {
+ const abortManager = StreamAbortManager.getInstance();
+ abortManager.clear();
+ });
on("completeOnboarding", this.handleCompleteOnboarding.bind(this));
@@ -728,6 +723,7 @@ export class Core {
};
return await callTool(tool, toolCall.function.arguments, {
+ config,
ide: this.ide,
llm: config.selectedModelByRole.chat,
fetch: (url, init) =>
diff --git a/core/data/log.test.ts b/core/data/log.test.ts
new file mode 100644
index 000000000..e2471b6bd
--- /dev/null
+++ b/core/data/log.test.ts
@@ -0,0 +1,192 @@
+import { DevDataLogEvent } from "@continuedev/config-yaml";
+import fs from "fs";
+import path from "path";
+import { IdeInfo, IdeSettings } from "..";
+import { Core } from "../core";
+import { getDevDataFilePath } from "../util/paths";
+import { DataLogger } from "./log";
+
+// Only mock fetch, not fs
+jest.mock("@continuedev/fetch");
+
+const TEST_EVENT: DevDataLogEvent = {
+ name: "tokensGenerated",
+ data: {
+ generatedTokens: 100,
+ model: "gpt-4",
+ promptTokens: 50,
+ provider: "openai",
+ },
+};
+const SCHEMA = "0.2.0";
+
+describe("DataLogger", () => {
+ let dataLogger: DataLogger;
+ const tempDir = path.join(process.cwd(), "temp-test-data");
+ const testFilePath = path.join(tempDir, "tokensGenerated-test.jsonl");
+
+ // Create temp directory for test files
+ beforeAll(() => {
+ if (!fs.existsSync(tempDir)) {
+ fs.mkdirSync(tempDir, { recursive: true });
+ }
+ });
+
+ // Clean up temp directory after tests
+ afterAll(() => {
+ if (fs.existsSync(tempDir)) {
+ fs.rmSync(tempDir, { recursive: true, force: true });
+ }
+ });
+
+ beforeEach(() => {
+ // Reset mocks
+ jest.clearAllMocks();
+
+ // Remove test file if it exists
+ if (fs.existsSync(testFilePath)) {
+ fs.unlinkSync(testFilePath);
+ }
+
+ // Get singleton instance
+ dataLogger = DataLogger.getInstance();
+
+ // Mock core and required promises
+ dataLogger.core = {
+ configHandler: {
+ loadConfig: jest.fn().mockResolvedValue({
+ config: {
+ data: [],
+ },
+ }),
+ currentProfile: {
+ profileDescription: {
+ id: "test-profile-id",
+ },
+ },
+ controlPlaneClient: {
+ getAccessToken: jest.fn().mockResolvedValue("test-access-token"),
+ },
+ },
+ } as unknown as Core;
+
+ dataLogger.ideSettingsPromise = Promise.resolve({
+ userToken: "test-user-token",
+ } as IdeSettings);
+
+ dataLogger.ideInfoPromise = Promise.resolve({
+ name: "VSCode",
+ version: "1.0.0",
+ extensionVersion: "0.1.0",
+ } as IdeInfo);
+ });
+
+ describe("getInstance", () => {
+ it("should return the same instance when called multiple times", () => {
+ const instance1 = DataLogger.getInstance();
+ const instance2 = DataLogger.getInstance();
+ expect(instance1).toBe(instance2);
+ });
+ });
+
+ describe("addBaseValues", () => {
+ it("should add base values to event data based on schema", async () => {
+ const mockZodSchema = {
+ shape: {
+ eventName: true,
+ timestamp: true,
+ schema: true,
+ userAgent: true,
+ selectedProfileId: true,
+ userId: true,
+ },
+ };
+
+ const result = await dataLogger.addBaseValues(
+ { customField: "value" },
+ "testEvent",
+ SCHEMA,
+ mockZodSchema as any,
+ );
+
+ expect(result).toEqual({
+ customField: "value",
+ eventName: "testEvent",
+ timestamp: expect.any(String),
+ schema: SCHEMA,
+ userAgent: "VSCode/1.0.0 (Continue/0.1.0)",
+ selectedProfileId: "test-profile-id",
+ userId: "test-user-token",
+ });
+ });
+
+ it("should not add fields not present in schema shape", async () => {
+ const mockZodSchema = {
+ shape: {
+ eventName: true,
+ // No other fields
+ },
+ };
+
+ const result = await dataLogger.addBaseValues(
+ { customField: "value" },
+ "testEvent",
+ SCHEMA,
+ mockZodSchema as any,
+ );
+
+ expect(result).toEqual({
+ customField: "value",
+ eventName: "testEvent",
+ });
+ });
+ });
+
+ describe("logLocalData", () => {
+ it("should actually write data to the local file", async () => {
+ // Call the method to log data locally
+ await dataLogger.logLocalData(TEST_EVENT);
+
+ // Verify the file was created
+ const filepath = getDevDataFilePath(TEST_EVENT.name, SCHEMA);
+ expect(fs.existsSync(filepath)).toBe(true);
+
+ // Read file contents and verify
+ const fileContent = fs.readFileSync(filepath, "utf8");
+ expect(fileContent).toContain('"generatedTokens":100');
+ expect(fileContent).toContain('"model":"gpt-4"');
+ expect(fileContent).toContain('"eventName":"tokensGenerated"');
+ });
+ });
+
+ describe("logDevData", () => {
+ it("should log data locally and to configured destinations", async () => {
+ // Spy on logLocalData and logToOneDestination
+ const logLocalDataSpy = jest
+ .spyOn(dataLogger, "logLocalData")
+ .mockResolvedValue();
+ const logToOneDestinationSpy = jest
+ .spyOn(dataLogger, "logToOneDestination")
+ .mockResolvedValue();
+
+ // Mock config with multiple data destinations
+ const mockConfig = {
+ config: {
+ data: [
+ { destination: "https://example.com/logs", schema: SCHEMA },
+ { destination: "file:///logs", schema: SCHEMA },
+ ],
+ },
+ };
+
+ dataLogger.core!.configHandler.loadConfig = jest
+ .fn()
+ .mockResolvedValue(mockConfig);
+
+ await dataLogger.logDevData(TEST_EVENT);
+
+ expect(logLocalDataSpy).toHaveBeenCalledWith(TEST_EVENT);
+ expect(logToOneDestinationSpy).toHaveBeenCalledTimes(2);
+ });
+ });
+});
diff --git a/core/data/log.ts b/core/data/log.ts
index 4470eba72..c4cf27805 100644
--- a/core/data/log.ts
+++ b/core/data/log.ts
@@ -12,7 +12,7 @@ import * as URI from "uri-js";
import { fileURLToPath } from "url";
import { AnyZodObject } from "zod";
import { Core } from "../core.js";
-import { IdeInfo, IdeSettings } from "../index.js";
+import { ContinueConfig, IdeInfo, IdeSettings } from "../index.js";
import { getDevDataFilePath } from "../util/paths.js";
import { joinPathsToUri } from "../util/uri.js";
@@ -68,8 +68,7 @@ export class DataLogger {
return newBody;
}
- async logDevData(event: DevDataLogEvent) {
- // Local logs (always on for all levels)
+ async logLocalData(event: DevDataLogEvent) {
try {
const filepath: string = getDevDataFilePath(
event.name,
@@ -100,126 +99,144 @@ export class DataLogger {
} catch (error) {
console.error("Error logging local dev data:", error);
}
+ }
+
+ async logDevData(event: DevDataLogEvent) {
+ // Local logs (always on for all levels)
+ await this.logLocalData(event);
// Remote logs
const config = (await this.core?.configHandler.loadConfig())?.config;
if (config?.data?.length) {
await Promise.allSettled(
- config.data.map(async (dataConfig) => {
- try {
- // First extract the data schema based on the version and level
- const { schema } = dataConfig;
+ config.data.map((dataConfig) =>
+ this.logToOneDestination(dataConfig, event),
+ ),
+ );
+ }
+ }
- const level = dataConfig.level ?? DEFAULT_DEV_DATA_LEVEL;
+ async parseEventData(
+ event: DevDataLogEvent,
+ schema: string,
+ level: "all" | "noCode",
+ ) {
+ const versionSchemas = devDataVersionedSchemas[schema];
+ if (!versionSchemas) {
+ throw new Error(
+ `Attempting to log dev data to non-existent version ${schema}`,
+ );
+ }
- // Skip event if `events` is specified and does not include the event
- const events = dataConfig.events ?? allDevEventNames;
- if (!events.includes(event.name)) {
- return;
- }
+ const levelSchemas = versionSchemas[level];
+ if (!levelSchemas) {
+ throw new Error(
+ `Attempting to log dev data at level ${level} for version ${schema} which does not exist`,
+ );
+ }
- const versionSchemas = devDataVersionedSchemas[schema];
- if (!versionSchemas) {
- throw new Error(
- `Attempting to log dev data to non-existent version ${schema}`,
- );
- }
+ const zodSchema = levelSchemas[event.name];
+ if (!zodSchema) {
+ throw new Error(
+ `Attempting to log dev data for event ${event.name} at level ${level} for version ${schema}: no schema found`,
+ );
+ }
- const levelSchemas = versionSchemas[level];
- if (!levelSchemas) {
- throw new Error(
- `Attempting to log dev data at level ${level} for version ${schema} which does not exist`,
- );
- }
+ const eventDataWithBaseValues = await this.addBaseValues(
+ event.data,
+ event.name,
+ schema,
+ zodSchema,
+ );
- const zodSchema = levelSchemas[event.name];
- if (!zodSchema) {
- throw new Error(
- `Attempting to log dev data for event ${event.name} at level ${level} for version ${schema}: no schema found`,
- );
- }
+ const parsed = zodSchema.safeParse(eventDataWithBaseValues);
+ if (!parsed.success) {
+ throw new Error(
+ `Failed to parse event data for event ${event.name} and schema ${schema}\n:${parsed.error.toString()}`,
+ );
+ }
- const eventDataWithBaseValues = await this.addBaseValues(
- event.data,
- event.name,
+ return parsed.data;
+ }
+
+ async logToOneDestination(
+ dataConfig: NonNullable[number],
+ event: DevDataLogEvent,
+ ) {
+ try {
+ if (!dataConfig) {
+ return;
+ }
+
+ // First extract the data schema based on the version and level
+ const { schema } = dataConfig;
+ const level = dataConfig.level ?? DEFAULT_DEV_DATA_LEVEL;
+
+ // Skip event if `events` is specified and does not include the event
+ const events = dataConfig.events ?? allDevEventNames;
+ if (!events.includes(event.name)) {
+ return;
+ }
+
+ // Parse the event data, throwing if it fails
+ const parsed = await this.parseEventData(event, schema, level);
+
+ const uriComponents = URI.parse(dataConfig.destination);
+
+ // Send to remote server
+ if (uriComponents.scheme === "https" || uriComponents.scheme === "http") {
+ const headers: Record = {
+ "Content-Type": "application/json",
+ };
+
+ // If an API key is provided, use it, otherwise use the Continue access token
+ if (dataConfig.apiKey) {
+ headers["Authorization"] = `Bearer ${dataConfig.apiKey}`;
+ } else {
+ const accessToken =
+ await this.core?.configHandler.controlPlaneClient.getAccessToken();
+ headers["Authorization"] = `Bearer ${accessToken}`;
+ }
+
+ const profileId =
+ this.core?.configHandler.currentProfile?.profileDescription.id ?? "";
+ const response = await fetchwithRequestOptions(
+ dataConfig.destination,
+ {
+ method: "POST",
+ headers,
+ body: JSON.stringify({
+ name: event.name,
+ data: parsed,
schema,
- zodSchema,
- );
+ level,
+ profileId,
+ }),
+ },
+ dataConfig.requestOptions,
+ );
+ if (!response.ok) {
+ throw new Error(
+ `Post request failed. ${response.status}: ${response.statusText}`,
+ );
+ }
+ } else if (uriComponents.scheme === "file") {
+ // Write to jsonc file for local file URIs
+ const dirUri = joinPathsToUri(dataConfig.destination, schema);
+ const dirPath = fileURLToPath(dirUri);
- const parsed = zodSchema.safeParse(eventDataWithBaseValues);
- if (!parsed.success) {
- throw new Error(
- `Failed to parse event data for event ${event.name} and schema ${schema}\n:${parsed.error.toString()}`,
- );
- }
-
- const uriComponents = URI.parse(dataConfig.destination);
-
- // Send to remote server
- if (
- uriComponents.scheme === "https" ||
- uriComponents.scheme === "http"
- ) {
- const headers: Record = {
- "Content-Type": "application/json",
- };
- if (dataConfig.apiKey) {
- headers["Authorization"] = `Bearer ${dataConfig.apiKey}`;
- }
-
- // For events going to Continue, overwrite the access token
- if (
- uriComponents.host?.endsWith(".continue.dev") ||
- uriComponents.host === "continue.dev"
- ) {
- //
- const accessToken =
- await this.core?.configHandler.controlPlaneClient.getAccessToken();
- headers["Authorization"] = `Bearer ${accessToken}`;
- }
- const profileId =
- this.core?.configHandler.currentProfile?.profileDescription
- .id ?? "";
- const response = await fetchwithRequestOptions(
- dataConfig.destination,
- {
- method: "POST",
- headers,
- body: JSON.stringify({
- name: event.name,
- data: parsed.data,
- schema,
- level,
- profileId,
- }),
- },
- dataConfig.requestOptions,
- );
- if (!response.ok) {
- throw new Error(
- `Post request failed. ${response.status}: ${response.statusText}`,
- );
- }
- } else if (uriComponents.scheme === "file") {
- // Write to jsonc file for local file URIs
- const dirUri = joinPathsToUri(dataConfig.destination, schema);
- const dirPath = fileURLToPath(dirUri);
-
- if (!fs.existsSync(dirPath)) {
- fs.mkdirSync(dirPath, { recursive: true });
- }
- const filepath = path.join(dirPath, `${event.name}.jsonl`);
- const jsonLine = JSON.stringify(event.data);
- fs.writeFileSync(filepath, `${jsonLine}\n`, { flag: "a" });
- } else {
- throw new Error(`Unsupported URI scheme ${uriComponents.scheme}`);
- }
- } catch (error) {
- console.error(
- `Error logging data to ${dataConfig.destination}: ${error instanceof Error ? error.message : error}`,
- );
- }
- }),
+ if (!fs.existsSync(dirPath)) {
+ fs.mkdirSync(dirPath, { recursive: true });
+ }
+ const filepath = path.join(dirPath, `${event.name}.jsonl`);
+ const jsonLine = JSON.stringify(event.data);
+ fs.writeFileSync(filepath, `${jsonLine}\n`, { flag: "a" });
+ } else {
+ throw new Error(`Unsupported URI scheme ${uriComponents.scheme}`);
+ }
+ } catch (error) {
+ console.error(
+ `Error logging data to ${dataConfig.destination}: ${error instanceof Error ? error.message : error}`,
);
}
}
diff --git a/core/edit/recursiveStream.ts b/core/edit/recursiveStream.ts
index 9cb2db915..004563cdb 100644
--- a/core/edit/recursiveStream.ts
+++ b/core/edit/recursiveStream.ts
@@ -16,6 +16,7 @@ const RECURSIVE_PROMPT = `Continue EXACTLY where you left`;
export async function* recursiveStream(
llm: ILLM,
+ abortController: AbortController,
prompt: ChatMessage[] | string,
prediction: Prediction | undefined,
currentBuffer = "",
@@ -28,7 +29,7 @@ export async function* recursiveStream(
// let whiteSpaceAtEndOfBuffer = buffer.match(/\s*$/)?.[0] ?? ""; // attempts at fixing whitespace bug with recursive boundaries
if (typeof prompt === "string") {
- const generator = llm.streamComplete(prompt, new AbortController().signal, {
+ const generator = llm.streamComplete(prompt, abortController.signal, {
raw: true,
prediction: undefined,
reasoning: false,
@@ -50,6 +51,7 @@ export async function* recursiveStream(
// // TODO - Prediction capabilities lost because of partial input
// yield* recursiveStream(
// llm,
+ // abortController,
// continuationPrompt,
// undefined,
// buffer,
@@ -60,7 +62,7 @@ export async function* recursiveStream(
}
}
} else {
- const generator = llm.streamChat(prompt, new AbortController().signal, {
+ const generator = llm.streamChat(prompt, abortController.signal, {
prediction,
reasoning: false,
});
@@ -90,6 +92,7 @@ export async function* recursiveStream(
// await generator.return(DUD_PROMPT_LOG);
// yield* recursiveStream(
// llm,
+ // abortController,
// continuationPrompt,
// undefined,
// buffer,
diff --git a/core/edit/streamDiffLines.ts b/core/edit/streamDiffLines.ts
index 4cba92608..096b31d7d 100644
--- a/core/edit/streamDiffLines.ts
+++ b/core/edit/streamDiffLines.ts
@@ -20,6 +20,7 @@ import { streamDiff } from "../diff/streamDiff";
import { streamLines } from "../diff/util";
import { getSystemMessageWithRules } from "../llm/rules/getSystemMessageWithRules";
import { gptEditPrompt } from "../llm/templates/edit";
+import { StreamAbortManager } from "../util/abortManager";
import { findLast } from "../util/findLast";
import { Telemetry } from "../util/posthog";
import { recursiveStream } from "./recursiveStream";
@@ -63,6 +64,7 @@ export async function* streamDiffLines({
highlighted,
suffix,
llm,
+ abortControllerId,
input,
language,
onlyOneInsertion,
@@ -73,12 +75,15 @@ export async function* streamDiffLines({
highlighted: string;
suffix: string;
llm: ILLM;
+ abortControllerId: string;
input: string;
language: string | undefined;
onlyOneInsertion: boolean;
overridePrompt: ChatMessage[] | undefined;
rulesToInclude: RuleWithSource[] | undefined;
}): AsyncGenerator {
+ const abortManager = StreamAbortManager.getInstance();
+ const abortController = abortManager.get(abortControllerId);
void Telemetry.capture(
"inlineEdit",
{
@@ -122,6 +127,7 @@ export async function* streamDiffLines({
(msg) => msg.role === "user" || msg.role === "tool",
) as UserChatMessage | ToolResultChatMessage | undefined),
baseSystemMessage: undefined,
+ contextItems: [],
})
: undefined;
@@ -157,7 +163,7 @@ export async function* streamDiffLines({
content: highlighted,
};
- const completion = recursiveStream(llm, prompt, prediction);
+ const completion = recursiveStream(llm, abortController, prompt, prediction);
let lines = streamLines(completion);
diff --git a/core/index.d.ts b/core/index.d.ts
index 6faff1bab..1f5d0d4a5 100644
--- a/core/index.d.ts
+++ b/core/index.d.ts
@@ -93,6 +93,7 @@ export interface ILLM
extends Omit,
Required> {
get providerName(): string;
+ get underlyingProviderName(): string;
complete(
prompt: string,
@@ -197,15 +198,14 @@ export interface CustomContextProvider {
description?: string;
renderInlineAs?: string;
type?: ContextProviderType;
+ loadSubmenuItems?: (
+ args: LoadSubmenuItemsArgs,
+ ) => Promise;
getContextItems(
query: string,
extras: ContextProviderExtras,
): Promise;
-
- loadSubmenuItems?: (
- args: LoadSubmenuItemsArgs,
- ) => Promise;
}
export interface ContextSubmenuItem {
@@ -424,7 +424,7 @@ export interface PromptLog {
completion: string;
}
-export type MessageModes = "chat" | "edit" | "agent";
+export type MessageModes = "chat" | "agent";
export type ToolStatus =
| "generating"
@@ -459,6 +459,7 @@ export interface ChatHistoryItem {
toolCallState?: ToolCallState;
isGatheringContext?: boolean;
reasoning?: Reasoning;
+ appliedRules?: RuleWithSource[];
}
export interface LLMFullCompletionOptions extends BaseCompletionOptions {
@@ -842,6 +843,7 @@ export interface SlashCommand {
description: string;
prompt?: string;
params?: { [key: string]: any };
+ promptFile?: string;
run: (sdk: ContinueSDK) => AsyncGenerator;
}
@@ -973,6 +975,7 @@ export interface ToolExtras {
toolCallId: string;
contextItems: ContextItem[];
}) => void;
+ config: ContinueConfig;
}
export interface Tool {
@@ -1002,6 +1005,12 @@ interface ToolChoice {
};
}
+export interface ConfigDependentToolParams {
+ rules: RuleWithSource[];
+}
+
+export type GetTool = (params: ConfigDependentToolParams) => Tool;
+
export interface BaseCompletionOptions {
temperature?: number;
topP?: number;
@@ -1023,6 +1032,7 @@ export interface BaseCompletionOptions {
toolChoice?: ToolChoice;
reasoning?: boolean;
reasoningBudgetTokens?: number;
+ promptCaching?: boolean;
}
export interface ModelCapability {
@@ -1033,6 +1043,7 @@ export interface ModelCapability {
export interface ModelDescription {
title: string;
provider: string;
+ underlyingProviderName: string;
model: string;
apiKey?: string;
@@ -1090,6 +1101,7 @@ export interface TabAutocompleteOptions {
disable: boolean;
maxPromptTokens: number;
debounceDelay: number;
+ modelTimeout: number;
maxSuffixPercentage: number;
prefixPercentage: number;
transform?: boolean;
@@ -1130,7 +1142,17 @@ export interface SSEOptions {
requestOptions?: RequestOptions;
}
-export type TransportOptions = StdioOptions | WebSocketOptions | SSEOptions;
+export interface StreamableHTTPOptions {
+ type: "streamable-http";
+ url: string;
+ requestOptions?: RequestOptions;
+}
+
+export type TransportOptions =
+ | StdioOptions
+ | WebSocketOptions
+ | SSEOptions
+ | StreamableHTTPOptions;
export interface MCPOptions {
name: string;
@@ -1159,12 +1181,22 @@ export interface MCPPrompt {
// Leaving here to ideate on
// export type ContinueConfigSource = "local-yaml" | "local-json" | "hub-assistant" | "hub"
+// https://modelcontextprotocol.io/docs/concepts/resources#direct-resources
export interface MCPResource {
name: string;
uri: string;
description?: string;
mimeType?: string;
}
+
+// https://modelcontextprotocol.io/docs/concepts/resources#resource-templates
+export interface MCPResourceTemplate {
+ uriTemplate: string;
+ name: string;
+ description?: string;
+ mimeType?: string;
+}
+
export interface MCPTool {
name: string;
description?: string;
@@ -1181,6 +1213,7 @@ export interface MCPServerStatus extends MCPOptions {
prompts: MCPPrompt[];
tools: MCPTool[];
resources: MCPResource[];
+ resourceTemplates: MCPResourceTemplate[];
}
export interface ContinueUIConfig {
@@ -1190,6 +1223,7 @@ export interface ContinueUIConfig {
showChatScrollbar?: boolean;
codeWrap?: boolean;
showSessionTabs?: boolean;
+ autoAcceptEditToolDiffs?: boolean;
}
export interface ContextMenuConfig {
@@ -1227,6 +1261,32 @@ export interface ApplyState {
toolCallId?: string;
}
+export interface StreamDiffLinesPayload {
+ prefix: string;
+ highlighted: string;
+ suffix: string;
+ input: string;
+ language: string | undefined;
+ modelTitle: string | undefined;
+ includeRulesInSystemMessage: boolean;
+ fileUri?: string;
+}
+
+export interface HighlightedCodePayload {
+ rangeInFileWithContents: RangeInFileWithContents;
+ prompt?: string;
+ shouldRun?: boolean;
+}
+
+export interface AcceptOrRejectDiffPayload {
+ filepath: string;
+ streamId?: string;
+}
+
+export interface ShowFilePayload {
+ filepath: string;
+}
+
export interface RangeInFileWithContents {
filepath: string;
range: {
@@ -1236,7 +1296,7 @@ export interface RangeInFileWithContents {
contents: string;
}
-export type CodeToEdit = RangeInFileWithContents | FileWithContents;
+export type SetCodeToEditPayload = RangeInFileWithContents | FileWithContents;
/**
* Represents the configuration for a quick action in the Code Lens.
@@ -1291,6 +1351,11 @@ export interface ExperimentalConfig {
*/
useChromiumForDocsCrawling?: boolean;
modelContextProtocolServers?: ExperimentalMCPOptions[];
+
+ /**
+ * If enabled, will add the current file as context.
+ */
+ useCurrentFileAsContext?: boolean;
}
export interface AnalyticsConfig {
@@ -1302,6 +1367,7 @@ export interface AnalyticsConfig {
export interface JSONModelDescription {
title: string;
provider: string;
+ underlyingProviderName: string;
model: string;
apiKey?: string;
apiBase?: string;
@@ -1495,19 +1561,22 @@ export interface TerminalOptions {
waitForCompletion?: boolean;
}
+export type RuleSource =
+ | "default-chat"
+ | "default-agent"
+ | "model-chat-options"
+ | "model-agent-options"
+ | "rules-block"
+ | "json-systemMessage"
+ | ".continuerules";
+
export interface RuleWithSource {
name?: string;
slug?: string;
- source:
- | "default-chat"
- | "default-agent"
- | "model-chat-options"
- | "model-agent-options"
- | "rules-block"
- | "json-systemMessage"
- | ".continuerules";
+ source: RuleSource;
globs?: string | string[];
rule: string;
description?: string;
ruleFile?: string;
+ alwaysApply?: boolean;
}
diff --git a/core/indexing/CodeSnippetsIndex.ts b/core/indexing/CodeSnippetsIndex.ts
index 9a2da5008..bf79b093e 100644
--- a/core/indexing/CodeSnippetsIndex.ts
+++ b/core/indexing/CodeSnippetsIndex.ts
@@ -7,7 +7,7 @@ import {
getQueryForFile,
} from "../util/treeSitter";
-import { DatabaseConnection, SqliteDb, tagToString } from "./refreshIndex";
+import { DatabaseConnection, SqliteDb } from "./refreshIndex";
import {
IndexResultType,
MarkCompleteCallback,
@@ -29,6 +29,7 @@ import {
getLastNUriRelativePathParts,
getUriPathBasename,
} from "../util/uri";
+import { tagToString } from "./utils";
type SnippetChunk = ChunkWithoutID & { title: string; signature: string };
diff --git a/core/indexing/CodebaseIndexer.ts b/core/indexing/CodebaseIndexer.ts
index 0bd1f57b6..1f9017e3d 100644
--- a/core/indexing/CodebaseIndexer.ts
+++ b/core/indexing/CodebaseIndexer.ts
@@ -249,7 +249,10 @@ export class CodebaseIndexer {
}
const { config } = await this.configHandler.loadConfig();
- if (config?.disableIndexing) {
+ if (!config) {
+ return;
+ }
+ if (config.disableIndexing) {
yield {
progress,
desc: "Indexing is disabled in config.json",
diff --git a/core/indexing/FullTextSearchCodebaseIndex.ts b/core/indexing/FullTextSearchCodebaseIndex.ts
index de183e158..1bac74e4a 100644
--- a/core/indexing/FullTextSearchCodebaseIndex.ts
+++ b/core/indexing/FullTextSearchCodebaseIndex.ts
@@ -3,13 +3,14 @@ import { RETRIEVAL_PARAMS } from "../util/parameters";
import { getUriPathBasename } from "../util/uri";
import { ChunkCodebaseIndex } from "./chunk/ChunkCodebaseIndex";
-import { DatabaseConnection, SqliteDb, tagToString } from "./refreshIndex";
+import { DatabaseConnection, SqliteDb } from "./refreshIndex";
import {
IndexResultType,
MarkCompleteCallback,
RefreshIndexResults,
type CodebaseIndex,
} from "./types";
+import { tagToString } from "./utils";
export interface RetrieveConfig {
tags: BranchAndDir[];
@@ -97,11 +98,14 @@ export class FullTextSearchCodebaseIndex implements CodebaseIndex {
// Delete
for (const item of results.del) {
- await db.run(`
+ await db.run(
+ `
DELETE FROM fts WHERE rowid IN (
SELECT id FROM fts_metadata WHERE path = ? AND cacheKey = ?
)
- `,[item.path, item.cacheKey]);
+ `,
+ [item.path, item.cacheKey],
+ );
await db.run("DELETE FROM fts_metadata WHERE path = ? AND cacheKey = ?", [
item.path,
item.cacheKey,
diff --git a/core/indexing/LanceDbIndex.ts b/core/indexing/LanceDbIndex.ts
index 3bf9a645d..cf41beaca 100644
--- a/core/indexing/LanceDbIndex.ts
+++ b/core/indexing/LanceDbIndex.ts
@@ -14,7 +14,7 @@ import { getUriPathBasename } from "../util/uri";
import { basicChunker } from "./chunk/basic.js";
import { chunkDocument, shouldChunk } from "./chunk/chunk.js";
-import { DatabaseConnection, SqliteDb, tagToString } from "./refreshIndex.js";
+import { DatabaseConnection, SqliteDb } from "./refreshIndex.js";
import {
CodebaseIndex,
IndexResultType,
@@ -24,6 +24,7 @@ import {
} from "./types";
import type * as LanceType from "vectordb";
+import { tagToString } from "./utils";
interface LanceDbRow {
uuid: string;
diff --git a/core/indexing/chunk/ChunkCodebaseIndex.ts b/core/indexing/chunk/ChunkCodebaseIndex.ts
index 9b39e506a..412ff7480 100644
--- a/core/indexing/chunk/ChunkCodebaseIndex.ts
+++ b/core/indexing/chunk/ChunkCodebaseIndex.ts
@@ -4,7 +4,7 @@ import { RunResult } from "sqlite3";
import { IContinueServerClient } from "../../continueServer/interface.js";
import { Chunk, IndexTag, IndexingProgressUpdate } from "../../index.js";
-import { DatabaseConnection, SqliteDb, tagToString } from "../refreshIndex.js";
+import { DatabaseConnection, SqliteDb } from "../refreshIndex.js";
import {
IndexResultType,
MarkCompleteCallback,
@@ -13,8 +13,9 @@ import {
type CodebaseIndex,
} from "../types.js";
-import { chunkDocument, shouldChunk } from "./chunk.js";
import { getUriPathBasename } from "../../util/uri.js";
+import { tagToString } from "../utils.js";
+import { chunkDocument, shouldChunk } from "./chunk.js";
export class ChunkCodebaseIndex implements CodebaseIndex {
relativeExpectedTime: number = 1;
diff --git a/core/indexing/refreshIndex.ts b/core/indexing/refreshIndex.ts
index f76c6a7f6..ec84f631b 100644
--- a/core/indexing/refreshIndex.ts
+++ b/core/indexing/refreshIndex.ts
@@ -18,10 +18,6 @@ import {
export type DatabaseConnection = Database;
-export function tagToString(tag: IndexTag): string {
- return `${tag.directory}::${tag.branch}::${tag.artifactId}`;
-}
-
export class SqliteDb {
static db: DatabaseConnection | null = null;
diff --git a/core/indexing/test/indexing.ts b/core/indexing/test/indexing.ts
index 5f22d0aeb..b90f52564 100644
--- a/core/indexing/test/indexing.ts
+++ b/core/indexing/test/indexing.ts
@@ -3,11 +3,11 @@ import { jest } from "@jest/globals";
import { IndexTag } from "../..";
import { IContinueServerClient } from "../../continueServer/interface";
import { ChunkCodebaseIndex } from "../chunk/ChunkCodebaseIndex";
-import { tagToString } from "../refreshIndex";
import { CodebaseIndex, RefreshIndexResults } from "../types";
import { testIde } from "../../test/fixtures";
import { addToTestDir, TEST_DIR } from "../../test/testDir";
+import { tagToString } from "../utils";
export const mockFilename = "test.py";
export const mockPathAndCacheKey = {
diff --git a/core/indexing/utils.test.ts b/core/indexing/utils.test.ts
new file mode 100644
index 000000000..414fb6ff5
--- /dev/null
+++ b/core/indexing/utils.test.ts
@@ -0,0 +1,95 @@
+import { IndexTag } from "..";
+import { tagToString } from "./utils";
+
+test("tagToString returns full tag string when under length limit", () => {
+ const tag: IndexTag = {
+ directory: "/normal/path/to/repo",
+ branch: "main",
+ artifactId: "12345",
+ };
+
+ expect(tagToString(tag)).toBe("/normal/path/to/repo::main::12345");
+});
+
+test("tagToString truncates beginning of directory when path is too long and adds hash for uniqueness", () => {
+ const longPrefix = "/very/long/path/that/will/be/truncated/";
+ const importantSuffix = "/user/important-project/src/feature";
+ const longPath = longPrefix + "x".repeat(200) + importantSuffix;
+
+ const tag: IndexTag = {
+ directory: longPath,
+ branch: "feature-branch",
+ artifactId: "67890",
+ };
+
+ const result = tagToString(tag);
+
+ expect(result).toContain("::feature-branch::67890");
+ expect(result.length).toBeLessThanOrEqual(240);
+ expect(result).toMatch(/^[a-f0-9]{8}_/);
+ expect(result).toContain(importantSuffix);
+});
+
+test("tagToString preserves branch and artifactId exactly, even when truncating", () => {
+ const longPath = "/a".repeat(300);
+ const tag: IndexTag = {
+ directory: longPath,
+ branch: "release-v2.0",
+ artifactId: "build-123",
+ };
+
+ const result = tagToString(tag);
+
+ expect(result).toContain("::release-v2.0::build-123");
+ expect(result).toMatch(/^[a-f0-9]{8}_/);
+ expect(result.length).toBeLessThanOrEqual(240);
+});
+
+test("tagToString ensures uniqueness for different long paths that would otherwise collide", () => {
+ const basePath = "/very/long/base/path/that/exceeds/limits/";
+ const commonSuffix = "/same/ending/path";
+
+ const tag1: IndexTag = {
+ directory: basePath + "different1" + "x".repeat(100) + commonSuffix,
+ branch: "main",
+ artifactId: "12345",
+ };
+
+ const tag2: IndexTag = {
+ directory: basePath + "different2" + "y".repeat(100) + commonSuffix,
+ branch: "main",
+ artifactId: "12345",
+ };
+
+ const fullString1 = `${tag1.directory}::${tag1.branch}::${tag1.artifactId}`;
+ const fullString2 = `${tag2.directory}::${tag2.branch}::${tag2.artifactId}`;
+
+ const result1 = tagToString(tag1);
+ const result2 = tagToString(tag2);
+
+ expect(result1).not.toBe(result2);
+ expect(result1.length).toBeLessThanOrEqual(240);
+ expect(result2.length).toBeLessThanOrEqual(240);
+
+ if (fullString1.length > 240) {
+ expect(result1).toMatch(/^[a-f0-9]{8}_/);
+ expect(result2).toMatch(/^[a-f0-9]{8}_/);
+ } else {
+ expect(result1).toBe(fullString1);
+ expect(result2).toBe(fullString2);
+ }
+});
+
+test("tagToString produces consistent results for the same input", () => {
+ const tag: IndexTag = {
+ directory:
+ "/some/very/long/path/that/exceeds/the/maximum/length/limit/for/directory/names/in/the/system",
+ branch: "develop",
+ artifactId: "test-123",
+ };
+
+ const result1 = tagToString(tag);
+ const result2 = tagToString(tag);
+
+ expect(result1).toBe(result2);
+});
diff --git a/core/indexing/utils.ts b/core/indexing/utils.ts
new file mode 100644
index 000000000..40ef7c39a
--- /dev/null
+++ b/core/indexing/utils.ts
@@ -0,0 +1,54 @@
+import crypto from "crypto";
+import { IndexTag } from "..";
+
+// Maximum length for table names to stay under OS filename limits
+const MAX_TABLE_NAME_LENGTH = 240;
+
+// Leave room for branch and artifactId
+const MAX_DIR_LENGTH = 200;
+
+/**
+ * Converts an IndexTag to a string representation, safely handling long paths.
+ *
+ * The string is used as a table name and identifier in various places, so it needs
+ * to stay under OS filename length limits (typically 255 chars). This is especially
+ * important for dev containers where the directory path can be very long due to
+ * containing container configuration.
+ *
+ * The format is: "{directory}::{branch}::{artifactId}"
+ *
+ * To handle long paths:
+ * 1. First tries the full string - most backwards compatible
+ * 2. If too long, truncates directory from the beginning and adds a hash prefix
+ * to ensure uniqueness while preserving the more readable end parts
+ * 3. Finally ensures entire string stays under MAX_TABLE_NAME_LENGTH for OS compatibility
+ *
+ * @param tag The tag containing directory, branch, and artifactId
+ * @returns A string representation safe for use as a table name
+ */
+export function tagToString(tag: IndexTag): string {
+ const result = `${tag.directory}::${tag.branch}::${tag.artifactId}`;
+
+ if (result.length <= MAX_TABLE_NAME_LENGTH) {
+ return result;
+ }
+
+ // Create a hash of the full directory path to ensure uniqueness
+ const dirHash = crypto
+ .createHash("md5")
+ .update(tag.directory)
+ .digest("hex")
+ .slice(0, 8);
+
+ // Calculate how much space we have for the directory after accounting for hash, separators, branch, and artifactId
+ const nonDirLength = `${dirHash}_::${tag.branch}::${tag.artifactId}`.length;
+ const maxDirForTruncated = MAX_TABLE_NAME_LENGTH - nonDirLength;
+
+ // Truncate from the beginning of directory path to preserve the more unique end parts
+ const truncatedDir =
+ tag.directory.length > maxDirForTruncated
+ ? tag.directory.slice(tag.directory.length - maxDirForTruncated)
+ : tag.directory;
+
+ return `${dirHash}_${truncatedDir}::${tag.branch}::${tag.artifactId}`;
+}
diff --git a/core/llm/autodetect.ts b/core/llm/autodetect.ts
index ea34414f7..cc8d3c766 100644
--- a/core/llm/autodetect.ts
+++ b/core/llm/autodetect.ts
@@ -79,7 +79,8 @@ const PROVIDER_SUPPORTS_IMAGES: string[] = [
"azure",
"scaleway",
"nebius",
- "ovhcloud"
+ "ovhcloud",
+ "watsonx",
];
const MODEL_SUPPORTS_IMAGES: string[] = [
@@ -99,6 +100,7 @@ const MODEL_SUPPORTS_IMAGES: string[] = [
"llama3.2",
"llama-3.2",
"llama4",
+ "granite-vision",
];
function modelSupportsTools(modelDescription: ModelDescription) {
diff --git a/core/llm/constructMessages.ts b/core/llm/constructMessages.ts
index 309429d4b..5358deee5 100644
--- a/core/llm/constructMessages.ts
+++ b/core/llm/constructMessages.ts
@@ -1,6 +1,7 @@
import {
ChatHistoryItem,
ChatMessage,
+ ContextItemWithId,
RuleWithSource,
TextMessagePart,
ToolResultChatMessage,
@@ -58,7 +59,7 @@ const EDIT_MESSAGE = `\
at the beginning, middle, or end of files using these "lazy" comments. Only
provide the complete file when explicitly requested. Include a concise explanation
of changes unless the user specifically asks for code only.
-`
+`;
export const DEFAULT_CHAT_SYSTEM_MESSAGE = `\
@@ -77,6 +78,31 @@ export const DEFAULT_AGENT_SYSTEM_MESSAGE = `\
${EDIT_MESSAGE}
`;
+/**
+ * Helper function to get the context items for a user message
+ */
+function getUserContextItems(
+ userMsg: UserChatMessage | ToolResultChatMessage | undefined,
+ history: ChatHistoryItem[],
+): ContextItemWithId[] {
+ if (!userMsg) return [];
+
+ // Find the history item that contains the userMsg
+ const historyItem = history.find((item) => {
+ // Check if the message ID matches
+ if ("id" in userMsg && "id" in item.message) {
+ return (item.message as any).id === (userMsg as any).id;
+ }
+ // Fallback to content comparison
+ return (
+ item.message.content === userMsg.content &&
+ item.message.role === userMsg.role
+ );
+ });
+
+ return historyItem?.contextItems || [];
+}
+
export function constructMessages(
messageMode: string,
history: ChatHistoryItem[],
@@ -92,7 +118,8 @@ export function constructMessages(
const historyItem = filteredHistory[i];
if (messageMode === "chat") {
- const toolMessage: ToolResultChatMessage = historyItem.message as ToolResultChatMessage;
+ const toolMessage: ToolResultChatMessage =
+ historyItem.message as ToolResultChatMessage;
if (historyItem.toolCallState?.toolCallId || toolMessage.toolCallId) {
// remove all tool calls from the history
continue;
@@ -127,10 +154,16 @@ export function constructMessages(
| ToolResultChatMessage
| undefined;
+ // Get context items for the last user message
+ const lastUserContextItems = getUserContextItems(
+ lastUserMsg,
+ filteredHistory,
+ );
const systemMessage = getSystemMessageWithRules({
baseSystemMessage: baseChatOrAgentSystemMessage,
rules,
userMessage: lastUserMsg,
+ contextItems: lastUserContextItems,
});
if (systemMessage.trim()) {
diff --git a/core/llm/index.ts b/core/llm/index.ts
index 96fdb319c..0d25d882c 100644
--- a/core/llm/index.ts
+++ b/core/llm/index.ts
@@ -88,6 +88,14 @@ export abstract class BaseLLM implements ILLM {
return (this.constructor as typeof BaseLLM).providerName;
}
+ /**
+ * This exists because for the continue-proxy, sometimes we want to get the value of the underlying provider that is used on the server
+ * For example, the underlying provider should always be sent with dev data
+ */
+ get underlyingProviderName(): string {
+ return this.providerName;
+ }
+
supportsFim(): boolean {
return false;
}
@@ -332,7 +340,7 @@ export abstract class BaseLLM implements ILLM {
name: "tokensGenerated",
data: {
model: model,
- provider: this.providerName,
+ provider: this.underlyingProviderName,
promptTokens: promptTokens,
generatedTokens: generatedTokens,
},
@@ -382,6 +390,9 @@ export abstract class BaseLLM implements ILLM {
// Error mapping to be more helpful
if (!resp.ok) {
+ if (resp.status === 499) {
+ return resp; // client side cancellation
+ }
let text = await resp.text();
if (resp.status === 404 && !resp.url.includes("/v1")) {
const error = JSON.parse(text)?.error?.replace(/"/g, "'");
diff --git a/core/llm/llm.test.ts b/core/llm/llm.test.ts
index d1067a8bc..ae21e68ee 100644
--- a/core/llm/llm.test.ts
+++ b/core/llm/llm.test.ts
@@ -22,6 +22,20 @@ const COMPLETION_OPTIONS: Partial = {
// maxTokens: 5,
};
+/**
+ * Retries a test function if it fails on the first attempt
+ * @param testFn The test function to run
+ * @returns A function that will retry once if the test fails
+ */
+const retryOnce = (testFn: () => Promise) => async () => {
+ try {
+ return await testFn();
+ } catch (error) {
+ console.log("Test failed on first attempt, retrying once...");
+ return await testFn();
+ }
+};
+
function testLLM(
llm: BaseLLM,
{
@@ -47,7 +61,7 @@ function testLLM(
describe(llm.providerName + "/" + llm.model, () => {
test(
"Stream Chat works",
- async () => {
+ retryOnce(async () => {
let total = "";
for await (const chunk of llm.streamChat(
[{ role: "user", content: "Hi" }],
@@ -58,13 +72,13 @@ function testLLM(
expect(total.length).toBeGreaterThan(0);
return;
- },
+ }),
timeout,
);
test(
"Stream Complete works",
- async () => {
+ retryOnce(async () => {
let total = "";
for await (const chunk of llm.streamComplete(
"Hi",
@@ -75,13 +89,13 @@ function testLLM(
expect(total.length).toBeGreaterThan(0);
return;
- },
+ }),
timeout,
);
test(
"Complete works",
- async () => {
+ retryOnce(async () => {
const completion = await llm.complete(
"Hi",
new AbortController().signal,
@@ -89,14 +103,14 @@ function testLLM(
expect(completion.length).toBeGreaterThan(0);
return;
- },
+ }),
timeout,
);
if (testFim) {
test(
"FIM works",
- async () => {
+ retryOnce(async () => {
let total = "";
for await (const chunk of llm.streamFim(
"Hi",
@@ -108,7 +122,7 @@ function testLLM(
expect(total.length).toBeGreaterThan(0);
return;
- },
+ }),
timeout,
);
}
@@ -116,7 +130,7 @@ function testLLM(
if (testToolCall) {
test(
"Tool Call works",
- async () => {
+ retryOnce(async () => {
let args = "";
let isFirstChunk = true;
for await (const chunk of llm.streamChat(
@@ -175,7 +189,7 @@ function testLLM(
const parsedArgs = JSON.parse(args);
expect(parsedArgs.name).toBe("Nate");
- },
+ }),
timeout,
);
}
@@ -230,6 +244,7 @@ describe("LLM", () => {
testFim: true,
skip: false,
testToolCall: true,
+ timeout: 60000,
},
);
testLLM(
diff --git a/core/llm/llms/Anthropic.ts b/core/llm/llms/Anthropic.ts
index 5bec42d49..b5906590a 100644
--- a/core/llm/llms/Anthropic.ts
+++ b/core/llm/llms/Anthropic.ts
@@ -1,7 +1,7 @@
+import { streamSse } from "@continuedev/fetch";
import { ChatMessage, CompletionOptions, LLMOptions } from "../../index.js";
import { renderChatMessage, stripImages } from "../../util/messageContent.js";
import { BaseLLM } from "../index.js";
-import { streamSse } from "../stream.js";
class Anthropic extends BaseLLM {
static providerName = "anthropic";
@@ -213,6 +213,10 @@ class Anthropic extends BaseLLM {
signal,
});
+ if (response.status === 499) {
+ return; // Aborted by user
+ }
+
if (!response.ok) {
const json = await response.json();
if (json.type === "error") {
diff --git a/core/llm/llms/Asksage.ts b/core/llm/llms/Asksage.ts
index 59554efe5..988c57ac6 100644
--- a/core/llm/llms/Asksage.ts
+++ b/core/llm/llms/Asksage.ts
@@ -134,10 +134,8 @@ class Asksage extends BaseLLM {
body: JSON.stringify(args),
});
- if (!response.ok) {
- throw new Error(
- `API request failed with status ${response.status}: ${response.statusText}`,
- );
+ if (response.status === 499) {
+ return ""; // Aborted by user
}
const data = await response.json();
@@ -167,10 +165,8 @@ class Asksage extends BaseLLM {
signal,
});
- if (!response.ok) {
- throw new Error(
- `API request failed with status ${response.status}: ${response.statusText}`,
- );
+ if (response.status === 499) {
+ return; // Aborted by user
}
const data = await response.json();
diff --git a/core/llm/llms/Bedrock.ts b/core/llm/llms/Bedrock.ts
index 430e4a93b..3b44e1f61 100644
--- a/core/llm/llms/Bedrock.ts
+++ b/core/llm/llms/Bedrock.ts
@@ -5,6 +5,7 @@ import {
ConverseStreamCommandOutput,
InvokeModelCommand,
Message,
+ ToolConfiguration,
} from "@aws-sdk/client-bedrock-runtime";
import { fromNodeProviderChain } from "@aws-sdk/credential-providers";
@@ -291,9 +292,10 @@ class Bedrock extends BaseLLM {
const convertedMessages = this._convertMessages(messages);
const shouldCacheSystemMessage =
- !!systemMessage && this.cacheBehavior?.cacheSystemMessage;
+ !!systemMessage && this.cacheBehavior?.cacheSystemMessage || this.completionOptions.promptCaching;
const enablePromptCaching =
- shouldCacheSystemMessage || this.cacheBehavior?.cacheConversation;
+ shouldCacheSystemMessage || this.cacheBehavior?.cacheConversation || this.completionOptions.promptCaching;
+ const shouldCacheToolsConfig = this.completionOptions.promptCaching;
// Add header for prompt caching
if (enablePromptCaching) {
@@ -304,29 +306,35 @@ class Bedrock extends BaseLLM {
}
const supportsTools =
- PROVIDER_TOOL_SUPPORT.bedrock?.(options.model || "") ?? false;
+ (this.capabilities?.tools || PROVIDER_TOOL_SUPPORT.bedrock?.(options.model)) ?? false;
+
+ let toolConfig = supportsTools && options.tools
+ ? {
+ tools: options.tools.map((tool) => ({
+ toolSpec: {
+ name: tool.function.name,
+ description: tool.function.description,
+ inputSchema: {
+ json: tool.function.parameters,
+ },
+ },
+ })),
+ } as ToolConfiguration
+ : undefined;
+
+ if (toolConfig?.tools && shouldCacheToolsConfig) {
+ toolConfig.tools.push({ cachePoint: { type: "default" } });
+ }
+
return {
modelId: options.model,
- messages: convertedMessages,
system: systemMessage
? shouldCacheSystemMessage
? [{ text: systemMessage }, { cachePoint: { type: "default" } }]
: [{ text: systemMessage }]
: undefined,
- toolConfig:
- supportsTools && options.tools
- ? {
- tools: options.tools.map((tool) => ({
- toolSpec: {
- name: tool.function.name,
- description: tool.function.description,
- inputSchema: {
- json: tool.function.parameters,
- },
- },
- })),
- }
- : undefined,
+ toolConfig: toolConfig,
+ messages: convertedMessages,
inferenceConfig: {
maxTokens: options.maxTokens,
temperature: options.temperature,
diff --git a/core/llm/llms/Cloudflare.ts b/core/llm/llms/Cloudflare.ts
index 8d18c4e3a..cba4204ef 100644
--- a/core/llm/llms/Cloudflare.ts
+++ b/core/llm/llms/Cloudflare.ts
@@ -1,7 +1,7 @@
+import { streamSse } from "@continuedev/fetch";
import { ChatMessage, CompletionOptions } from "../../index.js";
import { renderChatMessage } from "../../util/messageContent.js";
import { BaseLLM } from "../index.js";
-import { streamSse } from "../stream.js";
export default class Cloudflare extends BaseLLM {
static providerName = "cloudflare";
diff --git a/core/llm/llms/Cohere.ts b/core/llm/llms/Cohere.ts
index ecc9c5208..b4d2c3b41 100644
--- a/core/llm/llms/Cohere.ts
+++ b/core/llm/llms/Cohere.ts
@@ -1,3 +1,4 @@
+import { streamJSON } from "@continuedev/fetch";
import {
ChatMessage,
Chunk,
@@ -6,7 +7,6 @@ import {
} from "../../index.js";
import { renderChatMessage, stripImages } from "../../util/messageContent.js";
import { BaseLLM } from "../index.js";
-import { streamJSON } from "../stream.js";
class Cohere extends BaseLLM {
static providerName = "cohere";
@@ -84,6 +84,10 @@ class Cohere extends BaseLLM {
signal,
});
+ if (resp.status === 499) {
+ return; // Aborted by user
+ }
+
if (options.stream === false) {
const data = await resp.json();
yield { role: "assistant", content: data.text };
diff --git a/core/llm/llms/Deepseek.ts b/core/llm/llms/Deepseek.ts
index c1453d0db..305d177e7 100644
--- a/core/llm/llms/Deepseek.ts
+++ b/core/llm/llms/Deepseek.ts
@@ -1,5 +1,5 @@
+import { streamSse } from "@continuedev/fetch";
import { CompletionOptions, LLMOptions } from "../../index.js";
-import { streamSse } from "../stream.js";
import { osModelsEditPrompt } from "../templates/edit.js";
import OpenAI from "./OpenAI.js";
diff --git a/core/llm/llms/Flowise.ts b/core/llm/llms/Flowise.ts
index cdc4f8f77..57bb18ccc 100644
--- a/core/llm/llms/Flowise.ts
+++ b/core/llm/llms/Flowise.ts
@@ -132,12 +132,16 @@ class Flowise extends BaseLLM {
): AsyncGenerator {
const requestBody = this._getRequestBody(messages, options);
const { socket, socketInfo } = await this._initializeSocket();
- const request = this.fetch(this._getChatUrl(), {
+ const response = await this.fetch(this._getChatUrl(), {
method: "POST",
headers: this._getHeaders(),
body: JSON.stringify({ ...requestBody, socketIOClientId: socket.id }),
signal,
- }).then((res) => res.json());
+ });
+
+ if (response.status === 499) {
+ return; // Aborted by user
+ }
while (await socketInfo.hasNextToken()) {
yield { role: "assistant", content: socketInfo.getCurrentMessage() };
@@ -145,7 +149,7 @@ class Flowise extends BaseLLM {
if (socketInfo.error) {
socket.disconnect();
try {
- yield { role: "assistant", content: (await request).text };
+ yield { role: "assistant", content: await response.text() };
} catch (error: any) {
yield { role: "assistant", content: (error as Error).message ?? error };
}
diff --git a/core/llm/llms/FreeTrial.ts b/core/llm/llms/FreeTrial.ts
index ab69aff70..6ca040db0 100644
--- a/core/llm/llms/FreeTrial.ts
+++ b/core/llm/llms/FreeTrial.ts
@@ -1,3 +1,4 @@
+import { streamResponse } from "@continuedev/fetch";
import { TRIAL_FIM_MODEL } from "../../config/onboarding.js";
import { getHeaders } from "../../continueServer/stubs/headers.js";
import { TRIAL_PROXY_URL } from "../../control-plane/client.js";
@@ -8,7 +9,6 @@ import {
LLMOptions,
} from "../../index.js";
import { BaseLLM } from "../index.js";
-import { streamResponse } from "../stream.js";
class FreeTrial extends BaseLLM {
static providerName = "free-trial";
diff --git a/core/llm/llms/Gemini.ts b/core/llm/llms/Gemini.ts
index 1e3c35449..044ee6b71 100644
--- a/core/llm/llms/Gemini.ts
+++ b/core/llm/llms/Gemini.ts
@@ -1,3 +1,4 @@
+import { streamResponse } from "@continuedev/fetch";
import { v4 as uuidv4 } from "uuid";
import {
AssistantChatMessage,
@@ -10,7 +11,6 @@ import {
} from "../../index.js";
import { renderChatMessage, stripImages } from "../../util/messageContent.js";
import { BaseLLM } from "../index.js";
-import { streamResponse } from "../stream.js";
import {
GeminiChatContent,
GeminiChatContentPart,
@@ -438,6 +438,9 @@ class Gemini extends BaseLLM {
body: JSON.stringify(body),
signal,
});
+ if (response.status === 499) {
+ return; // Aborted by user
+ }
const data = await response.json();
yield { role: "assistant", content: data.candidates[0].content };
}
diff --git a/core/llm/llms/HuggingFaceInferenceAPI.ts b/core/llm/llms/HuggingFaceInferenceAPI.ts
index 40e67b3e5..208f6fd49 100644
--- a/core/llm/llms/HuggingFaceInferenceAPI.ts
+++ b/core/llm/llms/HuggingFaceInferenceAPI.ts
@@ -1,6 +1,6 @@
+import { streamSse } from "@continuedev/fetch";
import { CompletionOptions } from "../../index.js";
import { BaseLLM } from "../index.js";
-import { streamSse } from "../stream.js";
class HuggingFaceInferenceAPI extends BaseLLM {
static providerName = "huggingface-inference-api";
diff --git a/core/llm/llms/HuggingFaceTGI.ts b/core/llm/llms/HuggingFaceTGI.ts
index c9812cca3..8a86634c8 100644
--- a/core/llm/llms/HuggingFaceTGI.ts
+++ b/core/llm/llms/HuggingFaceTGI.ts
@@ -1,6 +1,6 @@
+import { streamSse } from "@continuedev/fetch";
import { CompletionOptions, LLMOptions } from "../../index.js";
import { BaseLLM } from "../index.js";
-import { streamSse } from "../stream.js";
class HuggingFaceTGI extends BaseLLM {
private static MAX_STOP_TOKENS = 4;
diff --git a/core/llm/llms/Inception.ts b/core/llm/llms/Inception.ts
index 2d75ca86b..385dea23c 100644
--- a/core/llm/llms/Inception.ts
+++ b/core/llm/llms/Inception.ts
@@ -1,5 +1,5 @@
+import { streamSse } from "@continuedev/fetch";
import { CompletionOptions, LLMOptions } from "../../index.js";
-import { streamSse } from "../stream.js";
import OpenAI from "./OpenAI.js";
diff --git a/core/llm/llms/LlamaCpp.ts b/core/llm/llms/LlamaCpp.ts
index 4833405ae..76fbfdd76 100644
--- a/core/llm/llms/LlamaCpp.ts
+++ b/core/llm/llms/LlamaCpp.ts
@@ -1,6 +1,6 @@
+import { streamSse } from "@continuedev/fetch";
import { CompletionOptions, LLMOptions } from "../../index.js";
import { BaseLLM } from "../index.js";
-import { streamSse } from "../stream.js";
class LlamaCpp extends BaseLLM {
static providerName = "llama.cpp";
@@ -35,7 +35,7 @@ class LlamaCpp extends BaseLLM {
...this.requestOptions?.headers,
};
- const resp = await this.fetch(new URL("completions", this.apiBase), {
+ const resp = await this.fetch(new URL("completion", this.apiBase), {
method: "POST",
headers,
body: JSON.stringify({
diff --git a/core/llm/llms/Moonshot.ts b/core/llm/llms/Moonshot.ts
index 732ce81cd..2235b5ac2 100644
--- a/core/llm/llms/Moonshot.ts
+++ b/core/llm/llms/Moonshot.ts
@@ -1,5 +1,5 @@
+import { streamSse } from "@continuedev/fetch";
import { CompletionOptions, LLMOptions } from "../../index.js";
-import { streamSse } from "../stream.js";
import { osModelsEditPrompt } from "../templates/edit.js";
import OpenAI from "./OpenAI.js";
diff --git a/core/llm/llms/Ollama.ts b/core/llm/llms/Ollama.ts
index 427d2492e..16d0e9542 100644
--- a/core/llm/llms/Ollama.ts
+++ b/core/llm/llms/Ollama.ts
@@ -1,6 +1,8 @@
import { Mutex } from "async-mutex";
import { JSONSchema7, JSONSchema7Object } from "json-schema";
+import { v4 as uuidv4 } from "uuid";
+import { streamResponse } from "@continuedev/fetch";
import {
ChatMessage,
ChatMessageRole,
@@ -11,7 +13,6 @@ import {
import { renderChatMessage } from "../../util/messageContent.js";
import { getRemoteModelInfo } from "../../util/ollamaHelper.js";
import { BaseLLM } from "../index.js";
-import { streamResponse } from "../stream.js";
type OllamaChatMessage = {
role: ChatMessageRole;
@@ -43,7 +44,7 @@ interface OllamaModelFileParams {
min_p?: number;
num_gpu?: number;
- // deprecated or not directly supported here:
+ // Deprecated or not directly supported here:
num_thread?: number;
use_mmap?: boolean;
num_gqa?: number;
@@ -90,10 +91,10 @@ type OllamaBaseResponse = {
model: string;
created_at: string;
} & (
- | {
+ | {
done: false;
}
- | {
+ | {
done: true;
done_reason: string;
total_duration: number; // Time spent generating the response in nanoseconds
@@ -104,7 +105,7 @@ type OllamaBaseResponse = {
eval_duration: number; // Time spent generating the response in nanoseconds
context: number[]; // An encoding of the conversation used in this response; can be sent in the next request to keep conversational memory
}
- );
+);
type OllamaErrorResponse = {
error: string;
@@ -113,14 +114,14 @@ type OllamaErrorResponse = {
type OllamaRawResponse =
| OllamaErrorResponse
| (OllamaBaseResponse & {
- response: string; // the generated response
- });
+ response: string; // the generated response
+ });
type OllamaChatResponse =
| OllamaErrorResponse
| (OllamaBaseResponse & {
- message: OllamaChatMessage;
- });
+ message: OllamaChatMessage;
+ });
interface OllamaTool {
type: "function";
@@ -370,7 +371,7 @@ class Ollama extends BaseLLM implements ModelInstaller {
if ("error" in j) {
throw new Error(j.error);
}
- j.response ??= ''
+ j.response ??= "";
yield j.response;
} catch (e) {
throw new Error(`Error parsing Ollama response: ${e} ${chunk}`);
@@ -439,6 +440,7 @@ class Ollama extends BaseLLM implements ModelInstaller {
// But ollama returns the full object in one response with no streaming
chatMessage.toolCalls = res.message.tool_calls.map((tc) => ({
type: "function",
+ id: `tc_${uuidv4()}`, // Generate a proper UUID with a prefix
function: {
name: tc.function.name,
arguments: JSON.stringify(tc.function.arguments),
@@ -455,6 +457,9 @@ class Ollama extends BaseLLM implements ModelInstaller {
}
if (chatOptions.stream === false) {
+ if (response.status === 499) {
+ return; // Aborted by user
+ }
const json = (await response.json()) as OllamaChatResponse;
yield convertChatMessage(json);
} else {
diff --git a/core/llm/llms/OpenAI.test.ts b/core/llm/llms/OpenAI.test.ts
new file mode 100644
index 000000000..46c8b4e23
--- /dev/null
+++ b/core/llm/llms/OpenAI.test.ts
@@ -0,0 +1,34 @@
+import OpenAI from "./OpenAI";
+
+describe("OpenAI", () => {
+ test("should identify correct o-series models", () => {
+ const openai = new OpenAI({
+ model: "o3-mini",
+ });
+ expect(openai.isOSeriesModel("o4-mini")).toBeTruthy();
+ expect(openai.isOSeriesModel("o3-mini")).toBeTruthy();
+ expect(openai.isOSeriesModel("o1-mini")).toBeTruthy();
+ expect(openai.isOSeriesModel("o1")).toBeTruthy();
+ expect(openai.isOSeriesModel("o3")).toBeTruthy();
+
+ // artificially correct samples for future models
+ expect(openai.isOSeriesModel("o5-mini")).toBeTruthy();
+ expect(openai.isOSeriesModel("o6")).toBeTruthy();
+ expect(openai.isOSeriesModel("o77")).toBeTruthy();
+ expect(openai.isOSeriesModel("o54-mini")).toBeTruthy();
+ });
+ test("should identify incorrect o-series models", () => {
+ const openai = new OpenAI({
+ model: "o3-mini",
+ });
+ expect(openai.isOSeriesModel("gpt-o4-mini")).toBeFalsy();
+ expect(openai.isOSeriesModel("gpt-4.5")).toBeFalsy();
+ expect(openai.isOSeriesModel("gpt-4.1")).toBeFalsy();
+
+ // artificially wrong samples
+ expect(openai.isOSeriesModel("os1")).toBeFalsy();
+ expect(openai.isOSeriesModel("so1")).toBeFalsy();
+ expect(openai.isOSeriesModel("ao31")).toBeFalsy();
+ expect(openai.isOSeriesModel("1os")).toBeFalsy();
+ });
+});
diff --git a/core/llm/llms/OpenAI.ts b/core/llm/llms/OpenAI.ts
index f6dbc2bf3..c48349f83 100644
--- a/core/llm/llms/OpenAI.ts
+++ b/core/llm/llms/OpenAI.ts
@@ -3,6 +3,7 @@ import {
ChatCompletionMessageParam,
} from "openai/resources/index";
+import { streamSse } from "@continuedev/fetch";
import {
ChatMessage,
CompletionOptions,
@@ -16,7 +17,6 @@ import {
LlmApiRequestType,
toChatBody,
} from "../openaiTypeConverters.js";
-import { streamSse } from "../stream.js";
const NON_CHAT_MODELS = [
"text-davinci-002",
@@ -77,8 +77,8 @@ class OpenAI extends BaseLLM {
return model;
}
- private isO3orO1Model(model?: string): boolean {
- return !!model && (model.startsWith("o1") || model.startsWith("o3"));
+ public isOSeriesModel(model?: string): boolean {
+ return !!model && !!model.match(/^o[0-9]+/);
}
private isFireworksAiModel(model?: string): boolean {
@@ -139,7 +139,7 @@ class OpenAI extends BaseLLM {
finalOptions.stop = options.stop?.slice(0, this.getMaxStopWords());
// OpenAI o1-preview and o1-mini or o3-mini:
- if (this.isO3orO1Model(options.model)) {
+ if (this.isOSeriesModel(options.model)) {
// a) use max_completion_tokens instead of max_tokens
finalOptions.max_completion_tokens = options.maxTokens;
finalOptions.max_tokens = undefined;
@@ -241,7 +241,7 @@ class OpenAI extends BaseLLM {
body.stop = body.stop?.slice(0, this.getMaxStopWords());
// OpenAI o1-preview and o1-mini or o3-mini:
- if (this.isO3orO1Model(body.model)) {
+ if (this.isOSeriesModel(body.model)) {
// a) use max_completion_tokens instead of max_tokens
body.max_completion_tokens = body.max_tokens;
body.max_tokens = undefined;
@@ -352,6 +352,9 @@ class OpenAI extends BaseLLM {
// Handle non-streaming response
if (body.stream === false) {
+ if (response.status === 499) {
+ return; // Aborted by user
+ }
const data = await response.json();
yield data.choices[0].message;
return;
diff --git a/core/llm/llms/SiliconFlow.ts b/core/llm/llms/SiliconFlow.ts
index cddb22b0d..d0d3e901d 100644
--- a/core/llm/llms/SiliconFlow.ts
+++ b/core/llm/llms/SiliconFlow.ts
@@ -1,5 +1,5 @@
+import { streamSse } from "@continuedev/fetch";
import { Chunk, CompletionOptions, LLMOptions } from "../../index.js";
-import { streamSse } from "../stream.js";
import { osModelsEditPrompt } from "../templates/edit.js";
import OpenAI from "./OpenAI.js";
@@ -58,7 +58,7 @@ class SiliconFlow extends OpenAI {
console.warn("[SiliconFlow] rerank: query is empty");
return [];
}
-
+
if (!chunks || chunks.length === 0) {
console.warn("[SiliconFlow] rerank: chunks is empty");
return [];
diff --git a/core/llm/llms/VertexAI.ts b/core/llm/llms/VertexAI.ts
index cc1b70b19..1a956cf76 100644
--- a/core/llm/llms/VertexAI.ts
+++ b/core/llm/llms/VertexAI.ts
@@ -1,9 +1,9 @@
import { GoogleAuth } from "google-auth-library";
+import { streamResponse, streamSse } from "@continuedev/fetch";
import { ChatMessage, CompletionOptions, LLMOptions } from "../../index.js";
import { renderChatMessage, stripImages } from "../../util/messageContent.js";
import { BaseLLM } from "../index.js";
-import { streamResponse, streamSse } from "../stream.js";
import Anthropic from "./Anthropic.js";
import Gemini from "./Gemini.js";
@@ -95,6 +95,7 @@ class VertexAI extends BaseLLM {
protected async *StreamChatAnthropic(
messages: ChatMessage[],
options: CompletionOptions,
+ signal: AbortSignal,
): AsyncGenerator {
const systemMessage = stripImages(
messages.filter((m) => m.role === "system")[0]?.content ?? "",
@@ -128,8 +129,13 @@ class VertexAI extends BaseLLM {
]
: systemMessage,
}),
+ signal,
});
+ if (response.status === 499) {
+ return; // Aborted by user
+ }
+
if (options.stream === false) {
const data = await response.json();
yield { role: "assistant", content: data.content[0].text };
@@ -150,6 +156,7 @@ class VertexAI extends BaseLLM {
private async *streamChatGemini(
messages: ChatMessage[],
options: CompletionOptions,
+ signal: AbortSignal,
): AsyncGenerator {
const apiURL = new URL(
`publishers/google/models/${options.model}:streamGenerateContent`,
@@ -160,6 +167,7 @@ class VertexAI extends BaseLLM {
const response = await this.fetch(apiURL, {
method: "POST",
body: JSON.stringify(body),
+ signal,
});
for await (const message of this.geminiInstance.processGeminiResponse(
streamResponse(response),
@@ -171,6 +179,7 @@ class VertexAI extends BaseLLM {
private async *streamChatBison(
messages: ChatMessage[],
options: CompletionOptions,
+ signal: AbortSignal,
): AsyncGenerator {
const instances = messages.map((message) => ({ prompt: message.content }));
@@ -193,7 +202,11 @@ class VertexAI extends BaseLLM {
const response = await this.fetch(apiURL, {
method: "POST",
body: JSON.stringify(body),
+ signal,
});
+ if (response.status === 499) {
+ return; // Aborted by user
+ }
const data = await response.json();
yield { role: "assistant", content: data.predictions[0].content };
}
@@ -203,6 +216,7 @@ class VertexAI extends BaseLLM {
protected async *StreamChatMistral(
messages: ChatMessage[],
options: CompletionOptions,
+ signal: AbortSignal,
): AsyncGenerator {
const apiBase = this.apiBase!;
const apiURL = new URL(
@@ -228,6 +242,7 @@ class VertexAI extends BaseLLM {
const response = await this.fetch(apiURL, {
method: "POST",
body: JSON.stringify(body),
+ signal,
});
for await (const chunk of streamSse(response)) {
@@ -304,6 +319,9 @@ class VertexAI extends BaseLLM {
}),
signal,
});
+ if (resp.status === 499) {
+ return; // Aborted by user
+ }
// Streaming is not supported by code-gecko
// TODO: convert to non-streaming fim method when one exist in continue.
yield (await resp.json()).predictions[0].content;
@@ -323,14 +341,14 @@ class VertexAI extends BaseLLM {
? this.geminiInstance.removeSystemMessage(messages)
: messages;
if (this.vertexProvider === "gemini") {
- yield* this.streamChatGemini(convertedMsgs, options);
+ yield* this.streamChatGemini(convertedMsgs, options, signal);
} else if (this.vertexProvider === "mistral") {
- yield* this.StreamChatMistral(messages, options);
+ yield* this.StreamChatMistral(messages, options, signal);
} else if (this.vertexProvider === "anthropic") {
- yield* this.StreamChatAnthropic(messages, options);
+ yield* this.StreamChatAnthropic(messages, options, signal);
} else {
if (options.model.includes("bison")) {
- yield* this.streamChatBison(convertedMsgs, options);
+ yield* this.streamChatBison(convertedMsgs, options, signal);
} else {
throw new Error(`Unsupported model: ${options.model}`);
}
diff --git a/core/llm/llms/Vllm.ts b/core/llm/llms/Vllm.ts
index b237b4c7e..991b09c3e 100644
--- a/core/llm/llms/Vllm.ts
+++ b/core/llm/llms/Vllm.ts
@@ -12,6 +12,10 @@ class Vllm extends OpenAI {
}
}
+ supportsFim(): boolean {
+ return false;
+ }
+
private _setupCompletionOptions() {
this.fetch(this._getEndpoint("models"), {
method: "GET",
diff --git a/core/llm/llms/WatsonX.ts b/core/llm/llms/WatsonX.ts
index ac91d3fa9..0c700f439 100644
--- a/core/llm/llms/WatsonX.ts
+++ b/core/llm/llms/WatsonX.ts
@@ -1,12 +1,12 @@
+import { streamResponse, streamSse } from "@continuedev/fetch";
import {
ChatMessage,
Chunk,
CompletionOptions,
LLMOptions,
} from "../../index.js";
-import { renderChatMessage } from "../../util/messageContent.js";
import { BaseLLM } from "../index.js";
-import { streamResponse } from "../stream.js";
+import { fromChatCompletionChunk } from "../openaiTypeConverters.js";
let watsonxToken = {
expiration: 0,
@@ -82,10 +82,8 @@ class WatsonX extends BaseLLM {
}
}
- getWatsonxEndpoint(): string {
- return this.deploymentId
- ? `${this.apiBase}/ml/v1/deployments/${this.deploymentId}/text/generation_stream?version=${this.apiVersion}`
- : `${this.apiBase}/ml/v1/text/generation_stream?version=${this.apiVersion}`;
+ _getEndpoint(endpoint: string): string {
+ return `${this.apiBase}/ml/v1/${this.deploymentId ? `deployments/${this.deploymentId}/` : ""}text/${endpoint}_stream?version=${this.apiVersion}`;
}
static providerName = "watsonx";
@@ -117,14 +115,10 @@ class WatsonX extends BaseLLM {
};
}
- protected _convertModelName(model: string): string {
- return model;
- }
-
protected _convertArgs(options: any, messages: ChatMessage[]) {
const finalOptions = {
messages: messages.map(this._convertMessage).filter(Boolean),
- model: this._convertModelName(options.model),
+ model: options.model,
max_tokens: options.maxTokens,
temperature: options.temperature,
top_p: options.topP,
@@ -185,26 +179,10 @@ class WatsonX extends BaseLLM {
signal: AbortSignal,
options: CompletionOptions,
): AsyncGenerator {
- for await (const chunk of this._streamChat(
- [{ role: "user", content: prompt }],
- signal,
- options,
- )) {
- yield renderChatMessage(chunk);
- }
- }
-
- protected async *_streamChat(
- messages: ChatMessage[],
- signal: AbortSignal,
- options: CompletionOptions,
- ): AsyncGenerator {
await this.updateWatsonxToken();
- const stopSequences =
- options.stop?.slice(0, 6) ??
- (options.model?.includes("granite") ? ["Question:"] : []);
- const url = this.getWatsonxEndpoint();
+ const stopSequences = options.stop?.slice(0, 6) ?? [];
+ const url = this._getEndpoint("generation");
const headers = this._getHeaders();
const parameters: any = {
@@ -224,7 +202,7 @@ class WatsonX extends BaseLLM {
}
const payload: any = {
- input: messages[messages.length - 1].content,
+ input: prompt,
parameters: parameters,
};
if (!this.deploymentId) {
@@ -232,46 +210,91 @@ class WatsonX extends BaseLLM {
payload.project_id = this.projectId;
}
- var response = await this.fetch(url, {
+ const response = await this.fetch(url, {
method: "POST",
headers: headers,
body: JSON.stringify(payload),
signal,
});
- if (!response.ok || response.body === null) {
- throw new Error(
- "Something went wrong. No response received, check your connection",
- );
- } else {
- for await (const value of streamResponse(response)) {
- const lines = value.split("\n");
- let generatedChunk = "";
- let generatedTextIndex = undefined;
- lines.forEach((el: string) => {
- // console.log(`${el}`);
- if (el.startsWith("id:")) {
- generatedTextIndex = parseInt(el.replace(/^id:\s+/, ""));
- if (isNaN(generatedTextIndex)) {
- console.error(`Unable to parse stream chunk ID: ${el}`);
- }
- } else if (el.startsWith("data:")) {
- const dataStr = el.replace(/^data:\s+/, "");
- try {
- const data = JSON.parse(dataStr);
- data.results.forEach((result: any) => {
- generatedChunk += result.generated_text || "";
- });
- } catch (e) {
- // parsing error is expected with streaming response
- // console.error(`Error parsing JSON string: ${dataStr}`, e);
- }
+ for await (const value of streamResponse(response)) {
+ const lines = value.split("\n");
+ let generatedChunk = "";
+ let generatedTextIndex = undefined;
+ lines.forEach((el: string) => {
+ // console.log(`${el}`);
+ if (el.startsWith("id:")) {
+ generatedTextIndex = parseInt(el.replace(/^id:\s+/, ""));
+ if (isNaN(generatedTextIndex)) {
+ console.error(`Unable to parse stream chunk ID: ${el}`);
}
- });
- yield {
- role: "assistant",
- content: generatedChunk,
- };
+ } else if (el.startsWith("data:")) {
+ const dataStr = el.replace(/^data:\s+/, "");
+ try {
+ const data = JSON.parse(dataStr);
+ data.results.forEach((result: any) => {
+ generatedChunk += result.generated_text || "";
+ });
+ } catch (e) {
+ // parsing error is expected with streaming response
+ // console.error(`Error parsing JSON string: ${dataStr}`, e);
+ }
+ }
+ });
+ yield generatedChunk;
+ }
+ }
+
+ protected async *_streamChat(
+ messages: ChatMessage[],
+ signal: AbortSignal,
+ options: CompletionOptions,
+ ): AsyncGenerator {
+ await this.updateWatsonxToken();
+
+ const stopSequences = options.stop?.slice(0, 6) ?? [];
+ const url = this._getEndpoint("chat");
+ const headers = this._getHeaders();
+
+ const payload: any = {
+ messages: messages,
+ max_tokens: options.maxTokens ?? 1024,
+ stop: stopSequences,
+ frequency_penalty: options.frequencyPenalty || 1,
+ presence_penalty: options.presencePenalty || 1,
+ };
+
+ if (!this.deploymentId) {
+ payload.model_id = options.model;
+ payload.project_id = this.projectId;
+ }
+
+ if (!!options.temperature) {
+ payload.temperature = options.temperature;
+ }
+ if (!!options.topP) {
+ payload.top_p = options.topP;
+ }
+ if (!!options.tools) {
+ payload.tools = options.tools;
+ if (options.toolChoice) {
+ payload.tool_choice = options.toolChoice;
+ } else {
+ payload.tool_choice_option = "auto";
+ }
+ }
+
+ const response = await this.fetch(url, {
+ method: "POST",
+ headers: headers,
+ body: JSON.stringify(payload),
+ signal,
+ });
+
+ for await (const value of streamSse(response)) {
+ const chunk = fromChatCompletionChunk(value);
+ if (chunk) {
+ yield chunk;
}
}
}
diff --git a/core/llm/llms/stubs/ContinueProxy.ts b/core/llm/llms/stubs/ContinueProxy.ts
index e43e2bfe2..d512ec2ac 100644
--- a/core/llm/llms/stubs/ContinueProxy.ts
+++ b/core/llm/llms/stubs/ContinueProxy.ts
@@ -1,6 +1,7 @@
import {
ContinueProperties,
decodeSecretLocation,
+ parseProxyModelName,
SecretType,
} from "@continuedev/config-yaml";
@@ -27,8 +28,12 @@ class ContinueProxy extends OpenAI {
// to call whatever LLM API is chosen
private actualApiBase?: string;
+ // Contains extra properties that we pass along to the proxy. Originally from `env` property on LLMOptions
+ private configEnv?: Record;
+
constructor(options: LLMOptions) {
super(options);
+ this.configEnv = options.env;
this.actualApiBase = options.apiBase;
this.apiKeyLocation = options.apiKeyLocation;
this.orgScopeId = options.orgScopeId;
@@ -43,11 +48,17 @@ class ContinueProxy extends OpenAI {
useLegacyCompletionsEndpoint: false,
};
+ get underlyingProviderName(): string {
+ const { provider } = parseProxyModelName(this.model);
+ return provider;
+ }
+
protected extraBodyProperties(): Record {
const continueProperties: ContinueProperties = {
apiKeyLocation: this.apiKeyLocation,
apiBase: this.actualApiBase,
orgScopeId: this.orgScopeId ?? null,
+ env: this.configEnv,
};
return {
continueProperties,
@@ -78,6 +89,10 @@ class ContinueProxy extends OpenAI {
}
supportsFim(): boolean {
+ const { provider } = parseProxyModelName(this.model);
+ if (provider === "vllm") {
+ return false;
+ }
return true;
}
diff --git a/core/llm/llms/test/supportsFim.test.ts b/core/llm/llms/test/supportsFim.test.ts
new file mode 100644
index 000000000..6cb7525ae
--- /dev/null
+++ b/core/llm/llms/test/supportsFim.test.ts
@@ -0,0 +1,55 @@
+import { jest } from "@jest/globals";
+import Anthropic from "../Anthropic.js";
+import Deepseek from "../Deepseek.js";
+import FunctionNetwork from "../FunctionNetwork.js";
+import Mistral from "../Mistral.js";
+import OpenAI from "../OpenAI.js";
+import ContinueProxy from "../stubs/ContinueProxy.js";
+import Vllm from "../Vllm.js";
+
+// Mock the parseProxyModelName function
+const mockParseProxyModelName = jest.fn();
+jest.mock("@continuedev/config-yaml", () => ({
+ parseProxyModelName: mockParseProxyModelName,
+ decodeSecretLocation: jest.fn(),
+ SecretType: { NotFound: "not-found" },
+}));
+
+// Test cases: [LLM class, model, expected supportsFim result, description]
+const testCases: [any, string, boolean, string][] = [
+ [ContinueProxy, "owner/package/vllm/some-model", false, "vllm provider"],
+ [ContinueProxy, "owner/package/openai/gpt-4", true, "openai provider"],
+ [
+ ContinueProxy,
+ "owner/package/anthropic/claude-3",
+ true,
+ "anthropic provider",
+ ],
+ [ContinueProxy, "owner/package/cohere/command-r", true, "cohere provider"],
+ [
+ ContinueProxy,
+ "owner/package/unknown-provider/some-model",
+ true,
+ "unknown provider",
+ ],
+ [ContinueProxy, "owner/package/groq/llama-model", true, "groq provider"],
+ [Vllm, "any-model", false, "Vllm"],
+ [Anthropic, "claude-3-5-sonnet-latest", false, "Anthropic"],
+ [FunctionNetwork, "any-model", false, "FunctionNetwork"],
+ [OpenAI, "codestral", false, "OpenAI"],
+ [Mistral, "codestral", true, "Mistral"],
+ [Deepseek, "deepseek-chat", true, "Deepseek"],
+];
+
+testCases.forEach(([LLMClass, model, expectedResult, description]) => {
+ test(`supportsFim returns ${expectedResult} for ${description}`, () => {
+ const llm = new LLMClass({
+ model,
+ apiKey: "test-key",
+ });
+
+ const result = llm.supportsFim();
+
+ expect(result).toBe(expectedResult);
+ });
+});
diff --git a/core/llm/rules/getSystemMessageWithRules.test.ts b/core/llm/rules/getSystemMessageWithRules.test.ts
index c1a7765ee..39f18e976 100644
--- a/core/llm/rules/getSystemMessageWithRules.test.ts
+++ b/core/llm/rules/getSystemMessageWithRules.test.ts
@@ -1,5 +1,6 @@
-import { RuleWithSource, UserChatMessage } from "../..";
-import { getSystemMessageWithRules } from "./getSystemMessageWithRules";
+/* eslint-disable max-lines-per-function */
+import { ContextItemWithId, RuleWithSource, UserChatMessage } from "../..";
+import { getSystemMessageWithRules, shouldApplyRule } from "./getSystemMessageWithRules";
describe("getSystemMessageWithRules", () => {
const baseSystemMessage = "Base system message";
@@ -25,11 +26,48 @@ describe("getSystemMessageWithRules", () => {
source: "rules-block",
};
+ // JavaScript rule
+ const jsRule: RuleWithSource = {
+ name: "JavaScript Rule",
+ rule: "Follow JavaScript best practices",
+ globs: "**/*.js",
+ source: "rules-block",
+ };
+
+ // Empty context items
+ const emptyContextItems: ContextItemWithId[] = [];
+
+ // Context items with file paths
+ const tsContextItem: ContextItemWithId = {
+ content: "TypeScript file content",
+ name: "Component.tsx",
+ description: "A TypeScript component",
+ id: { providerTitle: "file", itemId: "src/Component.tsx" },
+ uri: { type: "file", value: "src/Component.tsx" },
+ };
+
+ const pyContextItem: ContextItemWithId = {
+ content: "Python file content",
+ name: "utils.py",
+ description: "A Python utility file",
+ id: { providerTitle: "file", itemId: "utils.py" },
+ uri: { type: "file", value: "utils.py" },
+ };
+
+ const jsContextItem: ContextItemWithId = {
+ content: "JavaScript file content",
+ name: "utils.js",
+ description: "A JavaScript utility file",
+ id: { providerTitle: "file", itemId: "src/utils.js" },
+ uri: { type: "file", value: "src/utils.js" },
+ };
+
it("should not include pattern-matched rules when no file paths are mentioned", () => {
const result = getSystemMessageWithRules({
baseSystemMessage,
userMessage: undefined,
rules: [tsRule],
+ contextItems: emptyContextItems,
});
expect(result).toBe(baseSystemMessage);
@@ -40,12 +78,13 @@ describe("getSystemMessageWithRules", () => {
baseSystemMessage,
userMessage: undefined,
rules: [generalRule],
+ contextItems: emptyContextItems,
});
expect(result).toBe(`${baseSystemMessage}\n\n${generalRule.rule}`);
});
- it("should include only matching rules based on file paths", () => {
+ it("should include only matching rules based on file paths in message", () => {
const userMessage: UserChatMessage = {
role: "user",
content:
@@ -56,6 +95,7 @@ describe("getSystemMessageWithRules", () => {
baseSystemMessage,
userMessage,
rules: [tsRule, pythonRule, generalRule],
+ contextItems: emptyContextItems,
});
// Should include TS rule and general rule, but not Python rule
@@ -63,7 +103,38 @@ describe("getSystemMessageWithRules", () => {
expect(result).toBe(expected);
});
- it("should include multiple matching rules", () => {
+ it("should include matching rules based on file paths in context items", () => {
+ const result = getSystemMessageWithRules({
+ baseSystemMessage,
+ userMessage: undefined,
+ rules: [tsRule, pythonRule, generalRule],
+ contextItems: [tsContextItem],
+ });
+
+ // Should include TS rule and general rule, but not Python rule
+ const expected = `${baseSystemMessage}\n\n${tsRule.rule}\n\n${generalRule.rule}`;
+ expect(result).toBe(expected);
+ });
+
+ it("should include matching rules from both message and context items", () => {
+ const userMessage: UserChatMessage = {
+ role: "user",
+ content: "```python test.py\nprint('hello')\n```",
+ };
+
+ const result = getSystemMessageWithRules({
+ baseSystemMessage,
+ userMessage,
+ rules: [tsRule, pythonRule, generalRule],
+ contextItems: [tsContextItem],
+ });
+
+ // Should include TS rule, Python rule, and general rule
+ const expected = `${baseSystemMessage}\n\n${tsRule.rule}\n\n${pythonRule.rule}\n\n${generalRule.rule}`;
+ expect(result).toBe(expected);
+ });
+
+ it("should include multiple matching rules from message", () => {
const userMessage: UserChatMessage = {
role: "user",
content:
@@ -74,6 +145,20 @@ describe("getSystemMessageWithRules", () => {
baseSystemMessage,
userMessage,
rules: [tsRule, pythonRule, generalRule],
+ contextItems: emptyContextItems,
+ });
+
+ // Should include all rules
+ const expected = `${baseSystemMessage}\n\n${tsRule.rule}\n\n${pythonRule.rule}\n\n${generalRule.rule}`;
+ expect(result).toBe(expected);
+ });
+
+ it("should include multiple matching rules from context items", () => {
+ const result = getSystemMessageWithRules({
+ baseSystemMessage,
+ userMessage: undefined,
+ rules: [tsRule, pythonRule, generalRule],
+ contextItems: [tsContextItem, pyContextItem],
});
// Should include all rules
@@ -91,6 +176,7 @@ describe("getSystemMessageWithRules", () => {
baseSystemMessage,
userMessage,
rules: [tsRule, pythonRule, generalRule],
+ contextItems: emptyContextItems,
});
// Should only include the general rule
@@ -117,6 +203,7 @@ describe("getSystemMessageWithRules", () => {
baseSystemMessage,
userMessage,
rules: [commaRule],
+ contextItems: emptyContextItems,
});
// With the current implementation, the comma-separated pattern is treated as a single string,
@@ -143,6 +230,7 @@ describe("getSystemMessageWithRules", () => {
baseSystemMessage,
userMessage,
rules: [arrayGlobRule],
+ contextItems: emptyContextItems,
});
// With our new implementation, the array of patterns should match both src/main.ts and tests/example.test.ts
@@ -168,6 +256,7 @@ describe("getSystemMessageWithRules", () => {
baseSystemMessage,
userMessage,
rules: [arrayGlobRule],
+ contextItems: emptyContextItems,
});
// Should match src/main.ts but not config/settings.ts
@@ -193,9 +282,523 @@ describe("getSystemMessageWithRules", () => {
baseSystemMessage,
userMessage,
rules: [arrayGlobRule],
+ contextItems: emptyContextItems,
});
// Should not match any file paths
expect(result).toBe(baseSystemMessage);
});
+
+ // New test for code block with filename only (no language)
+ it("should handle code blocks with filename only (no language identifier)", () => {
+ const userMessage: UserChatMessage = {
+ role: "user",
+ content: "```test.js\nclass Calculator { /* code */ }\n```",
+ };
+
+ const result = getSystemMessageWithRules({
+ baseSystemMessage,
+ userMessage,
+ rules: [jsRule, tsRule, generalRule],
+ contextItems: emptyContextItems,
+ });
+
+ // Should include JS rule and general rule
+ const expected = `${baseSystemMessage}\n\n${jsRule.rule}\n\n${generalRule.rule}`;
+ expect(result).toBe(expected);
+ });
+
+ // New test for code blocks with line ranges
+ it("should handle code blocks with line ranges", () => {
+ const userMessage: UserChatMessage = {
+ role: "user",
+ content: "```js test.js (19-25)\ndivide(number) { /* code */ }\n```",
+ };
+
+ const result = getSystemMessageWithRules({
+ baseSystemMessage,
+ userMessage,
+ rules: [jsRule, tsRule, generalRule],
+ contextItems: emptyContextItems,
+ });
+
+ // Should include JS rule and general rule
+ const expected = `${baseSystemMessage}\n\n${jsRule.rule}\n\n${generalRule.rule}`;
+ expect(result).toBe(expected);
+ });
+
+ // New test for mixed code block formats
+ it("should handle mixed code block formats in the same message", () => {
+ const userMessage: UserChatMessage = {
+ role: "user",
+ content:
+ "```test.js\nclass Calculator { /* code */ }\n```\n" +
+ "```js utils.js (19-25)\ndivide(number) { /* code */ }\n```\n" +
+ "```ts config/settings.ts\nconst config = {};\n```",
+ };
+
+ const result = getSystemMessageWithRules({
+ baseSystemMessage,
+ userMessage,
+ rules: [jsRule, tsRule, generalRule],
+ contextItems: emptyContextItems,
+ });
+
+ // Should include JS rule, TS rule, and general rule
+ const expected = `${baseSystemMessage}\n\n${jsRule.rule}\n\n${tsRule.rule}\n\n${generalRule.rule}`;
+ expect(result).toBe(expected);
+ });
+
+ // Test for context items when there's no message
+ it("should apply rules based on context items only when no message is present", () => {
+ const result = getSystemMessageWithRules({
+ baseSystemMessage,
+ userMessage: undefined,
+ rules: [jsRule, tsRule, generalRule],
+ contextItems: [jsContextItem],
+ });
+
+ // Should include JS rule and general rule
+ const expected = `${baseSystemMessage}\n\n${jsRule.rule}\n\n${generalRule.rule}`;
+ expect(result).toBe(expected);
+ });
+
+ // Test for non-file context items
+ it("should ignore non-file context items", () => {
+ const nonFileContextItem: ContextItemWithId = {
+ content: "Some search result",
+ name: "Search result",
+ description: "A search result",
+ id: { providerTitle: "search", itemId: "search-result" },
+ // No uri with type "file"
+ };
+
+ const result = getSystemMessageWithRules({
+ baseSystemMessage,
+ userMessage: undefined,
+ rules: [jsRule, tsRule, generalRule],
+ contextItems: [nonFileContextItem],
+ });
+
+ // Should only include general rule
+ const expected = `${baseSystemMessage}\n\n${generalRule.rule}`;
+ expect(result).toBe(expected);
+ });
+
+ // Test combining context items with message
+ it("should match rules from both message code blocks and context items", () => {
+ const userMessage: UserChatMessage = {
+ role: "user",
+ content: "```ts src/main.ts\nconsole.log('hello');\n```",
+ };
+
+ const result = getSystemMessageWithRules({
+ baseSystemMessage,
+ userMessage,
+ rules: [jsRule, tsRule, pythonRule, generalRule],
+ contextItems: [jsContextItem, pyContextItem],
+ });
+
+ // Should include JS, TS, Python rules and general rule
+ const expected = `${baseSystemMessage}\n\n${jsRule.rule}\n\n${tsRule.rule}\n\n${pythonRule.rule}\n\n${generalRule.rule}`;
+ expect(result).toBe(expected);
+ });
+
+ // Tests for alwaysApply property
+ describe("alwaysApply property", () => {
+ const alwaysApplyTrueRule: RuleWithSource = {
+ name: "Always Apply True Rule",
+ rule: "This rule should always be applied",
+ globs: "**/*.nonexistent",
+ alwaysApply: true,
+ source: "rules-block",
+ };
+
+ const alwaysApplyFalseRule: RuleWithSource = {
+ name: "Always Apply False Rule",
+ rule: "This rule should never be applied",
+ alwaysApply: false,
+ source: "rules-block",
+ };
+
+ const alwaysApplyFalseWithMatchingGlobs: RuleWithSource = {
+ name: "Always Apply False with Matching Globs",
+ rule: "This rule should never be applied even with matching globs",
+ globs: "**/*.ts?(x)",
+ alwaysApply: false,
+ source: "rules-block",
+ };
+
+ it("should always include rules with alwaysApply: true regardless of globs or file paths", () => {
+ const userMessage: UserChatMessage = {
+ role: "user",
+ content: "```js main.js\nconsole.log('hello');\n```",
+ };
+
+ const result = getSystemMessageWithRules({
+ baseSystemMessage,
+ userMessage,
+ rules: [alwaysApplyTrueRule, tsRule],
+ contextItems: emptyContextItems,
+ });
+
+ // Should include the alwaysApply:true rule even though globs don't match
+ const expected = `${baseSystemMessage}\n\n${alwaysApplyTrueRule.rule}`;
+ expect(result).toBe(expected);
+ });
+
+ it("should include rules with alwaysApply: false when globs match", () => {
+ const userMessage: UserChatMessage = {
+ role: "user",
+ content: "```tsx Component.tsx\nexport const Component = () =>
Hello
;\n```",
+ };
+
+ const result = getSystemMessageWithRules({
+ baseSystemMessage,
+ userMessage,
+ rules: [alwaysApplyFalseWithMatchingGlobs, tsRule, generalRule],
+ contextItems: emptyContextItems,
+ });
+
+ // Should include alwaysApply:false rule because globs match
+ const expected = `${baseSystemMessage}\n\n${alwaysApplyFalseWithMatchingGlobs.rule}\n\n${tsRule.rule}\n\n${generalRule.rule}`;
+ expect(result).toBe(expected);
+ });
+
+ it("should include rules with alwaysApply: false when globs match", () => {
+ const userMessage: UserChatMessage = {
+ role: "user",
+ content:
+ "```ts Component.tsx\nexport const Component = () =>
Hello
;\n```",
+ };
+
+ const result = getSystemMessageWithRules({
+ baseSystemMessage,
+ userMessage,
+ rules: [alwaysApplyFalseWithMatchingGlobs, tsRule, generalRule],
+ contextItems: emptyContextItems,
+ });
+
+ // Should include alwaysApply:false rule because globs match
+ const expected = `${baseSystemMessage}\n\n${alwaysApplyFalseWithMatchingGlobs.rule}\n\n${tsRule.rule}\n\n${generalRule.rule}`;
+ expect(result).toBe(expected);
+ });
+
+ it("should NOT include rules with alwaysApply: false when globs don't match", () => {
+ const userMessage: UserChatMessage = {
+ role: "user",
+ content: "```py script.py\nprint('hello')\n```",
+ };
+
+ const result = getSystemMessageWithRules({
+ baseSystemMessage,
+ userMessage,
+ rules: [alwaysApplyFalseWithMatchingGlobs, generalRule],
+ contextItems: emptyContextItems,
+ });
+
+ // Should only include general rule (alwaysApply:false rule doesn't match .py files)
+ const expected = `${baseSystemMessage}\n\n${generalRule.rule}`;
+ expect(result).toBe(expected);
+ });
+
+ it("should NOT include rules with alwaysApply: false when no globs are specified", () => {
+ const userMessage: UserChatMessage = {
+ role: "user",
+ content: "```js main.js\nconsole.log('hello');\n```",
+ };
+
+ const alwaysApplyFalseNoGlobs: RuleWithSource = {
+ name: "Always Apply False No Globs",
+ rule: "This rule has alwaysApply false and no globs",
+ alwaysApply: false,
+ source: "rules-block",
+ };
+
+ const result = getSystemMessageWithRules({
+ baseSystemMessage,
+ userMessage,
+ rules: [alwaysApplyFalseNoGlobs, jsRule, generalRule],
+ contextItems: emptyContextItems,
+ });
+
+ // Should NOT include alwaysApply:false rule when no globs specified
+ const expected = `${baseSystemMessage}\n\n${jsRule.rule}\n\n${generalRule.rule}`;
+ expect(result).toBe(expected);
+ });
+
+ it("should include rules with alwaysApply: true even when no files are present", () => {
+ const result = getSystemMessageWithRules({
+ baseSystemMessage,
+ userMessage: undefined,
+ rules: [alwaysApplyTrueRule, tsRule, pythonRule],
+ contextItems: emptyContextItems,
+ });
+
+ // Should only include the alwaysApply:true rule
+ const expected = `${baseSystemMessage}\n\n${alwaysApplyTrueRule.rule}`;
+ expect(result).toBe(expected);
+ });
+
+ it("should handle mixed alwaysApply values correctly", () => {
+ const userMessage: UserChatMessage = {
+ role: "user",
+ content:
+ "```ts Component.tsx\nexport const Component = () =>
Hello
;\n```",
+ };
+
+ const result = getSystemMessageWithRules({
+ baseSystemMessage,
+ userMessage,
+ rules: [
+ alwaysApplyTrueRule,
+ alwaysApplyFalseRule,
+ alwaysApplyFalseWithMatchingGlobs,
+ tsRule,
+ generalRule,
+ ],
+ contextItems: emptyContextItems,
+ });
+
+ // Should include:
+ // - alwaysApplyTrueRule (always applies)
+ // - alwaysApplyFalseWithMatchingGlobs (has globs that match .tsx)
+ // - tsRule (globs match .tsx)
+ // - generalRule (no globs, so applies to all)
+ // Should NOT include:
+ // - alwaysApplyFalseRule (alwaysApply: false and no globs)
+ const expected = `${baseSystemMessage}\n\n${alwaysApplyTrueRule.rule}\n\n${alwaysApplyFalseWithMatchingGlobs.rule}\n\n${tsRule.rule}\n\n${generalRule.rule}`;
+ expect(result).toBe(expected);
+ });
+
+ it("should use glob matching when alwaysApply is false", () => {
+ // This tests that rules with alwaysApply: false follow glob matching
+ const ruleWithAlwaysApplyFalse: RuleWithSource = {
+ name: "Rule With Always Apply False",
+ rule: "This rule follows glob matching behavior",
+ globs: "**/*.ts?(x)",
+ alwaysApply: false,
+ source: "rules-block",
+ };
+
+ const userMessage: UserChatMessage = {
+ role: "user",
+ content:
+ "```ts Component.tsx\nexport const Component = () =>
Hello
;\n```",
+ };
+
+ const result = getSystemMessageWithRules({
+ baseSystemMessage,
+ userMessage,
+ rules: [ruleWithAlwaysApplyFalse],
+ contextItems: emptyContextItems,
+ });
+
+ // Should include the rule because it matches the file path
+ const expected = `${baseSystemMessage}\n\n${ruleWithAlwaysApplyFalse.rule}`;
+ expect(result).toBe(expected);
+ });
+
+ it("should include rules with globs when context file paths match (alwaysApply false)", () => {
+ const ruleWithGlobsOnly: RuleWithSource = {
+ name: "TypeScript Only Rule",
+ rule: "This rule should apply to TypeScript files only",
+ globs: "**/*.ts",
+ alwaysApply: false,
+ source: "rules-block",
+ };
+
+ const tsContextItem: ContextItemWithId = {
+ content: "TypeScript file content",
+ name: "utils.ts",
+ description: "A TypeScript utility file",
+ id: { providerTitle: "file", itemId: "src/utils.ts" },
+ uri: { type: "file", value: "src/utils.ts" },
+ };
+
+ const result = getSystemMessageWithRules({
+ baseSystemMessage,
+ userMessage: undefined, // No message, only context
+ rules: [ruleWithGlobsOnly, pythonRule], // Include a non-matching rule
+ contextItems: [tsContextItem],
+ });
+
+ // Should include the TypeScript rule but not the Python rule
+ const expected = `${baseSystemMessage}\n\n${ruleWithGlobsOnly.rule}`;
+ expect(result).toBe(expected);
+ });
+
+ it("should NOT include rules with globs when context file paths don't match (alwaysApply false)", () => {
+ const ruleWithGlobsOnly: RuleWithSource = {
+ name: "TypeScript Only Rule",
+ rule: "This rule should apply to TypeScript files only",
+ globs: "**/*.ts",
+ alwaysApply: false,
+ source: "rules-block",
+ };
+
+ const pyContextItem: ContextItemWithId = {
+ content: "Python file content",
+ name: "utils.py",
+ description: "A Python utility file",
+ id: { providerTitle: "file", itemId: "src/utils.py" },
+ uri: { type: "file", value: "src/utils.py" },
+ };
+
+ const result = getSystemMessageWithRules({
+ baseSystemMessage,
+ userMessage: undefined, // No message, only context
+ rules: [ruleWithGlobsOnly],
+ contextItems: [pyContextItem], // Python file doesn't match *.ts pattern
+ });
+
+ // Should NOT include the rule because context doesn't match the glob
+ expect(result).toBe(baseSystemMessage);
+ });
+ });
+});
+
+describe("shouldApplyRule", () => {
+ const ruleWithGlobs: RuleWithSource = {
+ name: "Rule with Globs",
+ rule: "Apply to TypeScript files",
+ globs: "**/*.ts?(x)",
+ alwaysApply: false,
+ source: "rules-block",
+ };
+
+ const ruleWithoutGlobs: RuleWithSource = {
+ name: "Rule without Globs",
+ rule: "Apply to all files",
+ alwaysApply: true,
+ source: "rules-block",
+ };
+
+ const ruleAlwaysApplyTrue: RuleWithSource = {
+ name: "Always Apply True",
+ rule: "Always apply this rule",
+ globs: "**/*.nonexistent",
+ alwaysApply: true,
+ source: "rules-block",
+ };
+
+ const ruleAlwaysApplyFalse: RuleWithSource = {
+ name: "Always Apply False",
+ rule: "Never apply this rule",
+ globs: "**/*.ts?(x)",
+ alwaysApply: false,
+ source: "rules-block",
+ };
+
+ const ruleAlwaysApplyFalseNoGlobs: RuleWithSource = {
+ name: "Always Apply False No Globs",
+ rule: "Never apply this rule",
+ alwaysApply: false,
+ source: "rules-block",
+ };
+
+ describe("alwaysApply behavior", () => {
+ it("should return true when alwaysApply is true, regardless of file paths", () => {
+ expect(shouldApplyRule(ruleAlwaysApplyTrue, [])).toBe(true);
+ expect(shouldApplyRule(ruleAlwaysApplyTrue, ["src/main.js"])).toBe(true);
+ expect(shouldApplyRule(ruleAlwaysApplyTrue, ["Component.tsx"])).toBe(true);
+ });
+
+ it("should use glob matching when alwaysApply is false", () => {
+ // Should apply when globs match
+ expect(shouldApplyRule(ruleAlwaysApplyFalse, ["src/main.ts"])).toBe(true);
+ expect(shouldApplyRule(ruleAlwaysApplyFalse, ["Component.tsx"])).toBe(true);
+
+ // Should not apply when globs don't match
+ expect(shouldApplyRule(ruleAlwaysApplyFalse, ["script.py"])).toBe(false);
+ expect(shouldApplyRule(ruleAlwaysApplyFalse, [])).toBe(false);
+ });
+
+ it("should return false when alwaysApply is false and no globs specified", () => {
+ expect(shouldApplyRule(ruleAlwaysApplyFalseNoGlobs, [])).toBe(false);
+ expect(shouldApplyRule(ruleAlwaysApplyFalseNoGlobs, ["any-file.js"])).toBe(false);
+ });
+ });
+
+ describe("default behavior (alwaysApply undefined)", () => {
+ it("should return true for rules without globs regardless of file paths", () => {
+ expect(shouldApplyRule(ruleWithoutGlobs, [])).toBe(true);
+ expect(shouldApplyRule(ruleWithoutGlobs, ["src/main.js"])).toBe(true);
+ expect(shouldApplyRule(ruleWithoutGlobs, ["Component.tsx", "utils.py"])).toBe(true);
+ });
+
+ it("should return false for rules with globs when no file paths are provided", () => {
+ expect(shouldApplyRule(ruleWithGlobs, [])).toBe(false);
+ });
+
+ it("should return true for rules with globs when matching file paths are provided", () => {
+ expect(shouldApplyRule(ruleWithGlobs, ["Component.tsx"])).toBe(true);
+ expect(shouldApplyRule(ruleWithGlobs, ["src/main.ts"])).toBe(true);
+ expect(shouldApplyRule(ruleWithGlobs, ["utils.js", "Component.tsx"])).toBe(true);
+ });
+
+ it("should return false for rules with globs when no matching file paths are provided", () => {
+ expect(shouldApplyRule(ruleWithGlobs, ["utils.py"])).toBe(false);
+ expect(shouldApplyRule(ruleWithGlobs, ["main.js", "script.rb"])).toBe(false);
+ });
+ });
+
+ describe("glob pattern matching", () => {
+ const ruleWithArrayGlobs: RuleWithSource = {
+ name: "Rule with Array Globs",
+ rule: "Apply to specific patterns",
+ globs: ["src/**/*.ts", "tests/**/*.test.js"],
+ source: "rules-block",
+ };
+
+ const ruleWithSpecificPattern: RuleWithSource = {
+ name: "Rule with Specific Pattern",
+ rule: "Apply to Python files",
+ globs: "**/*.py",
+ source: "rules-block",
+ };
+
+ it("should handle array of glob patterns", () => {
+ expect(shouldApplyRule(ruleWithArrayGlobs, ["src/main.ts"])).toBe(true);
+ expect(shouldApplyRule(ruleWithArrayGlobs, ["tests/unit.test.js"])).toBe(true);
+ expect(shouldApplyRule(ruleWithArrayGlobs, ["config/settings.json"])).toBe(false);
+ });
+
+ it("should handle string glob patterns", () => {
+ expect(shouldApplyRule(ruleWithSpecificPattern, ["utils.py"])).toBe(true);
+ expect(shouldApplyRule(ruleWithSpecificPattern, ["src/models/user.py"])).toBe(true);
+ expect(shouldApplyRule(ruleWithSpecificPattern, ["utils.js"])).toBe(false);
+ });
+
+ it("should return true if any file path matches when multiple paths provided", () => {
+ expect(shouldApplyRule(ruleWithSpecificPattern, ["utils.js", "models.py", "config.json"])).toBe(true);
+ expect(shouldApplyRule(ruleWithGlobs, ["utils.py", "Component.tsx", "script.rb"])).toBe(true);
+ });
+ });
+
+ describe("edge cases", () => {
+ it("should handle empty globs array", () => {
+ const ruleWithEmptyGlobs: RuleWithSource = {
+ name: "Rule with Empty Globs",
+ rule: "Test rule",
+ globs: [],
+ source: "rules-block",
+ };
+
+ // Empty array should be treated as "no globs" (truthy check fails)
+ expect(shouldApplyRule(ruleWithEmptyGlobs, ["any-file.js"])).toBe(false);
+ });
+
+ it("should handle undefined globs", () => {
+ const ruleUndefinedGlobs: RuleWithSource = {
+ name: "Rule with Undefined Globs",
+ rule: "Test rule",
+ globs: undefined,
+ source: "rules-block",
+ };
+
+ expect(shouldApplyRule(ruleUndefinedGlobs, ["any-file.js"])).toBe(true);
+ expect(shouldApplyRule(ruleUndefinedGlobs, [])).toBe(true);
+ });
+ });
});
diff --git a/core/llm/rules/getSystemMessageWithRules.ts b/core/llm/rules/getSystemMessageWithRules.ts
index dacd941bb..acbdf98be 100644
--- a/core/llm/rules/getSystemMessageWithRules.ts
+++ b/core/llm/rules/getSystemMessageWithRules.ts
@@ -1,5 +1,10 @@
import { minimatch } from "minimatch";
-import { RuleWithSource, ToolResultChatMessage, UserChatMessage } from "../..";
+import {
+ ContextItemWithId,
+ RuleWithSource,
+ ToolResultChatMessage,
+ UserChatMessage,
+} from "../..";
import { renderChatMessage } from "../../util/messageContent";
import { extractPathsFromCodeBlocks } from "../utils/extractPathsFromCodeBlocks";
@@ -23,32 +28,91 @@ const matchesGlobs = (
return false;
};
-export const getSystemMessageWithRules = ({
- baseSystemMessage,
- userMessage,
- rules,
-}: {
- baseSystemMessage?: string;
- userMessage: UserChatMessage | ToolResultChatMessage | undefined;
- rules: RuleWithSource[];
-}) => {
+/**
+ * Determines if a rule should be applied based on its alwaysApply property and file path matching
+ *
+ * @param rule - The rule to check
+ * @param filePaths - Array of file paths to check against the rule's globs
+ * @returns true if the rule should be applied, false otherwise
+ */
+export const shouldApplyRule = (
+ rule: RuleWithSource,
+ filePaths: string[],
+): boolean => {
+ if (rule.alwaysApply) {
+ return true;
+ }
+
+ // If alwaysApply is explicitly false, only apply if there are globs AND they match
+ if (rule.alwaysApply === false) {
+ if (!rule.globs) {
+ return false; // No globs specified, don't apply
+ }
+ return filePaths.some((path) => matchesGlobs(path, rule.globs));
+ }
+
+ // If alwaysApply is undefined, default behavior:
+ // - No globs: always apply
+ // - Has globs: only apply if they match
+ if (!rule.globs) {
+ return true;
+ }
+
+ return filePaths.some((path) => matchesGlobs(path, rule.globs));
+};
+
+/**
+ * Filters rules that apply to the given message and/or context items
+ *
+ * @param userMessage - The user or tool message to check for file paths in code blocks
+ * @param rules - The list of rules to filter
+ * @param contextItems - Context items to check for file paths
+ * @returns List of applicable rules
+ */
+export const getApplicableRules = (
+ userMessage: UserChatMessage | ToolResultChatMessage | undefined,
+ rules: RuleWithSource[],
+ contextItems: ContextItemWithId[],
+): RuleWithSource[] => {
const filePathsFromMessage = userMessage
? extractPathsFromCodeBlocks(renderChatMessage(userMessage))
: [];
+ // Extract file paths from context items
+ const filePathsFromContextItems = contextItems
+ .filter((item) => item.uri?.type === "file" && item.uri?.value)
+ .map((item) => item.uri!.value);
+ // Combine file paths from both sources
+ const allFilePaths = [...filePathsFromMessage, ...filePathsFromContextItems];
+
+ return rules.filter((rule) => shouldApplyRule(rule, allFilePaths));
+};
+
+/**
+ * Creates a system message string with applicable rules appended
+ *
+ * @param baseSystemMessage - The base system message to start with
+ * @param userMessage - The user message to check for file paths
+ * @param rules - The list of rules to filter
+ * @param contextItems - Context items to check for file paths
+ * @returns System message with applicable rules appended
+ */
+export const getSystemMessageWithRules = ({
+ baseSystemMessage,
+ userMessage,
+ rules,
+ contextItems,
+}: {
+ baseSystemMessage?: string;
+ userMessage: UserChatMessage | ToolResultChatMessage | undefined;
+ rules: RuleWithSource[];
+ contextItems: ContextItemWithId[];
+}) => {
+ const applicableRules = getApplicableRules(userMessage, rules, contextItems);
let systemMessage = baseSystemMessage ?? "";
- for (const rule of rules) {
- // A rule is active if it has no globs (applies to all files)
- // or if at least one file path matches its globs
- const hasNoGlobs = !rule.globs;
- const matchesAnyFilePath = filePathsFromMessage.some((path) =>
- matchesGlobs(path, rule.globs),
- );
-
- if (hasNoGlobs || matchesAnyFilePath) {
- systemMessage += `\n\n${rule.rule}`;
- }
+ for (const rule of applicableRules) {
+ systemMessage += `\n\n${rule.rule}`;
}
return systemMessage;
diff --git a/core/llm/stream.ts b/core/llm/stream.ts
index 0a014d931..5902ec114 100644
--- a/core/llm/stream.ts
+++ b/core/llm/stream.ts
@@ -1,4 +1,4 @@
-async function* toAsyncIterable(
+export async function* toAsyncIterable(
nodeReadable: NodeJS.ReadableStream,
): AsyncGenerator {
for await (const chunk of nodeReadable) {
@@ -58,7 +58,7 @@ function parseDataLine(line: string): any {
}
function parseSseLine(line: string): { done: boolean; data: any } {
- if (line.startsWith("data: [DONE]")) {
+ if (line.startsWith("data:[DONE]") || line.startsWith("data: [DONE]")) {
return { done: true, data: undefined };
}
if (line.startsWith("data:")) {
diff --git a/core/llm/streamChat.ts b/core/llm/streamChat.ts
index 223b5b20e..c899e437f 100644
--- a/core/llm/streamChat.ts
+++ b/core/llm/streamChat.ts
@@ -8,7 +8,7 @@ import { TTS } from "../util/tts";
export async function* llmStreamChat(
configHandler: ConfigHandler,
- abortedMessageIds: Set,
+ abortController: AbortController,
msg: Message,
ide: IDE,
messenger: IMessenger,
@@ -75,52 +75,44 @@ export async function* llmStreamChat(
selectedCode,
config,
fetch: (url, init) =>
- fetchwithRequestOptions(url, init, config.requestOptions),
+ fetchwithRequestOptions(
+ url,
+ {
+ ...init,
+ signal: abortController.signal,
+ },
+ config.requestOptions,
+ ),
completionOptions,
});
- const checkActiveInterval = setInterval(() => {
- if (abortedMessageIds.has(msg.messageId)) {
- abortedMessageIds.delete(msg.messageId);
- clearInterval(checkActiveInterval);
+ let next = await gen.next();
+ while (!next.done) {
+ if (abortController.signal.aborted) {
+ next = await gen.return(errorPromptLog);
+ break;
}
- }, 100);
- try {
- let next = await gen.next();
- while (!next.done) {
- if (abortedMessageIds.has(msg.messageId)) {
- abortedMessageIds.delete(msg.messageId);
- next = await gen.return(errorPromptLog);
- clearInterval(checkActiveInterval);
- break;
- }
- if (next.value) {
- yield {
- role: "assistant",
- content: next.value,
- };
- }
- next = await gen.next();
+ if (next.value) {
+ yield {
+ role: "assistant",
+ content: next.value,
+ };
}
- if (!next.done) {
- throw new Error("Will never happen");
- }
-
- return next.value;
- } catch (e) {
- throw e;
- } finally {
- clearInterval(checkActiveInterval);
+ next = await gen.next();
}
+ if (!next.done) {
+ throw new Error("Will never happen");
+ }
+
+ return next.value;
} else {
const gen = model.streamChat(
messages,
- new AbortController().signal,
+ abortController.signal,
completionOptions,
);
let next = await gen.next();
while (!next.done) {
- if (abortedMessageIds.has(msg.messageId)) {
- abortedMessageIds.delete(msg.messageId);
+ if (abortController.signal.aborted) {
next = await gen.return(errorPromptLog);
break;
}
diff --git a/core/llm/templates/edit/gpt.ts b/core/llm/templates/edit/gpt.ts
index 4dcc39523..61d23a732 100644
--- a/core/llm/templates/edit/gpt.ts
+++ b/core/llm/templates/edit/gpt.ts
@@ -64,6 +64,8 @@ export const gptEditPrompt: PromptTemplateFunction = (history, otherData) => {
\`\`\`
The user's request is: "${otherData.userInput}"
+
+ DO NOT output any natural language, only output the code changes.
Here is the rewritten code:`);
diff --git a/core/llm/toolSupport.test.ts b/core/llm/toolSupport.test.ts
index c92bb93ee..d3100a61b 100644
--- a/core/llm/toolSupport.test.ts
+++ b/core/llm/toolSupport.test.ts
@@ -6,39 +6,57 @@ describe("PROVIDER_TOOL_SUPPORT", () => {
const supportsFn = PROVIDER_TOOL_SUPPORT["continue-proxy"];
it("should return true for Claude 3.5 models", () => {
- expect(supportsFn("claude-3-5-sonnet")).toBe(true);
- expect(supportsFn("claude-3.5-sonnet")).toBe(true);
+ expect(
+ supportsFn("ownerSlug/packageSlug/anthropic/claude-3-5-sonnet"),
+ ).toBe(true);
+ expect(
+ supportsFn("ownerSlug/packageSlug/anthropic/claude-3.5-sonnet"),
+ ).toBe(true);
});
it("should return true for Claude 3.7 models", () => {
- expect(supportsFn("claude-3-7-haiku")).toBe(true);
- expect(supportsFn("claude-3.7-sonnet")).toBe(true);
+ expect(
+ supportsFn("ownerSlug/packageSlug/anthropic/claude-3-7-haiku"),
+ ).toBe(true);
+ expect(
+ supportsFn("ownerSlug/packageSlug/anthropic/claude-3.7-sonnet"),
+ ).toBe(true);
});
it("should return true for GPT-4 models", () => {
- expect(supportsFn("gpt-4-turbo")).toBe(true);
- expect(supportsFn("gpt-4-1106-preview")).toBe(true);
+ expect(supportsFn("ownerSlug/packageSlug/openai/gpt-4-turbo")).toBe(true);
+ expect(
+ supportsFn("ownerSlug/packageSlug/openai/gpt-4-1106-preview"),
+ ).toBe(true);
});
it("should return true for O3 models", () => {
- expect(supportsFn("o3-preview")).toBe(true);
+ expect(supportsFn("ownerSlug/packageSlug/openai/o3-preview")).toBe(true);
});
it("should return true for Gemini models", () => {
- expect(supportsFn("gemini-pro")).toBe(true);
- expect(supportsFn("gemini-1.5-pro")).toBe(true);
+ expect(supportsFn("ownerSlug/packageSlug/gemini/gemini-pro")).toBe(true);
+ expect(supportsFn("ownerSlug/packageSlug/gemini/gemini-1.5-pro")).toBe(
+ true,
+ );
});
it("should return false for unsupported models", () => {
- expect(supportsFn("gpt-3.5-turbo")).toBe(false);
- expect(supportsFn("claude-2")).toBe(false);
- expect(supportsFn("llama-3")).toBe(false);
+ expect(supportsFn("ownerSlug/packageSlug/openai/gpt-3.5-turbo")).toBe(
+ false,
+ );
+ expect(supportsFn("ownerSlug/packageSlug/anthropic/claude-2")).toBe(
+ false,
+ );
+ expect(supportsFn("ownerSlug/packageSlug/together/llama-3")).toBe(false);
});
it("should handle case insensitivity", () => {
- expect(supportsFn("CLAUDE-3-5-sonnet")).toBe(true);
- expect(supportsFn("GPT-4-turbo")).toBe(true);
- expect(supportsFn("GEMINI-pro")).toBe(true);
+ expect(
+ supportsFn("ownerSlug/packageSlug/anthropic/CLAUDE-3-5-sonnet"),
+ ).toBe(true);
+ expect(supportsFn("ownerSlug/packageSlug/openai/GPT-4-turbo")).toBe(true);
+ expect(supportsFn("ownerSlug/packageSlug/gemini/GEMINI-pro")).toBe(true);
});
});
@@ -56,8 +74,8 @@ describe("PROVIDER_TOOL_SUPPORT", () => {
});
it("should return undefined for unsupported models", () => {
- expect(supportsFn("claude-2")).toBeUndefined();
- expect(supportsFn("claude-instant")).toBeUndefined();
+ expect(supportsFn("claude-2")).toBe(false);
+ expect(supportsFn("claude-instant")).toBe(false);
});
it("should handle case insensitivity", () => {
@@ -81,8 +99,8 @@ describe("PROVIDER_TOOL_SUPPORT", () => {
});
it("should return undefined for unsupported models", () => {
- expect(supportsFn("gpt-3.5-turbo")).toBeUndefined();
- expect(supportsFn("davinci")).toBeUndefined();
+ expect(supportsFn("gpt-3.5-turbo")).toBe(false);
+ expect(supportsFn("davinci")).toBe(false);
});
it("should handle case insensitivity", () => {
@@ -115,31 +133,49 @@ describe("PROVIDER_TOOL_SUPPORT", () => {
const supportsFn = PROVIDER_TOOL_SUPPORT["bedrock"];
it("should return true for Claude 3.5 Sonnet models", () => {
- expect(supportsFn("anthropic.claude-3-5-sonnet-20240620-v1:0")).toBe(true);
- expect(supportsFn("anthropic.claude-3.5-sonnet-20240620-v1:0")).toBe(true);
+ expect(supportsFn("anthropic.claude-3-5-sonnet-20240620-v1:0")).toBe(
+ true,
+ );
+ expect(supportsFn("anthropic.claude-3.5-sonnet-20240620-v1:0")).toBe(
+ true,
+ );
});
it("should return true for Claude 3.7 Sonnet models", () => {
- expect(supportsFn("anthropic.claude-3-7-sonnet-20240620-v1:0")).toBe(true);
- expect(supportsFn("anthropic.claude-3.7-sonnet-20240620-v1:0")).toBe(true);
+ expect(supportsFn("anthropic.claude-3-7-sonnet-20240620-v1:0")).toBe(
+ true,
+ );
+ expect(supportsFn("anthropic.claude-3.7-sonnet-20240620-v1:0")).toBe(
+ true,
+ );
});
it("should return undefined for Claude Haiku and Opus models", () => {
- expect(supportsFn("anthropic.claude-3-5-haiku-20240307-v1:0")).toBeUndefined();
- expect(supportsFn("anthropic.claude-3.5-haiku-20240620-v1:0")).toBeUndefined();
- expect(supportsFn("anthropic.claude-3-7-haiku-20240620-v1:0")).toBeUndefined();
- expect(supportsFn("anthropic.claude-3-5-opus-20240620-v1:0")).toBeUndefined();
- expect(supportsFn("anthropic.claude-3.7-opus-20240620-v1:0")).toBeUndefined();
+ expect(supportsFn("anthropic.claude-3-5-haiku-20240307-v1:0")).toBe(
+ false,
+ );
+ expect(supportsFn("anthropic.claude-3.5-haiku-20240620-v1:0")).toBe(
+ false,
+ );
+ expect(supportsFn("anthropic.claude-3-7-haiku-20240620-v1:0")).toBe(
+ false,
+ );
+ expect(supportsFn("anthropic.claude-3-5-opus-20240620-v1:0")).toBe(false);
+ expect(supportsFn("anthropic.claude-3.7-opus-20240620-v1:0")).toBe(false);
});
it("should return undefined for other unsupported models", () => {
- expect(supportsFn("anthropic.claude-instant-v1")).toBeUndefined();
- expect(supportsFn("anthropic.titan-text-express-v1")).toBeUndefined();
+ expect(supportsFn("anthropic.claude-instant-v1")).toBe(false);
+ expect(supportsFn("anthropic.titan-text-express-v1")).toBe(false);
});
it("should handle case insensitivity", () => {
- expect(supportsFn("ANTHROPIC.CLAUDE-3-5-SONNET-20240620-v1:0")).toBe(true);
- expect(supportsFn("ANTHROPIC.CLAUDE-3.7-SONNET-20240620-v1:0")).toBe(true);
+ expect(supportsFn("ANTHROPIC.CLAUDE-3-5-SONNET-20240620-v1:0")).toBe(
+ true,
+ );
+ expect(supportsFn("ANTHROPIC.CLAUDE-3.7-SONNET-20240620-v1:0")).toBe(
+ true,
+ );
});
});
@@ -155,6 +191,7 @@ describe("PROVIDER_TOOL_SUPPORT", () => {
expect(supportsFn("pixtral-12b-2409")).toBe(true);
expect(supportsFn("pixtral-large-latest")).toBe(true);
expect(supportsFn("open-mistral-nemo")).toBe(true);
+ expect(supportsFn("devstral-latest")).toBe(true);
});
it("should return false for other unsupported models", () => {
@@ -170,6 +207,7 @@ describe("PROVIDER_TOOL_SUPPORT", () => {
expect(supportsFn("CODESTRAL-LATEST")).toBe(true);
expect(supportsFn("MINISTRAL-8B-LATEST")).toBe(true);
expect(supportsFn("PIXTRAL-12B-2409")).toBe(true);
+ expect(supportsFn("DEVSTRAL-LATEST")).toBe(true);
});
});
@@ -192,6 +230,7 @@ describe("PROVIDER_TOOL_SUPPORT", () => {
expect(supportsFn("aya-expanse")).toBe(true);
expect(supportsFn("firefunction-v2")).toBe(true);
expect(supportsFn("mistral-7b")).toBe(true);
+ expect(supportsFn("devstral-24b")).toBe(true);
});
it("should return false for explicitly unsupported models", () => {
@@ -203,9 +242,9 @@ describe("PROVIDER_TOOL_SUPPORT", () => {
});
it("should return undefined for other models", () => {
- expect(supportsFn("llama2")).toBeUndefined();
- expect(supportsFn("phi-2")).toBeUndefined();
- expect(supportsFn("falcon")).toBeUndefined();
+ expect(supportsFn("llama2")).toBe(false);
+ expect(supportsFn("phi-2")).toBe(false);
+ expect(supportsFn("falcon")).toBe(false);
});
it("should handle case insensitivity", () => {
@@ -218,16 +257,16 @@ describe("PROVIDER_TOOL_SUPPORT", () => {
describe("edge cases", () => {
it("should handle empty model names", () => {
expect(PROVIDER_TOOL_SUPPORT["continue-proxy"]("")).toBe(false);
- expect(PROVIDER_TOOL_SUPPORT["anthropic"]("")).toBeUndefined();
- expect(PROVIDER_TOOL_SUPPORT["openai"]("")).toBeUndefined();
+ expect(PROVIDER_TOOL_SUPPORT["anthropic"]("")).toBe(false);
+ expect(PROVIDER_TOOL_SUPPORT["openai"]("")).toBe(false);
expect(PROVIDER_TOOL_SUPPORT["gemini"]("")).toBe(false);
- expect(PROVIDER_TOOL_SUPPORT["bedrock"]("")).toBeUndefined();
- expect(PROVIDER_TOOL_SUPPORT["ollama"]("")).toBeUndefined();
+ expect(PROVIDER_TOOL_SUPPORT["bedrock"]("")).toBe(false);
+ expect(PROVIDER_TOOL_SUPPORT["ollama"]("")).toBe(false);
});
it("should handle non-existent provider", () => {
// @ts-ignore - Testing runtime behavior with invalid provider
- expect(PROVIDER_TOOL_SUPPORT["non-existent"]).toBeUndefined();
+ expect(PROVIDER_TOOL_SUPPORT["non-existent"]).toBe(undefined);
});
});
});
diff --git a/core/llm/toolSupport.ts b/core/llm/toolSupport.ts
index cea36da6b..e6d4387ce 100644
--- a/core/llm/toolSupport.ts
+++ b/core/llm/toolSupport.ts
@@ -1,152 +1,274 @@
-export const PROVIDER_TOOL_SUPPORT: Record<
- string,
- (model: string) => boolean | undefined
-> = {
- "continue-proxy": (model) => {
- // see getContinueProxyModelName
- const provider = model.split("/")[2];
- const _model = model.split("/")[3];
- if (provider && _model && provider !== "continue-proxy") {
- const fn = PROVIDER_TOOL_SUPPORT[provider];
- if (fn) {
- return fn(_model);
- }
- }
- return [
- "claude-3-5",
- "claude-3.5",
- "claude-3-7",
- "claude-3.7",
- "gpt-4",
- "o3",
- "gemini",
- ].some((part) => model.toLowerCase().startsWith(part));
- },
- anthropic: (model) => {
- if (
- ["claude-3-5", "claude-3.5", "claude-3-7", "claude-3.7"].some((part) =>
- model.toLowerCase().startsWith(part),
- )
- ) {
- return true;
- }
- },
- azure: (model) => {
- if (
- model.toLowerCase().startsWith("gpt-4") ||
- model.toLowerCase().startsWith("o3")
- ) return true;
- return false;
- },
- openai: (model) => {
- // https://platform.openai.com/docs/guides/function-calling#models-supporting-function-calling
- if (
- model.toLowerCase().startsWith("gpt-4") ||
- model.toLowerCase().startsWith("o3")
- ) {
- return true;
- }
- // firworks-ai https://docs.fireworks.ai/guides/function-calling
- if (model.startsWith("accounts/fireworks/models/")) {
- switch (model.substring(26)) {
- case "llama-v3p1-405b-instruct":
- case "llama-v3p1-70b-instruct":
- case "qwen2p5-72b-instruct":
- case "firefunction-v1":
- case "firefunction-v2":
- return true;
- default:
- return false;
- }
- }
- },
- gemini: (model) => {
- // All gemini models support function calling
- return model.toLowerCase().includes("gemini");
- },
- vertexai: (model) => {
- // All gemini models except flash 2.0 lite support function calling
- return model.toLowerCase().includes("gemini") && !model.toLowerCase().includes("lite");;
- },
- bedrock: (model) => {
- // For Bedrock, only support Claude Sonnet models with versions 3.5/3-5 and 3.7/3-7
- if (
- model.toLowerCase().includes("sonnet") &&
- ["claude-3-5", "claude-3.5", "claude-3-7", "claude-3.7"].some((part) =>
- model.toLowerCase().includes(part),
- )
- ) {
- return true;
- }
- },
- mistral: (model) => {
- // https://docs.mistral.ai/capabilities/function_calling/
- return !model.toLowerCase().includes("mamba") &&
- [
- "codestral",
- "mistral-large",
- "mistral-small",
- "pixtral",
- "ministral",
- "mistral-nemo"
- ].some((part) => model.toLowerCase().includes(part));
- },
- // https://ollama.com/search?c=tools
- ollama: (model) => {
- let modelName = "";
- // Extract the model name after the last slash to support other registries
- if(model.includes("/")) {
- let parts = model.split('/');
- modelName = parts[parts.length - 1];
- } else {
- modelName = model;
- }
+import { parseProxyModelName } from "@continuedev/config-yaml";
+
+export const PROVIDER_TOOL_SUPPORT: Record boolean> =
+ {
+ "continue-proxy": (model) => {
+ try {
+ const { provider, model: _model } = parseProxyModelName(model);
+ if (provider && _model && provider !== "continue-proxy") {
+ const fn = PROVIDER_TOOL_SUPPORT[provider];
+ if (fn) {
+ return fn(_model);
+ }
+ }
+ } catch (e) {}
+
+ return [
+ "claude-3-5",
+ "claude-3.5",
+ "claude-3-7",
+ "claude-3.7",
+ "claude-sonnet-4",
+ "gpt-4",
+ "o3",
+ "gemini",
+ ].some((part) => model.toLowerCase().startsWith(part));
+ },
+ anthropic: (model) => {
+ if (
+ [
+ "claude-3-5",
+ "claude-3.5",
+ "claude-3-7",
+ "claude-3.7",
+ "claude-sonnet-4",
+ ].some((part) => model.toLowerCase().startsWith(part))
+ ) {
+ return true;
+ }
- if (
- ["vision", "math", "guard", "mistrallite", "mistral-openorca"].some(
- (part) => modelName.toLowerCase().includes(part),
- )
- ) {
return false;
- }
- if (
- [
- "cogito",
- "llama3.3",
- "qwq",
- "llama3.2",
- "llama3.1",
- "qwen2",
- "mixtral",
- "command-r",
- "smollm2",
- "hermes3",
- "athene-v2",
- "nemotron",
- "llama3-groq",
- "granite3",
- "granite-3",
- "aya-expanse",
- "firefunction-v2",
- "mistral",
- ].some((part) => modelName.toLowerCase().includes(part))
- ) {
- return true;
- }
- },
- sambanova: (model) => {
- // https://docs.sambanova.ai/cloud/docs/capabilities/function-calling
- if (
- model.toLowerCase().startsWith("meta-llama-3") ||
- model.toLowerCase().includes("llama-4") ||
- model.toLowerCase().includes("deepseek")
- ) {
- return true;
- }
- },
- deepseek: (model) => {
- if(model !== "deepseek-reasoner") {
- return true;
- }
- }
-};
+ },
+ azure: (model) => {
+ if (
+ model.toLowerCase().startsWith("gpt-4") ||
+ model.toLowerCase().startsWith("o3")
+ )
+ return true;
+ return false;
+ },
+ openai: (model) => {
+ // https://platform.openai.com/docs/guides/function-calling#models-supporting-function-calling
+ if (
+ model.toLowerCase().startsWith("gpt-4") ||
+ model.toLowerCase().startsWith("o3")
+ ) {
+ return true;
+ }
+ // firworks-ai https://docs.fireworks.ai/guides/function-calling
+ if (model.startsWith("accounts/fireworks/models/")) {
+ switch (model.substring(26)) {
+ case "llama-v3p1-405b-instruct":
+ case "llama-v3p1-70b-instruct":
+ case "qwen2p5-72b-instruct":
+ case "firefunction-v1":
+ case "firefunction-v2":
+ return true;
+ default:
+ return false;
+ }
+ }
+
+ return false;
+ },
+ gemini: (model) => {
+ // All gemini models support function calling
+ return model.toLowerCase().includes("gemini");
+ },
+ vertexai: (model) => {
+ // All gemini models except flash 2.0 lite support function calling
+ return (
+ model.toLowerCase().includes("gemini") &&
+ !model.toLowerCase().includes("lite")
+ );
+ },
+ bedrock: (model) => {
+ // For Bedrock, only support Claude Sonnet models with versions 3.5/3-5 and 3.7/3-7
+ if (
+ model.toLowerCase().includes("sonnet") &&
+ [
+ "claude-3-5",
+ "claude-3.5",
+ "claude-3-7",
+ "claude-3.7",
+ "claude-sonnet-4",
+ ].some((part) => model.toLowerCase().includes(part))
+ ) {
+ return true;
+ }
+
+ return false;
+ },
+ mistral: (model) => {
+ // https://docs.mistral.ai/capabilities/function_calling/
+ return (
+ !model.toLowerCase().includes("mamba") &&
+ [
+ "devstral",
+ "codestral",
+ "mistral-large",
+ "mistral-small",
+ "pixtral",
+ "ministral",
+ "mistral-nemo",
+ "devstral",
+ ].some((part) => model.toLowerCase().includes(part))
+ );
+ },
+ // https://ollama.com/search?c=tools
+ ollama: (model) => {
+ let modelName = "";
+ // Extract the model name after the last slash to support other registries
+ if (model.includes("/")) {
+ let parts = model.split("/");
+ modelName = parts[parts.length - 1];
+ } else {
+ modelName = model;
+ }
+
+ if (
+ ["vision", "math", "guard", "mistrallite", "mistral-openorca"].some(
+ (part) => modelName.toLowerCase().includes(part),
+ )
+ ) {
+ return false;
+ }
+ if (
+ [
+ "cogito",
+ "llama3.3",
+ "qwq",
+ "llama3.2",
+ "llama3.1",
+ "qwen2",
+ "qwen3",
+ "mixtral",
+ "command-r",
+ "smollm2",
+ "hermes3",
+ "athene-v2",
+ "nemotron",
+ "llama3-groq",
+ "granite3",
+ "granite-3",
+ "aya-expanse",
+ "firefunction-v2",
+ "mistral",
+ "devstral",
+ ].some((part) => modelName.toLowerCase().includes(part))
+ ) {
+ return true;
+ }
+
+ return false;
+ },
+ sambanova: (model) => {
+ // https://docs.sambanova.ai/cloud/docs/capabilities/function-calling
+ if (
+ model.toLowerCase().startsWith("meta-llama-3") ||
+ model.toLowerCase().includes("llama-4") ||
+ model.toLowerCase().includes("deepseek")
+ ) {
+ return true;
+ }
+
+ return false;
+ },
+ deepseek: (model) => {
+ if (model !== "deepseek-reasoner") {
+ return true;
+ }
+
+ return false;
+ },
+ watsonx: (model) => {
+ if (model.toLowerCase().includes("guard")) {
+ return false;
+ }
+ if (
+ [
+ "llama-3",
+ "llama-4",
+ "mistral",
+ "codestral",
+ "granite-3",
+ "devstral",
+ ].some((part) => model.toLowerCase().includes(part))
+ ) {
+ return true;
+ }
+
+ return false;
+ },
+ openrouter: (model) => {
+ // https://openrouter.ai/models?fmt=cards&supported_parameters=tools
+ if (
+ ["vision", "math", "guard", "mistrallite", "mistral-openorca"].some(
+ (part) => model.toLowerCase().includes(part),
+ )
+ ) {
+ return false;
+ }
+
+ const supportedPrefixes = [
+ "openai/gpt-3.5",
+ "openai/gpt-4",
+ "openai/o1",
+ "openai/o3",
+ "openai/o4",
+ "anthropic/claude-3",
+ "anthropic/claude-4",
+ "microsoft/phi-3",
+ "google/gemini-flash-1.5",
+ "google/gemini-2",
+ "google/gemini-pro",
+ "x-ai/grok",
+ "qwen/qwen3",
+ "qwen/qwen-",
+ "cohere/command-r",
+ "ai21/jamba-1.6",
+ "mistralai/mistral",
+ "mistralai/ministral",
+ "mistralai/codestral",
+ "mistralai/mixtral",
+ "mistral/ministral",
+ "mistral/devstral",
+ "mistralai/pixtral",
+ "meta-llama/llama-3.3",
+ "amazon/nova",
+ "deepseek/deepseek-r1",
+ "deepseek/deepseek-chat",
+ "meta-llama/llama-4",
+ "all-hands/openhands-lm-32b",
+ ];
+ for (const prefix of supportedPrefixes) {
+ if (model.toLowerCase().startsWith(prefix)) {
+ return true;
+ }
+ }
+
+ const specificModels = [
+ "qwen/qwq-32b",
+ "qwen/qwen-2.5-72b-instruct",
+ "meta-llama/llama-3.2-3b-instruct",
+ "meta-llama/llama-3-8b-instruct",
+ "meta-llama/llama-3-70b-instruct",
+ "arcee-ai/caller-large",
+ "nousresearch/hermes-3-llama-3.1-70b",
+ ];
+ for (const model of specificModels) {
+ if (model.toLowerCase() === model) {
+ return true;
+ }
+ }
+
+ const supportedContains = ["llama-3.1"];
+ for (const model of supportedContains) {
+ if (model.toLowerCase().includes(model)) {
+ return true;
+ }
+ }
+
+ return false;
+ },
+ };
diff --git a/core/llm/utils/extractPathsFromCodeBlocks.test.ts b/core/llm/utils/extractPathsFromCodeBlocks.test.ts
new file mode 100644
index 000000000..93959a392
--- /dev/null
+++ b/core/llm/utils/extractPathsFromCodeBlocks.test.ts
@@ -0,0 +1,35 @@
+import { extractPathsFromCodeBlocks } from "./extractPathsFromCodeBlocks";
+
+describe("extractPathsFromCodeBlocks", () => {
+ it("should extract paths from code blocks with language and filepath", () => {
+ const content = "```typescript src/main.ts\nconst x = 1;\n```";
+ expect(extractPathsFromCodeBlocks(content)).toEqual(["src/main.ts"]);
+ });
+
+ it("should extract paths from code blocks with filepath only (no language)", () => {
+ const content = "```test.js\nclass Calculator { }\n```";
+ expect(extractPathsFromCodeBlocks(content)).toEqual(["test.js"]);
+ });
+
+ it("should extract paths from code blocks with line ranges", () => {
+ const content = "```js test.js (19-25)\nfunction test() {}\n```";
+ expect(extractPathsFromCodeBlocks(content)).toEqual(["test.js"]);
+ });
+
+ it("should handle multiple code blocks with different formats", () => {
+ const content =
+ "```typescript src/main.ts\nconst x = 1;\n```\n" +
+ "```test.js\nclass Calculator { }\n```\n" +
+ "```js utils.js (19-25)\nfunction test() {}\n```";
+ const result = extractPathsFromCodeBlocks(content);
+ expect(result).toContain("src/main.ts");
+ expect(result).toContain("test.js");
+ expect(result).toContain("utils.js");
+ expect(result.length).toBe(3);
+ });
+
+ it("should not extract paths from code blocks without file paths", () => {
+ const content = "```typescript\nconst x = 1;\n```";
+ expect(extractPathsFromCodeBlocks(content)).toEqual([]);
+ });
+});
\ No newline at end of file
diff --git a/core/llm/utils/extractPathsFromCodeBlocks.ts b/core/llm/utils/extractPathsFromCodeBlocks.ts
index 7573a1f6f..00f723c7a 100644
--- a/core/llm/utils/extractPathsFromCodeBlocks.ts
+++ b/core/llm/utils/extractPathsFromCodeBlocks.ts
@@ -2,21 +2,37 @@
* Extracts file paths from markdown code blocks
*/
export function extractPathsFromCodeBlocks(content: string): string[] {
- // Match:
- // 1. Starting ```
- // 2. Optional language identifier
- // 3. Required whitespace
- // 4. File path (captured) that must contain a dot and extension
- const codeBlockRegex = /```(?:[\w-+#]+)?\s+([^\s\n()]+\.[a-zA-Z0-9]+)/g;
- const paths: string[] = [];
- let match;
+ console.log("CONTENT", content);
- while ((match = codeBlockRegex.exec(content)) !== null) {
- const path = match[1];
- if (path && !path.startsWith("```")) {
- paths.push(path);
+ const paths: string[] = [];
+
+ // Match code block opening patterns:
+ // 1. ```language filepath
+ // 2. ```filepath
+ // 3. ```language filepath (range)
+
+ // First match all code block starts
+ const codeBlockStarts = content.match(/```[^\n]+/g) || [];
+
+ for (const blockStart of codeBlockStarts) {
+ // Try to extract a valid filename with extension
+ const filenameMatches = blockStart.match(/([^\s()```]+\.[a-zA-Z0-9]+)/);
+
+ if (filenameMatches && filenameMatches[1]) {
+ const filename = filenameMatches[1];
+
+ // Verify this is a legitimate filename (not part of something else)
+ if (
+ // Check if valid extension
+ /\.[a-zA-Z0-9]+$/.test(filename) &&
+ // Make sure it's not a URL
+ !filename.includes("://") &&
+ // Avoid duplicates
+ !paths.includes(filename)
+ ) {
+ paths.push(filename);
+ }
}
}
-
return paths;
}
diff --git a/core/package-lock.json b/core/package-lock.json
index 71133e753..b2da9407e 100644
--- a/core/package-lock.json
+++ b/core/package-lock.json
@@ -14,10 +14,10 @@
"@aws-sdk/credential-providers": "^3.778.0",
"@continuedev/config-types": "^1.0.13",
"@continuedev/config-yaml": "file:../packages/config-yaml",
- "@continuedev/fetch": "^1.0.6",
+ "@continuedev/fetch": "^1.0.10",
"@continuedev/llm-info": "^1.0.8",
- "@continuedev/openai-adapters": "^1.0.19",
- "@modelcontextprotocol/sdk": "^1.5.0",
+ "@continuedev/openai-adapters": "^1.0.25",
+ "@modelcontextprotocol/sdk": "^1.12.0",
"@mozilla/readability": "^0.5.0",
"@octokit/rest": "^20.1.1",
"@typescript-eslint/eslint-plugin": "^7.8.0",
@@ -55,6 +55,7 @@
"p-limit": "^6.1.0",
"partial-json": "^0.1.7",
"pg": "^8.11.3",
+ "plist": "^3.1.0",
"posthog-node": "^3.6.3",
"puppeteer": "^22.4.0",
"puppeteer-chromium-resolver": "^23.0.0",
@@ -91,6 +92,7 @@
"@types/mustache": "^4.2.5",
"@types/node-fetch": "^2.6.11",
"@types/pg": "^8.11.6",
+ "@types/plist": "^3.0.5",
"@types/request": "^2.48.12",
"@types/tar": "^6.1.13",
"@types/uuid": "^9.0.7",
@@ -110,7 +112,10 @@
"node": ">=20.19.0"
}
},
- "../../../../../documents/code/continuedev/continue/packages/config-yaml": {
+ "../../../../dallin/documents/code/continuedev/continue/packages/config-yaml": {
+ "extraneous": true
+ },
+ "../../../../documents/code/continuedev/continue/packages/config-yaml": {
"version": "1.0.78",
"extraneous": true,
"license": "Apache-2.0",
@@ -131,12 +136,9 @@
"ts-node": "^10.9.2"
}
},
- "../../../../dallin/documents/code/continuedev/continue/packages/config-yaml": {
- "extraneous": true
- },
"../packages/config-yaml": {
"name": "@continuedev/config-yaml",
- "version": "1.0.87",
+ "version": "1.0.88",
"license": "Apache-2.0",
"dependencies": {
"@continuedev/config-types": "^1.0.14",
@@ -2925,9 +2927,10 @@
"link": true
},
"node_modules/@continuedev/fetch": {
- "version": "1.0.6",
- "resolved": "https://registry.npmjs.org/@continuedev/fetch/-/fetch-1.0.6.tgz",
- "integrity": "sha512-QpB9cHgEw5avoouFR0qm7/XTo44SrVfkGAmzbDTui2P9djj+DYvj+0yaJ8e/Ubyc5PUjFTUS2YnRar7NfYpHIg==",
+ "version": "1.0.10",
+ "resolved": "https://registry.npmjs.org/@continuedev/fetch/-/fetch-1.0.10.tgz",
+ "integrity": "sha512-RBUXtm/VDz+9Itgw+CxrHXwVXoHCAedGzPOgA7gS5HZ9lObaeCJgEfzmfbln1ocFsfqSFmn5X5wSE7DHgfxpVA==",
+ "license": "Apache-2.0",
"dependencies": {
"@continuedev/config-types": "^1.0.5",
"follow-redirects": "^1.15.6",
@@ -2942,14 +2945,15 @@
"integrity": "sha512-/htL7p4li3zQSwn9bXkI23WRpZNklWTPzRSSG3Fd5gvYW8cizjhlf7OzeDdKxBfi1S0lpqMm0VwHlx3KjMKLpw=="
},
"node_modules/@continuedev/openai-adapters": {
- "version": "1.0.19",
- "resolved": "https://registry.npmjs.org/@continuedev/openai-adapters/-/openai-adapters-1.0.19.tgz",
- "integrity": "sha512-9bfgTHPThRZAIn5T/zaWvKhMgVDFgpP3zr9DIkBT5THRNIrbbWd6VrguNEp9ASlX85ohNiXnk+jiC/FfFcH++w==",
+ "version": "1.0.25",
+ "resolved": "https://registry.npmjs.org/@continuedev/openai-adapters/-/openai-adapters-1.0.25.tgz",
+ "integrity": "sha512-YG7bcAlUk3BnqIOZw+ClmxmZU6G3OaaZqbhfqgiCnJem5i7oDy0pkAVHjig4iRTQkpvDokKmBXCH9wmQNRbWNw==",
+ "license": "Apache-2.0",
"dependencies": {
"@azure/openai": "^1.0.0-beta.12",
"@continuedev/config-types": "^1.0.5",
"@continuedev/config-yaml": "^1.0.51",
- "@continuedev/fetch": "^1.0.3",
+ "@continuedev/fetch": "^1.0.10",
"dotenv": "^16.5.0",
"json-schema": "^0.4.0",
"node-fetch": "^3.3.2",
@@ -3737,12 +3741,18 @@
]
},
"node_modules/@modelcontextprotocol/sdk": {
- "version": "1.5.0",
- "resolved": "https://registry.npmjs.org/@modelcontextprotocol/sdk/-/sdk-1.5.0.tgz",
- "integrity": "sha512-IJ+5iVVs8FCumIHxWqpwgkwOzyhtHVKy45s6Ug7Dv0MfRpaYisH8QQ87rIWeWdOzlk8sfhitZ7HCyQZk7d6b8w==",
+ "version": "1.12.0",
+ "resolved": "https://registry.npmjs.org/@modelcontextprotocol/sdk/-/sdk-1.12.0.tgz",
+ "integrity": "sha512-m//7RlINx1F3sz3KqwY1WWzVgTcYX52HYk4bJ1hkBXV3zccAEth+jRvG8DBRrdaQuRsPAJOx2MH3zaHNCKL7Zg==",
"dependencies": {
+ "ajv": "^6.12.6",
"content-type": "^1.0.5",
+ "cors": "^2.8.5",
+ "cross-spawn": "^7.0.5",
"eventsource": "^3.0.2",
+ "express": "^5.0.1",
+ "express-rate-limit": "^7.5.0",
+ "pkce-challenge": "^5.0.0",
"raw-body": "^3.0.0",
"zod": "^3.23.8",
"zod-to-json-schema": "^3.24.1"
@@ -4938,6 +4948,16 @@
"pg-types": "^4.0.1"
}
},
+ "node_modules/@types/plist": {
+ "version": "3.0.5",
+ "resolved": "https://registry.npmjs.org/@types/plist/-/plist-3.0.5.tgz",
+ "integrity": "sha512-E6OCaRmAe4WDmWNsL/9RMqdkkzDCY1etutkflWk4c+AcjDU07Pcz1fQwTX0TQz+Pxqn9i4L1TU3UFpjnrcDgxA==",
+ "dev": true,
+ "dependencies": {
+ "@types/node": "*",
+ "xmlbuilder": ">=11.0.1"
+ }
+ },
"node_modules/@types/readable-stream": {
"version": "4.0.18",
"resolved": "https://registry.npmjs.org/@types/readable-stream/-/readable-stream-4.0.18.tgz",
@@ -5258,6 +5278,14 @@
"onnxruntime-node": "1.14.0"
}
},
+ "node_modules/@xmldom/xmldom": {
+ "version": "0.8.10",
+ "resolved": "https://registry.npmjs.org/@xmldom/xmldom/-/xmldom-0.8.10.tgz",
+ "integrity": "sha512-2WALfTl4xo2SkGCYRt6rDTFfk9R1czmBvUQy12gK2KuRKIpWEhcbbzy8EZXtz/jkRqHX8bFEc6FC1HjX4TUWYw==",
+ "engines": {
+ "node": ">=10.0.0"
+ }
+ },
"node_modules/@yomguithereal/helpers": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/@yomguithereal/helpers/-/helpers-1.1.1.tgz",
@@ -5287,6 +5315,45 @@
"node": ">=6.5"
}
},
+ "node_modules/accepts": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/accepts/-/accepts-2.0.0.tgz",
+ "integrity": "sha512-5cvg6CtKwfgdmVqY1WIiXKc3Q1bkRqGLi+2W/6ao+6Y7gu/RCwRuAhGEzh5B4KlszSuTLgZYuqFqo5bImjNKng==",
+ "dependencies": {
+ "mime-types": "^3.0.0",
+ "negotiator": "^1.0.0"
+ },
+ "engines": {
+ "node": ">= 0.6"
+ }
+ },
+ "node_modules/accepts/node_modules/mime-db": {
+ "version": "1.54.0",
+ "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.54.0.tgz",
+ "integrity": "sha512-aU5EJuIN2WDemCcAp2vFBfp/m4EAhWJnUNSSw0ixs7/kXbd6Pg64EmwJkNdFhB8aWt1sH2CTXrLxo/iAGV3oPQ==",
+ "engines": {
+ "node": ">= 0.6"
+ }
+ },
+ "node_modules/accepts/node_modules/mime-types": {
+ "version": "3.0.1",
+ "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-3.0.1.tgz",
+ "integrity": "sha512-xRc4oEhT6eaBpU1XF7AjpOFD+xQmXNB5OVKwp4tqCuBpHLS/ZbBDrc07mYTDqVMg6PfxUjjNp85O6Cd2Z/5HWA==",
+ "dependencies": {
+ "mime-db": "^1.54.0"
+ },
+ "engines": {
+ "node": ">= 0.6"
+ }
+ },
+ "node_modules/accepts/node_modules/negotiator": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/negotiator/-/negotiator-1.0.0.tgz",
+ "integrity": "sha512-8Ofs/AUQh8MaEcrlq5xOX0CQ9ypTF5dl78mjlMNfOK08fzpgTHQRQPBxcPlEtIw0yRpws+Zo/3r+5WRby7u3Gg==",
+ "engines": {
+ "node": ">= 0.6"
+ }
+ },
"node_modules/acorn": {
"version": "8.14.0",
"resolved": "https://registry.npmjs.org/acorn/-/acorn-8.14.0.tgz",
@@ -6018,6 +6085,39 @@
"readable-stream": "^4.2.0"
}
},
+ "node_modules/body-parser": {
+ "version": "2.2.0",
+ "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-2.2.0.tgz",
+ "integrity": "sha512-02qvAaxv8tp7fBa/mw1ga98OGm+eCbqzJOKoRt70sLmfEEi+jyBYVTDGfCL/k06/4EMk/z01gCe7HoCH/f2LTg==",
+ "dependencies": {
+ "bytes": "^3.1.2",
+ "content-type": "^1.0.5",
+ "debug": "^4.4.0",
+ "http-errors": "^2.0.0",
+ "iconv-lite": "^0.6.3",
+ "on-finished": "^2.4.1",
+ "qs": "^6.14.0",
+ "raw-body": "^3.0.0",
+ "type-is": "^2.0.0"
+ },
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/body-parser/node_modules/qs": {
+ "version": "6.14.0",
+ "resolved": "https://registry.npmjs.org/qs/-/qs-6.14.0.tgz",
+ "integrity": "sha512-YWWTjgABSKcvs/nWBi9PycY/JiPJqOD4JA6o9Sej2AtvSGarXxKC3OQSk4pAarbdQlKAh5D4FCQkJNkW+GAn3w==",
+ "dependencies": {
+ "side-channel": "^1.1.0"
+ },
+ "engines": {
+ "node": ">=0.6"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
"node_modules/boolbase": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/boolbase/-/boolbase-1.0.0.tgz",
@@ -6247,9 +6347,9 @@
}
},
"node_modules/call-bind-apply-helpers": {
- "version": "1.0.1",
- "resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.1.tgz",
- "integrity": "sha512-BhYE+WDaywFg2TBWYNXAE+8B1ATnThNBqXHP5nQu0jWJdVvY2hvkpyB3qOmtmDePiS5/BDQ8wASEWGMWRG148g==",
+ "version": "1.0.2",
+ "resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz",
+ "integrity": "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==",
"dependencies": {
"es-errors": "^1.3.0",
"function-bind": "^1.1.2"
@@ -6258,6 +6358,21 @@
"node": ">= 0.4"
}
},
+ "node_modules/call-bound": {
+ "version": "1.0.4",
+ "resolved": "https://registry.npmjs.org/call-bound/-/call-bound-1.0.4.tgz",
+ "integrity": "sha512-+ys997U96po4Kx/ABpBCqhA9EuxJaQWDQg7295H4hBphv3IZg0boBKuwYpt4YXp6MZ5AmZQnU/tyMTlRpaSejg==",
+ "dependencies": {
+ "call-bind-apply-helpers": "^1.0.2",
+ "get-intrinsic": "^1.3.0"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
"node_modules/callsites": {
"version": "3.1.0",
"resolved": "https://registry.npmjs.org/callsites/-/callsites-3.1.0.tgz",
@@ -6640,6 +6755,17 @@
"resolved": "https://registry.npmjs.org/console-control-strings/-/console-control-strings-1.1.0.tgz",
"integrity": "sha512-ty/fTekppD2fIwRvnZAVdeOiGd1c7YXEixbgJTNzqcxJWKQnjJ/V1bNEEE6hygpM3WjwHFUVK6HTjWSzV4a8sQ=="
},
+ "node_modules/content-disposition": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-1.0.0.tgz",
+ "integrity": "sha512-Au9nRL8VNUut/XSzbQA38+M78dzP4D+eqg3gfJHMIHHYa3bg067xj1KxMUWj+VULbiZMowKngFFbKczUrNJ1mg==",
+ "dependencies": {
+ "safe-buffer": "5.2.1"
+ },
+ "engines": {
+ "node": ">= 0.6"
+ }
+ },
"node_modules/content-type": {
"version": "1.0.5",
"resolved": "https://registry.npmjs.org/content-type/-/content-type-1.0.5.tgz",
@@ -6654,6 +6780,22 @@
"integrity": "sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg==",
"dev": true
},
+ "node_modules/cookie": {
+ "version": "0.7.2",
+ "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.7.2.tgz",
+ "integrity": "sha512-yki5XnKuf750l50uGTllt6kKILY4nQ1eNIQatoXEByZ5dWgnKqbnqmTrBE5B4N7lrMJKQ2ytWMiTO2o0v6Ew/w==",
+ "engines": {
+ "node": ">= 0.6"
+ }
+ },
+ "node_modules/cookie-signature": {
+ "version": "1.2.2",
+ "resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.2.2.tgz",
+ "integrity": "sha512-D76uU73ulSXrD1UXF4KE2TMxVVwhsnCgfAyTg9k8P6KGZjlXKrOLe4dJQKI3Bxi5wjesZoFXJWElNWBjPZMbhg==",
+ "engines": {
+ "node": ">=6.6.0"
+ }
+ },
"node_modules/core-js-compat": {
"version": "3.39.0",
"resolved": "https://registry.npmjs.org/core-js-compat/-/core-js-compat-3.39.0.tgz",
@@ -6672,6 +6814,18 @@
"resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.3.tgz",
"integrity": "sha512-ZQBvi1DcpJ4GDqanjucZ2Hj3wEO5pZDS89BWbkcrvdxksJorwUDDZamX9ldFkp9aw2lmBDLgkObEA4DWNJ9FYQ=="
},
+ "node_modules/cors": {
+ "version": "2.8.5",
+ "resolved": "https://registry.npmjs.org/cors/-/cors-2.8.5.tgz",
+ "integrity": "sha512-KIHbLJqu73RGr/hnbrO9uBeixNGuvSQjul/jdFvS/KFSIH1hWVd1ng7zOHx+YrEfInLG7q4n6GHQ9cDtxv/P6g==",
+ "dependencies": {
+ "object-assign": "^4",
+ "vary": "^1"
+ },
+ "engines": {
+ "node": ">= 0.10"
+ }
+ },
"node_modules/cosmiconfig": {
"version": "9.0.0",
"resolved": "https://registry.npmjs.org/cosmiconfig/-/cosmiconfig-9.0.0.tgz",
@@ -7181,11 +7335,11 @@
}
},
"node_modules/dunder-proto": {
- "version": "1.0.0",
- "resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.0.tgz",
- "integrity": "sha512-9+Sj30DIu+4KvHqMfLUGLFYL2PkURSYMVXJyXe92nFRvlYq5hBjLEhblKB+vkd/WVlUYMWigiY07T91Fkk0+4A==",
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz",
+ "integrity": "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==",
"dependencies": {
- "call-bind-apply-helpers": "^1.0.0",
+ "call-bind-apply-helpers": "^1.0.1",
"es-errors": "^1.3.0",
"gopd": "^1.2.0"
},
@@ -7220,6 +7374,11 @@
"safe-buffer": "^5.0.1"
}
},
+ "node_modules/ee-first": {
+ "version": "1.1.1",
+ "resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz",
+ "integrity": "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow=="
+ },
"node_modules/eight-colors": {
"version": "1.3.1",
"resolved": "https://registry.npmjs.org/eight-colors/-/eight-colors-1.3.1.tgz",
@@ -7268,6 +7427,14 @@
"resolved": "https://registry.npmjs.org/enabled/-/enabled-2.0.0.tgz",
"integrity": "sha512-AKrN98kuwOzMIdAizXGI86UFBoo26CL21UM763y1h/GMSJ4/OHU9k2YlsmBpyScFo/wbLzWQJBMCW4+IO3/+OQ=="
},
+ "node_modules/encodeurl": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-2.0.0.tgz",
+ "integrity": "sha512-Q0n9HRi4m6JuGIV1eFlmvJB7ZEVxu93IrMyiMsGC0lrMJMWzRgx6WGquyfQgZVb31vhGgXnfmPNNXmxnOkRBrg==",
+ "engines": {
+ "node": ">= 0.8"
+ }
+ },
"node_modules/encoding": {
"version": "0.1.13",
"resolved": "https://registry.npmjs.org/encoding/-/encoding-0.1.13.tgz",
@@ -7463,9 +7630,9 @@
}
},
"node_modules/es-object-atoms": {
- "version": "1.0.0",
- "resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.0.0.tgz",
- "integrity": "sha512-MZ4iQ6JwHOBQjahnjwaC1ZtIBH+2ohjamzAO3oaHcXYup7qxjF2fixyH+Q71voWHeOkI2q/TnJao/KfXYIZWbw==",
+ "version": "1.1.1",
+ "resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.1.tgz",
+ "integrity": "sha512-FGgH2h8zKNim9ljj7dankFPcICIK9Cp5bm+c2gQSYePhpaG5+esrLODihIorn+Pe6FGJzWhXQotPv73jTaldXA==",
"dependencies": {
"es-errors": "^1.3.0"
},
@@ -7558,6 +7725,11 @@
"node": ">=6"
}
},
+ "node_modules/escape-html": {
+ "version": "1.0.3",
+ "resolved": "https://registry.npmjs.org/escape-html/-/escape-html-1.0.3.tgz",
+ "integrity": "sha512-NiSupZ4OeuGwr68lGIeym/ksIZMJodUGOSCZ/FSnTxcrekbvqrgdUxlJOMpijaKZVjAJrWrGs/6Jy8OMuyj9ow=="
+ },
"node_modules/escape-string-regexp": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-4.0.0.tgz",
@@ -7933,6 +8105,14 @@
"node": ">=0.10.0"
}
},
+ "node_modules/etag": {
+ "version": "1.8.1",
+ "resolved": "https://registry.npmjs.org/etag/-/etag-1.8.1.tgz",
+ "integrity": "sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg==",
+ "engines": {
+ "node": ">= 0.6"
+ }
+ },
"node_modules/event-target-shim": {
"version": "5.0.1",
"resolved": "https://registry.npmjs.org/event-target-shim/-/event-target-shim-5.0.1.tgz",
@@ -8024,6 +8204,94 @@
"node": "^14.15.0 || ^16.10.0 || >=18.0.0"
}
},
+ "node_modules/express": {
+ "version": "5.1.0",
+ "resolved": "https://registry.npmjs.org/express/-/express-5.1.0.tgz",
+ "integrity": "sha512-DT9ck5YIRU+8GYzzU5kT3eHGA5iL+1Zd0EutOmTE9Dtk+Tvuzd23VBU+ec7HPNSTxXYO55gPV/hq4pSBJDjFpA==",
+ "dependencies": {
+ "accepts": "^2.0.0",
+ "body-parser": "^2.2.0",
+ "content-disposition": "^1.0.0",
+ "content-type": "^1.0.5",
+ "cookie": "^0.7.1",
+ "cookie-signature": "^1.2.1",
+ "debug": "^4.4.0",
+ "encodeurl": "^2.0.0",
+ "escape-html": "^1.0.3",
+ "etag": "^1.8.1",
+ "finalhandler": "^2.1.0",
+ "fresh": "^2.0.0",
+ "http-errors": "^2.0.0",
+ "merge-descriptors": "^2.0.0",
+ "mime-types": "^3.0.0",
+ "on-finished": "^2.4.1",
+ "once": "^1.4.0",
+ "parseurl": "^1.3.3",
+ "proxy-addr": "^2.0.7",
+ "qs": "^6.14.0",
+ "range-parser": "^1.2.1",
+ "router": "^2.2.0",
+ "send": "^1.1.0",
+ "serve-static": "^2.2.0",
+ "statuses": "^2.0.1",
+ "type-is": "^2.0.1",
+ "vary": "^1.1.2"
+ },
+ "engines": {
+ "node": ">= 18"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/express"
+ }
+ },
+ "node_modules/express-rate-limit": {
+ "version": "7.5.0",
+ "resolved": "https://registry.npmjs.org/express-rate-limit/-/express-rate-limit-7.5.0.tgz",
+ "integrity": "sha512-eB5zbQh5h+VenMPM3fh+nw1YExi5nMr6HUCR62ELSP11huvxm/Uir1H1QEyTkk5QX6A58pX6NmaTMceKZ0Eodg==",
+ "engines": {
+ "node": ">= 16"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/express-rate-limit"
+ },
+ "peerDependencies": {
+ "express": "^4.11 || 5 || ^5.0.0-beta.1"
+ }
+ },
+ "node_modules/express/node_modules/mime-db": {
+ "version": "1.54.0",
+ "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.54.0.tgz",
+ "integrity": "sha512-aU5EJuIN2WDemCcAp2vFBfp/m4EAhWJnUNSSw0ixs7/kXbd6Pg64EmwJkNdFhB8aWt1sH2CTXrLxo/iAGV3oPQ==",
+ "engines": {
+ "node": ">= 0.6"
+ }
+ },
+ "node_modules/express/node_modules/mime-types": {
+ "version": "3.0.1",
+ "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-3.0.1.tgz",
+ "integrity": "sha512-xRc4oEhT6eaBpU1XF7AjpOFD+xQmXNB5OVKwp4tqCuBpHLS/ZbBDrc07mYTDqVMg6PfxUjjNp85O6Cd2Z/5HWA==",
+ "dependencies": {
+ "mime-db": "^1.54.0"
+ },
+ "engines": {
+ "node": ">= 0.6"
+ }
+ },
+ "node_modules/express/node_modules/qs": {
+ "version": "6.14.0",
+ "resolved": "https://registry.npmjs.org/qs/-/qs-6.14.0.tgz",
+ "integrity": "sha512-YWWTjgABSKcvs/nWBi9PycY/JiPJqOD4JA6o9Sej2AtvSGarXxKC3OQSk4pAarbdQlKAh5D4FCQkJNkW+GAn3w==",
+ "dependencies": {
+ "side-channel": "^1.1.0"
+ },
+ "engines": {
+ "node": ">=0.6"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
"node_modules/extend": {
"version": "3.0.2",
"resolved": "https://registry.npmjs.org/extend/-/extend-3.0.2.tgz",
@@ -8250,6 +8518,22 @@
"resolved": "https://registry.npmjs.org/filtrex/-/filtrex-3.1.0.tgz",
"integrity": "sha512-mHzZ2wUISETF1OaEcNRiGz1ljuIV8c/C9td9qyAZ+wTwigkAk5RO9YrCxQKk5H9v7joDRFIBik9U5RTK9eXZ/A=="
},
+ "node_modules/finalhandler": {
+ "version": "2.1.0",
+ "resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-2.1.0.tgz",
+ "integrity": "sha512-/t88Ty3d5JWQbWYgaOGCCYfXRwV1+be02WqYYlL6h0lEiUAMPM8o8qKGO01YIkOHzka2up08wvgYD0mDiI+q3Q==",
+ "dependencies": {
+ "debug": "^4.4.0",
+ "encodeurl": "^2.0.0",
+ "escape-html": "^1.0.3",
+ "on-finished": "^2.4.1",
+ "parseurl": "^1.3.3",
+ "statuses": "^2.0.1"
+ },
+ "engines": {
+ "node": ">= 0.8"
+ }
+ },
"node_modules/find-replace": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/find-replace/-/find-replace-3.0.0.tgz",
@@ -8417,6 +8701,22 @@
"node": ">=12.20.0"
}
},
+ "node_modules/forwarded": {
+ "version": "0.2.0",
+ "resolved": "https://registry.npmjs.org/forwarded/-/forwarded-0.2.0.tgz",
+ "integrity": "sha512-buRG0fpBtRHSTCOASe6hD258tEubFoRLb4ZNA6NxMVHNw2gOcwHo9wyablzMzOA5z9xA9L1KNjk/Nt6MT9aYow==",
+ "engines": {
+ "node": ">= 0.6"
+ }
+ },
+ "node_modules/fresh": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/fresh/-/fresh-2.0.0.tgz",
+ "integrity": "sha512-Rx/WycZ60HOaqLKAi6cHRKKI7zxWbJ31MhntmtwMoaTeF7XFH9hhBp8vITaMidfljRQ6eYWCKkaTK+ykVJHP2A==",
+ "engines": {
+ "node": ">= 0.8"
+ }
+ },
"node_modules/fs-constants": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/fs-constants/-/fs-constants-1.0.0.tgz",
@@ -8619,18 +8919,20 @@
}
},
"node_modules/get-intrinsic": {
- "version": "1.2.5",
- "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.2.5.tgz",
- "integrity": "sha512-Y4+pKa7XeRUPWFNvOOYHkRYrfzW07oraURSvjDmRVOJ748OrVmeXtpE4+GCEHncjCjkTxPNRt8kEbxDhsn6VTg==",
+ "version": "1.3.0",
+ "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz",
+ "integrity": "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==",
"dependencies": {
- "call-bind-apply-helpers": "^1.0.0",
- "dunder-proto": "^1.0.0",
+ "call-bind-apply-helpers": "^1.0.2",
"es-define-property": "^1.0.1",
"es-errors": "^1.3.0",
+ "es-object-atoms": "^1.1.1",
"function-bind": "^1.1.2",
+ "get-proto": "^1.0.1",
"gopd": "^1.2.0",
"has-symbols": "^1.1.0",
- "hasown": "^2.0.2"
+ "hasown": "^2.0.2",
+ "math-intrinsics": "^1.1.0"
},
"engines": {
"node": ">= 0.4"
@@ -8648,6 +8950,18 @@
"node": ">=8.0.0"
}
},
+ "node_modules/get-proto": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/get-proto/-/get-proto-1.0.1.tgz",
+ "integrity": "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==",
+ "dependencies": {
+ "dunder-proto": "^1.0.1",
+ "es-object-atoms": "^1.0.0"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ }
+ },
"node_modules/get-stream": {
"version": "6.0.1",
"resolved": "https://registry.npmjs.org/get-stream/-/get-stream-6.0.1.tgz",
@@ -9320,6 +9634,14 @@
"node": ">= 12"
}
},
+ "node_modules/ipaddr.js": {
+ "version": "1.9.1",
+ "resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-1.9.1.tgz",
+ "integrity": "sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g==",
+ "engines": {
+ "node": ">= 0.10"
+ }
+ },
"node_modules/is-array-buffer": {
"version": "3.0.4",
"resolved": "https://registry.npmjs.org/is-array-buffer/-/is-array-buffer-3.0.4.tgz",
@@ -9604,6 +9926,11 @@
"resolved": "https://registry.npmjs.org/is-potential-custom-element-name/-/is-potential-custom-element-name-1.0.1.tgz",
"integrity": "sha512-bCYeRA2rVibKZd+s2625gGnGF/t7DSqDs4dP7CrLA1m7jKWz6pps0LpYLJN8Q64HtmPKJ1hrN3nzPNKFEKOUiQ=="
},
+ "node_modules/is-promise": {
+ "version": "4.0.0",
+ "resolved": "https://registry.npmjs.org/is-promise/-/is-promise-4.0.0.tgz",
+ "integrity": "sha512-hvpoI6korhJMnej285dSg6nu1+e6uxs7zG3BYAm5byqDsgJNWwxzM6z6iZiAgQR4TJ30JmBTOwqZUw3WlyH3AQ=="
+ },
"node_modules/is-property": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/is-property/-/is-property-1.0.2.tgz",
@@ -11442,6 +11769,33 @@
"tmpl": "1.0.5"
}
},
+ "node_modules/math-intrinsics": {
+ "version": "1.1.0",
+ "resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz",
+ "integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==",
+ "engines": {
+ "node": ">= 0.4"
+ }
+ },
+ "node_modules/media-typer": {
+ "version": "1.1.0",
+ "resolved": "https://registry.npmjs.org/media-typer/-/media-typer-1.1.0.tgz",
+ "integrity": "sha512-aisnrDP4GNe06UcKFnV5bfMNPBUw4jsLGaWwWfnH3v02GnBuXX2MCVn5RbrWo0j3pczUilYblq7fQ7Nw2t5XKw==",
+ "engines": {
+ "node": ">= 0.8"
+ }
+ },
+ "node_modules/merge-descriptors": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-2.0.0.tgz",
+ "integrity": "sha512-Snk314V5ayFLhp3fkUREub6WtjBfPdCPY1Ln8/8munuLuiYhsABgBVWsozAG+MWMbVEvcdcpbi9R7ww22l9Q3g==",
+ "engines": {
+ "node": ">=18"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/sindresorhus"
+ }
+ },
"node_modules/merge-stream": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/merge-stream/-/merge-stream-2.0.0.tgz",
@@ -12112,11 +12466,18 @@
"node": "*"
}
},
+ "node_modules/object-assign": {
+ "version": "4.1.1",
+ "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz",
+ "integrity": "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==",
+ "engines": {
+ "node": ">=0.10.0"
+ }
+ },
"node_modules/object-inspect": {
"version": "1.13.3",
"resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.3.tgz",
"integrity": "sha512-kDCGIbxkDSXE3euJZZXzc6to7fCrKHNI/hSRQnRuQ+BWjFNzZwiFF8fj/6o2t2G9/jTj8PSIYTfCLelLZEeRpA==",
- "peer": true,
"engines": {
"node": ">= 0.4"
},
@@ -12230,6 +12591,17 @@
"whatwg-fetch": "^3.6.20"
}
},
+ "node_modules/on-finished": {
+ "version": "2.4.1",
+ "resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.4.1.tgz",
+ "integrity": "sha512-oVlzkg3ENAhCk2zdv7IJwd/QUD4z2RxRwpkcGY8psCVcCYZNq4wYnVWALHM+brtuJjePWiYF/ClmuDr8Ch5+kg==",
+ "dependencies": {
+ "ee-first": "1.1.1"
+ },
+ "engines": {
+ "node": ">= 0.8"
+ }
+ },
"node_modules/once": {
"version": "1.4.0",
"resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz",
@@ -12599,6 +12971,14 @@
"url": "https://github.com/inikulin/parse5?sponsor=1"
}
},
+ "node_modules/parseurl": {
+ "version": "1.3.3",
+ "resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz",
+ "integrity": "sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ==",
+ "engines": {
+ "node": ">= 0.8"
+ }
+ },
"node_modules/partial-json": {
"version": "0.1.7",
"resolved": "https://registry.npmjs.org/partial-json/-/partial-json-0.1.7.tgz",
@@ -12661,6 +13041,14 @@
"node": ">=16 || 14 >=14.17"
}
},
+ "node_modules/path-to-regexp": {
+ "version": "8.2.0",
+ "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-8.2.0.tgz",
+ "integrity": "sha512-TdrF7fW9Rphjq4RjrW0Kp2AW0Ahwu9sRGTkS6bvDi0SCwZlEZYmcfDbEsTz8RVk0EHIS/Vd1bv3JhG+1xZuAyQ==",
+ "engines": {
+ "node": ">=16"
+ }
+ },
"node_modules/path-type": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/path-type/-/path-type-4.0.0.tgz",
@@ -12855,6 +13243,14 @@
"node": ">= 6"
}
},
+ "node_modules/pkce-challenge": {
+ "version": "5.0.0",
+ "resolved": "https://registry.npmjs.org/pkce-challenge/-/pkce-challenge-5.0.0.tgz",
+ "integrity": "sha512-ueGLflrrnvwB3xuo/uGob5pd5FN7l0MsLf0Z87o/UQmRtwjvfylfc9MurIxRAWywCYTgrvpXBcqjV4OfCYGCIQ==",
+ "engines": {
+ "node": ">=16.20.0"
+ }
+ },
"node_modules/pkg-dir": {
"version": "4.2.0",
"resolved": "https://registry.npmjs.org/pkg-dir/-/pkg-dir-4.2.0.tgz",
@@ -12924,6 +13320,19 @@
"resolved": "https://registry.npmjs.org/platform/-/platform-1.3.6.tgz",
"integrity": "sha512-fnWVljUchTro6RiCFvCXBbNhJc2NijN7oIQxbwsyL0buWJPG85v81ehlHI9fXrJsMNgTofEoWIQeClKpgxFLrg=="
},
+ "node_modules/plist": {
+ "version": "3.1.0",
+ "resolved": "https://registry.npmjs.org/plist/-/plist-3.1.0.tgz",
+ "integrity": "sha512-uysumyrvkUX0rX/dEVqt8gC3sTBzd4zoWfLeS29nb53imdaXVvLINYXTI2GNqzaMuvacNx4uJQ8+b3zXR0pkgQ==",
+ "dependencies": {
+ "@xmldom/xmldom": "^0.8.8",
+ "base64-js": "^1.5.1",
+ "xmlbuilder": "^15.1.1"
+ },
+ "engines": {
+ "node": ">=10.4.0"
+ }
+ },
"node_modules/possible-typed-array-names": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/possible-typed-array-names/-/possible-typed-array-names-1.0.0.tgz",
@@ -13205,6 +13614,18 @@
"resolved": "https://registry.npmjs.org/long/-/long-4.0.0.tgz",
"integrity": "sha512-XsP+KhQif4bjX1kbuSiySJFNAehNxgLb6hPRGJ9QsUr8ajHkuXGdrHmFUTUUXhDwVX2R5bY4JNZEwbUiMhV+MA=="
},
+ "node_modules/proxy-addr": {
+ "version": "2.0.7",
+ "resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.7.tgz",
+ "integrity": "sha512-llQsMLSUDUPT44jdrU/O37qlnifitDP+ZwrmmZcoSKyLKvtZxpyV0n2/bD/N4tBAAZ/gJEdZU7KMraoK1+XYAg==",
+ "dependencies": {
+ "forwarded": "0.2.0",
+ "ipaddr.js": "1.9.1"
+ },
+ "engines": {
+ "node": ">= 0.10"
+ }
+ },
"node_modules/proxy-agent": {
"version": "6.5.0",
"resolved": "https://registry.npmjs.org/proxy-agent/-/proxy-agent-6.5.0.tgz",
@@ -13447,6 +13868,14 @@
"url": "https://github.com/sponsors/sindresorhus"
}
},
+ "node_modules/range-parser": {
+ "version": "1.2.1",
+ "resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.2.1.tgz",
+ "integrity": "sha512-Hrgsx+orqoygnmhFbKaHE6c296J+HTAQXoxEF6gNupROmmGJRoyzfG3ccAveqCBrwr/2yxQ5BVd/GTl5agOwSg==",
+ "engines": {
+ "node": ">= 0.6"
+ }
+ },
"node_modules/raw-body": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/raw-body/-/raw-body-3.0.0.tgz",
@@ -13804,6 +14233,21 @@
"url": "https://github.com/sponsors/isaacs"
}
},
+ "node_modules/router": {
+ "version": "2.2.0",
+ "resolved": "https://registry.npmjs.org/router/-/router-2.2.0.tgz",
+ "integrity": "sha512-nLTrUKm2UyiL7rlhapu/Zl45FwNgkZGaCpZbIHajDYgwlJCOzLSk+cIPAnsEqV955GjILJnKbdQC1nVPz+gAYQ==",
+ "dependencies": {
+ "debug": "^4.4.0",
+ "depd": "^2.0.0",
+ "is-promise": "^4.0.0",
+ "parseurl": "^1.3.3",
+ "path-to-regexp": "^8.0.0"
+ },
+ "engines": {
+ "node": ">= 18"
+ }
+ },
"node_modules/rrweb-cssom": {
"version": "0.7.1",
"resolved": "https://registry.npmjs.org/rrweb-cssom/-/rrweb-cssom-0.7.1.tgz",
@@ -13922,11 +14366,65 @@
"semver": "bin/semver.js"
}
},
+ "node_modules/send": {
+ "version": "1.2.0",
+ "resolved": "https://registry.npmjs.org/send/-/send-1.2.0.tgz",
+ "integrity": "sha512-uaW0WwXKpL9blXE2o0bRhoL2EGXIrZxQ2ZQ4mgcfoBxdFmQold+qWsD2jLrfZ0trjKL6vOw0j//eAwcALFjKSw==",
+ "dependencies": {
+ "debug": "^4.3.5",
+ "encodeurl": "^2.0.0",
+ "escape-html": "^1.0.3",
+ "etag": "^1.8.1",
+ "fresh": "^2.0.0",
+ "http-errors": "^2.0.0",
+ "mime-types": "^3.0.1",
+ "ms": "^2.1.3",
+ "on-finished": "^2.4.1",
+ "range-parser": "^1.2.1",
+ "statuses": "^2.0.1"
+ },
+ "engines": {
+ "node": ">= 18"
+ }
+ },
+ "node_modules/send/node_modules/mime-db": {
+ "version": "1.54.0",
+ "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.54.0.tgz",
+ "integrity": "sha512-aU5EJuIN2WDemCcAp2vFBfp/m4EAhWJnUNSSw0ixs7/kXbd6Pg64EmwJkNdFhB8aWt1sH2CTXrLxo/iAGV3oPQ==",
+ "engines": {
+ "node": ">= 0.6"
+ }
+ },
+ "node_modules/send/node_modules/mime-types": {
+ "version": "3.0.1",
+ "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-3.0.1.tgz",
+ "integrity": "sha512-xRc4oEhT6eaBpU1XF7AjpOFD+xQmXNB5OVKwp4tqCuBpHLS/ZbBDrc07mYTDqVMg6PfxUjjNp85O6Cd2Z/5HWA==",
+ "dependencies": {
+ "mime-db": "^1.54.0"
+ },
+ "engines": {
+ "node": ">= 0.6"
+ }
+ },
"node_modules/seq-queue": {
"version": "0.0.5",
"resolved": "https://registry.npmjs.org/seq-queue/-/seq-queue-0.0.5.tgz",
"integrity": "sha512-hr3Wtp/GZIc/6DAGPDcV4/9WoZhjrkXsi5B/07QgX8tsdc6ilr7BFM6PM6rbdAX1kFSDYeZGLipIZZKyQP0O5Q=="
},
+ "node_modules/serve-static": {
+ "version": "2.2.0",
+ "resolved": "https://registry.npmjs.org/serve-static/-/serve-static-2.2.0.tgz",
+ "integrity": "sha512-61g9pCh0Vnh7IutZjtLGGpTA355+OPn2TyDv/6ivP2h/AdAVX9azsoxmg2/M6nZeQZNYBEwIcsne1mJd9oQItQ==",
+ "dependencies": {
+ "encodeurl": "^2.0.0",
+ "escape-html": "^1.0.3",
+ "parseurl": "^1.3.3",
+ "send": "^1.2.0"
+ },
+ "engines": {
+ "node": ">= 18"
+ }
+ },
"node_modules/set-blocking": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/set-blocking/-/set-blocking-2.0.0.tgz",
@@ -14022,15 +14520,65 @@
}
},
"node_modules/side-channel": {
- "version": "1.0.6",
- "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.0.6.tgz",
- "integrity": "sha512-fDW/EZ6Q9RiO8eFG8Hj+7u/oW+XrPTIChwCOM2+th2A6OblDtYYIpve9m+KvI9Z4C9qSEXlaGR6bTEYHReuglA==",
- "peer": true,
+ "version": "1.1.0",
+ "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.1.0.tgz",
+ "integrity": "sha512-ZX99e6tRweoUXqR+VBrslhda51Nh5MTQwou5tnUDgbtyM0dBgmhEDtWGP/xbKn6hqfPRHujUNwz5fy/wbbhnpw==",
"dependencies": {
- "call-bind": "^1.0.7",
"es-errors": "^1.3.0",
- "get-intrinsic": "^1.2.4",
- "object-inspect": "^1.13.1"
+ "object-inspect": "^1.13.3",
+ "side-channel-list": "^1.0.0",
+ "side-channel-map": "^1.0.1",
+ "side-channel-weakmap": "^1.0.2"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/side-channel-list": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/side-channel-list/-/side-channel-list-1.0.0.tgz",
+ "integrity": "sha512-FCLHtRD/gnpCiCHEiJLOwdmFP+wzCmDEkc9y7NsYxeF4u7Btsn1ZuwgwJGxImImHicJArLP4R0yX4c2KCrMrTA==",
+ "dependencies": {
+ "es-errors": "^1.3.0",
+ "object-inspect": "^1.13.3"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/side-channel-map": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/side-channel-map/-/side-channel-map-1.0.1.tgz",
+ "integrity": "sha512-VCjCNfgMsby3tTdo02nbjtM/ewra6jPHmpThenkTYh8pG9ucZ/1P8So4u4FGBek/BjpOVsDCMoLA/iuBKIFXRA==",
+ "dependencies": {
+ "call-bound": "^1.0.2",
+ "es-errors": "^1.3.0",
+ "get-intrinsic": "^1.2.5",
+ "object-inspect": "^1.13.3"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/side-channel-weakmap": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmjs.org/side-channel-weakmap/-/side-channel-weakmap-1.0.2.tgz",
+ "integrity": "sha512-WPS/HvHQTYnHisLo9McqBHOJk2FkHO/tlpvldyrnem4aeQp4hai3gythswg6p01oSoTl58rcpiFAjF2br2Ak2A==",
+ "dependencies": {
+ "call-bound": "^1.0.2",
+ "es-errors": "^1.3.0",
+ "get-intrinsic": "^1.2.5",
+ "object-inspect": "^1.13.3",
+ "side-channel-map": "^1.0.1"
},
"engines": {
"node": ">= 0.4"
@@ -15106,6 +15654,38 @@
"url": "https://github.com/sponsors/sindresorhus"
}
},
+ "node_modules/type-is": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/type-is/-/type-is-2.0.1.tgz",
+ "integrity": "sha512-OZs6gsjF4vMp32qrCbiVSkrFmXtG/AZhY3t0iAMrMBiAZyV9oALtXO8hsrHbMXF9x6L3grlFuwW2oAz7cav+Gw==",
+ "dependencies": {
+ "content-type": "^1.0.5",
+ "media-typer": "^1.1.0",
+ "mime-types": "^3.0.0"
+ },
+ "engines": {
+ "node": ">= 0.6"
+ }
+ },
+ "node_modules/type-is/node_modules/mime-db": {
+ "version": "1.54.0",
+ "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.54.0.tgz",
+ "integrity": "sha512-aU5EJuIN2WDemCcAp2vFBfp/m4EAhWJnUNSSw0ixs7/kXbd6Pg64EmwJkNdFhB8aWt1sH2CTXrLxo/iAGV3oPQ==",
+ "engines": {
+ "node": ">= 0.6"
+ }
+ },
+ "node_modules/type-is/node_modules/mime-types": {
+ "version": "3.0.1",
+ "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-3.0.1.tgz",
+ "integrity": "sha512-xRc4oEhT6eaBpU1XF7AjpOFD+xQmXNB5OVKwp4tqCuBpHLS/ZbBDrc07mYTDqVMg6PfxUjjNp85O6Cd2Z/5HWA==",
+ "dependencies": {
+ "mime-db": "^1.54.0"
+ },
+ "engines": {
+ "node": ">= 0.6"
+ }
+ },
"node_modules/typed-array-buffer": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/typed-array-buffer/-/typed-array-buffer-1.0.2.tgz",
@@ -15266,9 +15846,9 @@
}
},
"node_modules/undici": {
- "version": "6.21.1",
- "resolved": "https://registry.npmjs.org/undici/-/undici-6.21.1.tgz",
- "integrity": "sha512-q/1rj5D0/zayJB2FraXdaWxbhWiNKDvu8naDT2dl1yTlvJp4BLtOcp2a5BvgGNQpYYJzau7tf1WgKv3b+7mqpQ==",
+ "version": "6.21.3",
+ "resolved": "https://registry.npmjs.org/undici/-/undici-6.21.3.tgz",
+ "integrity": "sha512-gBLkYIlEnSp8pFbT64yFgGE6UIB9tAkhukC23PmMDCe5Nd+cRqKxSjw5y54MK2AZMgZfJWMaNE4nYUHgi1XEOw==",
"license": "MIT",
"engines": {
"node": ">=18.17"
@@ -15441,6 +16021,14 @@
"node": ">=10.12.0"
}
},
+ "node_modules/vary": {
+ "version": "1.1.2",
+ "resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz",
+ "integrity": "sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg==",
+ "engines": {
+ "node": ">= 0.8"
+ }
+ },
"node_modules/vectordb": {
"version": "0.4.20",
"resolved": "https://registry.npmjs.org/vectordb/-/vectordb-0.4.20.tgz",
@@ -15922,6 +16510,14 @@
"node": ">=18"
}
},
+ "node_modules/xmlbuilder": {
+ "version": "15.1.1",
+ "resolved": "https://registry.npmjs.org/xmlbuilder/-/xmlbuilder-15.1.1.tgz",
+ "integrity": "sha512-yMqGBqtXyeN1e3TGYvgNgDVZ3j84W4cwkOXQswghol6APgZWaff9lnbvN7MHYJOiXsvGPXtjTYJEiC9J2wv9Eg==",
+ "engines": {
+ "node": ">=8.0"
+ }
+ },
"node_modules/xmlchars": {
"version": "2.2.0",
"resolved": "https://registry.npmjs.org/xmlchars/-/xmlchars-2.2.0.tgz",
diff --git a/core/package.json b/core/package.json
index 9332baa21..5622cc903 100644
--- a/core/package.json
+++ b/core/package.json
@@ -27,6 +27,7 @@
"@types/mustache": "^4.2.5",
"@types/node-fetch": "^2.6.11",
"@types/pg": "^8.11.6",
+ "@types/plist": "^3.0.5",
"@types/request": "^2.48.12",
"@types/tar": "^6.1.13",
"@types/uuid": "^9.0.7",
@@ -48,10 +49,10 @@
"@aws-sdk/credential-providers": "^3.778.0",
"@continuedev/config-types": "^1.0.13",
"@continuedev/config-yaml": "file:../packages/config-yaml",
- "@continuedev/fetch": "^1.0.6",
+ "@continuedev/fetch": "^1.0.10",
"@continuedev/llm-info": "^1.0.8",
- "@continuedev/openai-adapters": "^1.0.19",
- "@modelcontextprotocol/sdk": "^1.5.0",
+ "@continuedev/openai-adapters": "^1.0.25",
+ "@modelcontextprotocol/sdk": "^1.12.0",
"@mozilla/readability": "^0.5.0",
"@octokit/rest": "^20.1.1",
"@typescript-eslint/eslint-plugin": "^7.8.0",
@@ -89,6 +90,7 @@
"p-limit": "^6.1.0",
"partial-json": "^0.1.7",
"pg": "^8.11.3",
+ "plist": "^3.1.0",
"posthog-node": "^3.6.3",
"puppeteer": "^22.4.0",
"puppeteer-chromium-resolver": "^23.0.0",
diff --git a/core/promptFiles/v1/slashCommandFromPromptFile.ts b/core/promptFiles/v1/slashCommandFromPromptFile.ts
index a934b2586..7f478e623 100644
--- a/core/promptFiles/v1/slashCommandFromPromptFile.ts
+++ b/core/promptFiles/v1/slashCommandFromPromptFile.ts
@@ -63,6 +63,7 @@ export function slashCommandFromPromptFileV1(
name,
description,
prompt,
+ promptFile: path,
run: async function* (context) {
const userInput = extractUserInput(context.input, name);
const [_, renderedPrompt] = await renderPromptFileV2(prompt, {
diff --git a/core/protocol/core.ts b/core/protocol/core.ts
index de061c730..142764d19 100644
--- a/core/protocol/core.ts
+++ b/core/protocol/core.ts
@@ -9,7 +9,7 @@ import { AutocompleteInput } from "../autocomplete/util/types";
import { SharedConfigSchema } from "../config/sharedConfig";
import { GlobalContextModelSelections } from "../util/GlobalContext";
-import type {
+import {
BrowserSerializedContinueConfig,
ChatMessage,
ContextItem,
@@ -29,10 +29,11 @@ import type {
SessionMetadata,
SiteIndexingConfig,
SlashCommandDescription,
+ StreamDiffLinesPayload,
ToolCall,
} from "../";
import { SerializedOrgWithProfiles } from "../config/ProfileLifecycleManager";
-import { ControlPlaneSessionInfo } from "../control-plane/client";
+import { ControlPlaneSessionInfo } from "../control-plane/AuthTypes";
export type OnboardingModes = "Local" | "Best" | "Custom" | "Quickstart";
@@ -45,6 +46,7 @@ export type ToCoreFromIdeOrWebviewProtocol = {
// Special
ping: [string, string];
abort: [undefined, void];
+ cancelApply: [undefined, void];
// History
"history/list": [ListHistoryOptions, SessionMetadata[]];
@@ -142,18 +144,7 @@ export type ToCoreFromIdeOrWebviewProtocol = {
},
AsyncGenerator,
];
- streamDiffLines: [
- {
- prefix: string;
- highlighted: string;
- suffix: string;
- input: string;
- language: string | undefined;
- modelTitle: string | undefined;
- includeRulesInSystemMessage: boolean;
- },
- AsyncGenerator,
- ];
+ streamDiffLines: [StreamDiffLinesPayload, AsyncGenerator];
"chatDescriber/describe": [
{
text: string;
diff --git a/core/protocol/ide.ts b/core/protocol/ide.ts
index 88e7f779c..324772ace 100644
--- a/core/protocol/ide.ts
+++ b/core/protocol/ide.ts
@@ -1,5 +1,3 @@
-import { ControlPlaneSessionInfo } from "../control-plane/client";
-
import type {
ContinueRcJson,
DiffLine,
@@ -16,6 +14,7 @@ import type {
TerminalOptions,
Thread,
} from "../";
+import { ControlPlaneSessionInfo } from "../control-plane/AuthTypes";
export interface GetGhTokenArgs {
force?: boolean;
@@ -99,7 +98,7 @@ export type ToIdeFromWebviewOrCoreProtocol = {
ControlPlaneSessionInfo | undefined,
];
logoutOfControlPlane: [undefined, void];
- reportError:[any, void];
+ reportError: [any, void];
closeSidebar: [undefined, void];
};
diff --git a/core/protocol/ideWebview.ts b/core/protocol/ideWebview.ts
index 17c09a348..540f8a7e3 100644
--- a/core/protocol/ideWebview.ts
+++ b/core/protocol/ideWebview.ts
@@ -1,11 +1,14 @@
import { ToIdeFromWebviewOrCoreProtocol } from "./ide";
import { ToWebviewFromIdeOrCoreProtocol } from "./webview";
-import type {
+import {
+ AcceptOrRejectDiffPayload,
ApplyState,
- CodeToEdit,
+ HighlightedCodePayload,
MessageContent,
RangeInFileWithContents,
+ SetCodeToEditPayload,
+ ShowFilePayload,
} from "../";
export type ToIdeFromWebviewProtocol = ToIdeFromWebviewOrCoreProtocol & {
@@ -21,7 +24,7 @@ export type ToIdeFromWebviewProtocol = ToIdeFromWebviewOrCoreProtocol & {
];
overwriteFile: [{ filepath: string; prevFileContent: string | null }, void];
showTutorial: [undefined, void];
- showFile: [{ filepath: string }, void];
+ showFile: [ShowFilePayload, void];
toggleDevTools: [undefined, void];
reloadWindow: [undefined, void];
focusEditor: [undefined, void];
@@ -39,11 +42,11 @@ export type ToIdeFromWebviewProtocol = ToIdeFromWebviewOrCoreProtocol & {
vscMediaUrl: string;
},
];
- "jetbrains/getColors": [undefined, Record];
+ "jetbrains/getColors": [undefined, Record];
"vscode/openMoveRightMarkdown": [undefined, void];
setGitHubAuthToken: [{ token: string }, void];
- acceptDiff: [{ filepath: string; streamId?: string }, void];
- rejectDiff: [{ filepath: string; streamId?: string }, void];
+ acceptDiff: [AcceptOrRejectDiffPayload, void];
+ rejectDiff: [AcceptOrRejectDiffPayload, void];
"edit/sendPrompt": [
{
prompt: MessageContent;
@@ -63,15 +66,8 @@ export type ToWebviewFromIdeProtocol = ToWebviewFromIdeOrCoreProtocol & {
focusContinueInput: [undefined, void];
focusContinueInputWithoutClear: [undefined, void];
focusContinueInputWithNewSession: [undefined, void];
- highlightedCode: [
- {
- rangeInFileWithContents: RangeInFileWithContents;
- prompt?: string;
- shouldRun?: boolean;
- },
- void,
- ];
- setCodeToEdit: [CodeToEdit, void];
+ highlightedCode: [HighlightedCodePayload, void];
+ setCodeToEdit: [SetCodeToEditPayload, void];
navigateTo: [{ path: string; toggle?: boolean }, void];
addModel: [undefined, void];
diff --git a/core/protocol/webview.ts b/core/protocol/webview.ts
index 2e6ec3cff..5ba47e3d4 100644
--- a/core/protocol/webview.ts
+++ b/core/protocol/webview.ts
@@ -1,6 +1,6 @@
import { ConfigResult } from "@continuedev/config-yaml";
import { SerializedOrgWithProfiles } from "../config/ProfileLifecycleManager.js";
-import { ControlPlaneSessionInfo } from "../control-plane/client.js";
+import { ControlPlaneSessionInfo } from "../control-plane/AuthTypes.js";
import type {
BrowserSerializedContinueConfig,
ContextItemWithId,
@@ -40,7 +40,7 @@ export type ToWebviewFromIdeOrCoreProtocol = {
setTTSActive: [boolean, void];
getWebviewHistoryLength: [undefined, number];
getCurrentSessionId: [undefined, string];
- "jetbrains/setColors": [Record, void];
+ "jetbrains/setColors": [Record, void];
sessionUpdate: [{ sessionInfo: ControlPlaneSessionInfo | undefined }, void];
toolCallPartialOutput: [{ toolCallId: string; contextItems: any[] }, void];
};
diff --git a/core/test/testDir.ts b/core/test/testDir.ts
index 0e34f509b..315f4d60e 100644
--- a/core/test/testDir.ts
+++ b/core/test/testDir.ts
@@ -43,7 +43,7 @@ export function addToTestDir(pathsOrUris: (string | [string, string])[]) {
if (Array.isArray(p)) {
fs.writeFileSync(filepath, p[1]);
} else if (p.endsWith("/")) {
- fs.mkdirSync(p, { recursive: true });
+ fs.mkdirSync(filepath, { recursive: true });
} else {
fs.writeFileSync(filepath, "");
}
diff --git a/core/tools/builtIn.ts b/core/tools/builtIn.ts
index 9f70b1a22..892cc3ff8 100644
--- a/core/tools/builtIn.ts
+++ b/core/tools/builtIn.ts
@@ -10,6 +10,7 @@ export enum BuiltInToolNames {
ViewDiff = "builtin_view_diff",
LSTool = "builtin_ls",
CreateRuleBlock = "builtin_create_rule_block",
+ RequestRule = "builtin_request_rule",
// excluded from allTools for now
ViewRepoMap = "builtin_view_repo_map",
@@ -18,4 +19,4 @@ export enum BuiltInToolNames {
export const BUILT_IN_GROUP_NAME = "Built-In";
-export const CLIENT_TOOLS = [BuiltInToolNames.EditExistingFile];
+export const CLIENT_TOOLS_IMPLS = [BuiltInToolNames.EditExistingFile];
diff --git a/core/tools/callTool.ts b/core/tools/callTool.ts
index d8eaf4ffd..243c162bb 100644
--- a/core/tools/callTool.ts
+++ b/core/tools/callTool.ts
@@ -10,6 +10,7 @@ import { grepSearchImpl } from "./implementations/grepSearch";
import { lsToolImpl } from "./implementations/lsTool";
import { readCurrentlyOpenFileImpl } from "./implementations/readCurrentlyOpenFile";
import { readFileImpl } from "./implementations/readFile";
+import { requestRuleImpl } from "./implementations/requestRule";
import { runTerminalCommandImpl } from "./implementations/runTerminalCommand";
import { searchWebImpl } from "./implementations/searchWeb";
import { viewDiffImpl } from "./implementations/viewDiff";
@@ -29,11 +30,12 @@ async function callHttpTool(
}),
});
+ const data = await response.json();
+
if (!response.ok) {
- throw new Error(`Failed to call tool: ${url}`);
+ throw new Error(`Failed to call tool at ${url}:\n${JSON.stringify(data)}`);
}
- const data = await response.json();
return data.output;
}
@@ -84,7 +86,7 @@ async function callToolFromUri(
});
if (response.isError === true) {
- throw new Error(`Failed to call tool: ${toolName}`);
+ throw new Error(JSON.stringify(response.content));
}
const contextItems: ContextItem[] = [];
@@ -130,6 +132,39 @@ async function callToolFromUri(
}
}
+async function callBuiltInTool(
+ functionName: string,
+ args: any,
+ extras: ToolExtras,
+): Promise {
+ switch (functionName) {
+ case BuiltInToolNames.ReadFile:
+ return await readFileImpl(args, extras);
+ case BuiltInToolNames.CreateNewFile:
+ return await createNewFileImpl(args, extras);
+ case BuiltInToolNames.GrepSearch:
+ return await grepSearchImpl(args, extras);
+ case BuiltInToolNames.FileGlobSearch:
+ return await fileGlobSearchImpl(args, extras);
+ case BuiltInToolNames.RunTerminalCommand:
+ return await runTerminalCommandImpl(args, extras);
+ case BuiltInToolNames.SearchWeb:
+ return await searchWebImpl(args, extras);
+ case BuiltInToolNames.ViewDiff:
+ return await viewDiffImpl(args, extras);
+ case BuiltInToolNames.LSTool:
+ return await lsToolImpl(args, extras);
+ case BuiltInToolNames.ReadCurrentlyOpenFile:
+ return await readCurrentlyOpenFileImpl(args, extras);
+ case BuiltInToolNames.CreateRuleBlock:
+ return await createRuleBlockImpl(args, extras);
+ case BuiltInToolNames.RequestRule:
+ return await requestRuleImpl(args, extras);
+ default:
+ throw new Error(`Tool "${functionName}" not found`);
+ }
+}
+
// Handles calls for core/non-client tools
// Returns an error context item if the tool call fails
// Note: Edit tool is handled on client
@@ -141,44 +176,11 @@ export async function callTool(
contextItems: ContextItem[];
errorMessage: string | undefined;
}> {
- const args = JSON.parse(callArgs || "{}");
- const uri = tool.uri ?? tool.function.name;
try {
- let contextItems: ContextItem[] = [];
- switch (uri) {
- case BuiltInToolNames.ReadFile:
- contextItems = await readFileImpl(args, extras);
- break;
- case BuiltInToolNames.CreateNewFile:
- contextItems = await createNewFileImpl(args, extras);
- break;
- case BuiltInToolNames.GrepSearch:
- contextItems = await grepSearchImpl(args, extras);
- break;
- case BuiltInToolNames.FileGlobSearch:
- contextItems = await fileGlobSearchImpl(args, extras);
- break;
- case BuiltInToolNames.RunTerminalCommand:
- contextItems = await runTerminalCommandImpl(args, extras);
- break;
- case BuiltInToolNames.SearchWeb:
- contextItems = await searchWebImpl(args, extras);
- break;
- case BuiltInToolNames.ViewDiff:
- contextItems = await viewDiffImpl(args, extras);
- break;
- case BuiltInToolNames.LSTool:
- contextItems = await lsToolImpl(args, extras);
- break;
- case BuiltInToolNames.ReadCurrentlyOpenFile:
- contextItems = await readCurrentlyOpenFileImpl(args, extras);
- break;
- case BuiltInToolNames.CreateRuleBlock:
- contextItems = await createRuleBlockImpl(args, extras);
- break;
- default:
- contextItems = await callToolFromUri(uri, args, extras);
- }
+ const args = JSON.parse(callArgs || "{}");
+ const contextItems = tool.uri
+ ? await callToolFromUri(tool.uri, args, extras)
+ : await callBuiltInTool(tool.function.name, args, extras);
if (tool.faviconUrl) {
contextItems.forEach((item) => {
item.icon = tool.faviconUrl;
diff --git a/core/tools/definitions/createRuleBlock.ts b/core/tools/definitions/createRuleBlock.ts
index c3a0846f4..011ab4985 100644
--- a/core/tools/definitions/createRuleBlock.ts
+++ b/core/tools/definitions/createRuleBlock.ts
@@ -13,10 +13,10 @@ export const createRuleBlock: Tool = {
function: {
name: BuiltInToolNames.CreateRuleBlock,
description:
- "Creates a persistent rule for all future conversations. For establishing code standards or preferences that should be applied consistently.",
+ "Creates a persistent rule for all future conversations. For establishing code standards or preferences that should be applied consistently. To modify existing rules, use the edit tool instead.",
parameters: {
type: "object",
- required: ["name", "rule"],
+ required: ["name", "rule", "alwaysApply", "description"],
properties: {
name: {
type: "string",
@@ -28,11 +28,20 @@ export const createRuleBlock: Tool = {
description:
"Clear, imperative instruction for future code generation (e.g. 'Use named exports', 'Add Python type hints'). Each rule should focus on one specific standard.",
},
+ description: {
+ type: "string",
+ description: "Short description of the rule",
+ },
globs: {
type: "string",
description:
"Optional file patterns to which this rule applies (e.g. ['**/*.{ts,tsx}'] or ['src/**/*.ts', 'tests/**/*.ts'])",
},
+ alwaysApply: {
+ type: "boolean",
+ description:
+ "Whether this rule should always be applied regardless of file pattern matching",
+ },
},
},
},
diff --git a/core/tools/definitions/globSearch.ts b/core/tools/definitions/globSearch.ts
index 3cbc43d52..5c2375124 100644
--- a/core/tools/definitions/globSearch.ts
+++ b/core/tools/definitions/globSearch.ts
@@ -6,7 +6,7 @@ export const globSearchTool: Tool = {
displayTitle: "Glob File Search",
wouldLikeTo: 'find file matches for "{{{ pattern }}}"',
isCurrently: 'finding file matches for "{{{ pattern }}}"',
- hasAlready: 'retreived file matches for "{{{ pattern }}}"',
+ hasAlready: 'retrieved file matches for "{{{ pattern }}}"',
readonly: true,
isInstant: true,
group: BUILT_IN_GROUP_NAME,
diff --git a/core/tools/definitions/requestRule.test.ts b/core/tools/definitions/requestRule.test.ts
new file mode 100644
index 000000000..e1d0feb81
--- /dev/null
+++ b/core/tools/definitions/requestRule.test.ts
@@ -0,0 +1,237 @@
+import { RuleWithSource } from "../..";
+import { getRequestRuleDescription } from "./requestRule";
+
+describe("getRequestRuleDescription", () => {
+ it("should return no rules message when no agent-requested rules exist", () => {
+ const rules: RuleWithSource[] = [
+ {
+ name: "Always Apply Rule",
+ description: "This rule always applies",
+ source: "default-chat",
+ rule: "Always use semicolons",
+ alwaysApply: true,
+ ruleFile: "/path/to/rule1.md",
+ },
+ {
+ name: "Rule with Globs",
+ description: "This rule has globs",
+ source: "rules-block",
+ rule: "Use TypeScript",
+ globs: "**/*.ts",
+ ruleFile: "/path/to/rule2.md",
+ },
+ ];
+
+ const result = getRequestRuleDescription(rules);
+
+ expect(result).toBe(
+ "Use this tool to select additional rules, specifically based on their descriptions. Available rules:\nNo rules available.",
+ );
+ });
+
+ it("should return formatted rules when agent-requested rules exist", () => {
+ const rules: RuleWithSource[] = [
+ {
+ name: "Agent Rule 1",
+ description: "First agent-requested rule",
+ source: "rules-block",
+ rule: "Use consistent formatting",
+ alwaysApply: false,
+ ruleFile: "/path/to/agent-rule1.md",
+ },
+ {
+ name: "Agent Rule 2",
+ description: "Second agent-requested rule",
+ source: "default-agent",
+ rule: "Follow naming conventions",
+ alwaysApply: false,
+ ruleFile: "/path/to/agent-rule2.md",
+ },
+ // These should be filtered out
+ {
+ name: "Always Apply Rule",
+ description: "This rule always applies",
+ source: "default-chat",
+ rule: "Always use semicolons",
+ alwaysApply: true,
+ ruleFile: "/path/to/rule1.md",
+ },
+ {
+ name: "Rule with Globs",
+ description: "This rule has globs",
+ source: "rules-block",
+ rule: "Use TypeScript",
+ globs: "**/*.ts",
+ ruleFile: "/path/to/rule2.md",
+ },
+ ];
+
+ const result = getRequestRuleDescription(rules);
+
+ const expected =
+ "Use this tool to select additional rules, specifically based on their descriptions. Available rules:\n" +
+ "Agent Rule 1: First agent-requested rule\n" +
+ "Agent Rule 2: Second agent-requested rule";
+
+ expect(result).toBe(expected);
+ });
+
+ it("should handle rules with missing description", () => {
+ const rules: RuleWithSource[] = [
+ {
+ name: "Rule Without Description",
+ source: "rules-block",
+ rule: "Some rule content",
+ alwaysApply: false,
+ ruleFile: "/path/to/no-desc-rule.md",
+ },
+ ];
+
+ const result = getRequestRuleDescription(rules);
+
+ const expected =
+ "Use this tool to select additional rules, specifically based on their descriptions. Available rules:\n" +
+ "Rule Without Description: undefined";
+
+ expect(result).toBe(expected);
+ });
+
+ it("should handle rules with missing name", () => {
+ const rules: RuleWithSource[] = [
+ {
+ description: "Rule without name",
+ source: "rules-block",
+ rule: "Some rule content",
+ alwaysApply: false,
+ ruleFile: "/path/to/no-name-rule.md",
+ },
+ ];
+
+ const result = getRequestRuleDescription(rules);
+
+ const expected =
+ "Use this tool to select additional rules, specifically based on their descriptions. Available rules:\n" +
+ "undefined: Rule without name";
+
+ expect(result).toBe(expected);
+ });
+
+ it("should handle rules with missing ruleFile", () => {
+ const rules: RuleWithSource[] = [
+ {
+ name: "Rule Without File",
+ description: "Rule without file path",
+ source: "rules-block",
+ rule: "Some rule content",
+ alwaysApply: false,
+ },
+ ];
+
+ const result = getRequestRuleDescription(rules);
+
+ const expected =
+ "Use this tool to select additional rules, specifically based on their descriptions. Available rules:\n" +
+ "Rule Without File: Rule without file path";
+
+ expect(result).toBe(expected);
+ });
+
+ it("should filter out rules with alwaysApply undefined (truthy)", () => {
+ const rules: RuleWithSource[] = [
+ {
+ name: "Rule with undefined alwaysApply",
+ description: "This should be filtered out",
+ source: "rules-block",
+ rule: "Some rule",
+ ruleFile: "/path/to/rule.md",
+ // alwaysApply is undefined, which is truthy in the filter condition
+ },
+ {
+ name: "Valid Agent Rule",
+ description: "This should be included",
+ source: "rules-block",
+ rule: "Some rule",
+ alwaysApply: false,
+ ruleFile: "/path/to/valid-rule.md",
+ },
+ ];
+
+ const result = getRequestRuleDescription(rules);
+
+ const expected =
+ "Use this tool to select additional rules, specifically based on their descriptions. Available rules:\n" +
+ "Valid Agent Rule: This should be included";
+
+ expect(result).toBe(expected);
+ });
+
+ it("should filter out rules with any globs defined", () => {
+ const rules: RuleWithSource[] = [
+ {
+ name: "Rule with string globs",
+ description: "This should be filtered out",
+ source: "rules-block",
+ rule: "Some rule",
+ alwaysApply: false,
+ globs: "**/*.ts",
+ ruleFile: "/path/to/rule1.md",
+ },
+ {
+ name: "Rule with array globs",
+ description: "This should also be filtered out",
+ source: "rules-block",
+ rule: "Some rule",
+ alwaysApply: false,
+ globs: ["**/*.ts", "**/*.js"],
+ ruleFile: "/path/to/rule2.md",
+ },
+ {
+ name: "Valid Agent Rule",
+ description: "This should be included",
+ source: "rules-block",
+ rule: "Some rule",
+ alwaysApply: false,
+ ruleFile: "/path/to/valid-rule.md",
+ },
+ ];
+
+ const result = getRequestRuleDescription(rules);
+
+ const expected =
+ "Use this tool to select additional rules, specifically based on their descriptions. Available rules:\n" +
+ "Valid Agent Rule: This should be included";
+
+ expect(result).toBe(expected);
+ });
+
+ it("should handle empty rules array", () => {
+ const rules: RuleWithSource[] = [];
+
+ const result = getRequestRuleDescription(rules);
+
+ expect(result).toBe(
+ "Use this tool to select additional rules, specifically based on their descriptions. Available rules:\nNo rules available.",
+ );
+ });
+
+ it("should handle single agent-requested rule", () => {
+ const rules: RuleWithSource[] = [
+ {
+ name: "Single Rule",
+ description: "The only agent-requested rule",
+ source: "rules-block",
+ rule: "Follow this guideline",
+ alwaysApply: false,
+ ruleFile: "/path/to/single-rule.md",
+ },
+ ];
+
+ const result = getRequestRuleDescription(rules);
+
+ const expected =
+ "Use this tool to select additional rules, specifically based on their descriptions. Available rules:\n" +
+ "Single Rule: The only agent-requested rule";
+
+ expect(result).toBe(expected);
+ });
+});
diff --git a/core/tools/definitions/requestRule.ts b/core/tools/definitions/requestRule.ts
new file mode 100644
index 000000000..cb60cda73
--- /dev/null
+++ b/core/tools/definitions/requestRule.ts
@@ -0,0 +1,52 @@
+import { ConfigDependentToolParams, GetTool } from "../..";
+import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn";
+
+export interface RequestRuleArgs {
+ name: string;
+}
+
+export function getRequestRuleDescription(
+ rules: ConfigDependentToolParams["rules"],
+): string {
+ // Must be explicitly false and no globs
+ const agentRequestedRules = rules.filter(
+ (rule) => rule.alwaysApply === false && !rule.globs,
+ );
+
+ const prefix =
+ "Use this tool to select additional rules, specifically based on their descriptions. Available rules:\n";
+
+ const body = agentRequestedRules
+ .map((rule) => `${rule.name}: ${rule.description}`)
+ .join("\n");
+
+ if (body.length === 0) {
+ return prefix + "No rules available.";
+ }
+
+ return prefix + body;
+}
+
+export const requestRuleTool: GetTool = ({ rules }) => ({
+ type: "function",
+ displayTitle: "Request Rules",
+ wouldLikeTo: "request rule {{{ name }}}",
+ isCurrently: "reading rule {{{ name }}}",
+ hasAlready: "read rule {{{ name }}}",
+ group: BUILT_IN_GROUP_NAME,
+ readonly: false,
+ function: {
+ name: BuiltInToolNames.RequestRule,
+ description: getRequestRuleDescription(rules),
+ parameters: {
+ type: "object",
+ required: ["name"],
+ properties: {
+ name: {
+ type: "string",
+ description: "Name of the rule",
+ },
+ },
+ },
+ },
+});
diff --git a/core/tools/definitions/runTerminalCommand.ts b/core/tools/definitions/runTerminalCommand.ts
index 73d326902..d194205e9 100644
--- a/core/tools/definitions/runTerminalCommand.ts
+++ b/core/tools/definitions/runTerminalCommand.ts
@@ -1,6 +1,27 @@
import { Tool } from "../..";
import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn";
+import os from 'os';
+
+/**
+ * Get the preferred shell for the current platform
+ * @returns The preferred shell command or path
+ */
+export function getPreferredShell(): string {
+ const platform = os.platform();
+
+ if (platform === 'win32') {
+ return process.env.COMSPEC || 'cmd.exe';
+ } else if (platform === 'darwin') {
+ return process.env.SHELL || '/bin/zsh';
+ } else {
+ // Linux and other Unix-like systems
+ return process.env.SHELL || '/bin/bash';
+ }
+}
+
+export const PLATFORM_INFO = `Choose terminal commands and scripts optimized for ${os.platform} and ${os.arch} and shell ${getPreferredShell()}.`
+
export const runTerminalCommandTool: Tool = {
type: "function",
displayTitle: "Run Terminal Command",
@@ -12,11 +33,12 @@ export const runTerminalCommandTool: Tool = {
function: {
name: BuiltInToolNames.RunTerminalCommand,
description:
- "Run a terminal command in the current directory.\
+ `Run a terminal command in the current directory.\
The shell is not stateful and will not remember any previous commands.\
When a command is run in the background ALWAYS suggest using shell commands to stop it; NEVER suggest using Ctrl+C.\
When suggesting subsequent shell commands ALWAYS format them in shell command blocks.\
- Do NOT perform actions requiring special/admin privileges.",
+ Do NOT perform actions requiring special/admin privileges.\
+ ${PLATFORM_INFO}`,
parameters: {
type: "object",
required: ["command"],
diff --git a/core/tools/implementations/createRuleBlock.test.ts b/core/tools/implementations/createRuleBlock.test.ts
index 0491b8e26..4a789143c 100644
--- a/core/tools/implementations/createRuleBlock.test.ts
+++ b/core/tools/implementations/createRuleBlock.test.ts
@@ -1,4 +1,4 @@
-import * as YAML from "yaml";
+import { parseMarkdownRule } from "../../config/markdown/parseMarkdownRule";
import { createRuleBlockImpl } from "./createRuleBlock";
// Mock the extras parameter with necessary functions
@@ -17,33 +17,6 @@ describe("createRuleBlockImpl", () => {
jest.clearAllMocks();
});
- it("should create a basic rule with name and rule content", async () => {
- const args = {
- name: "Test Rule",
- rule: "Always write tests",
- };
-
- const result = await createRuleBlockImpl(args, mockExtras as any);
-
- // Verify that writeFile was called with the correct YAML
- expect(mockIde.writeFile).toHaveBeenCalled();
- const yamlContent = mockIde.writeFile.mock.calls[0][1];
- const parsedYaml = YAML.parse(yamlContent);
-
- // Verify the structure of the YAML
- expect(parsedYaml).toEqual({
- name: "Test Rule",
- version: "0.0.1",
- schema: "v1",
- rules: [
- {
- name: "Test Rule",
- rule: "Always write tests",
- },
- ],
- });
- });
-
it("should create a rule with glob pattern", async () => {
const args = {
name: "TypeScript Rule",
@@ -53,14 +26,16 @@ describe("createRuleBlockImpl", () => {
await createRuleBlockImpl(args, mockExtras as any);
- // Verify the YAML structure with globs
- const yamlContent = mockIde.writeFile.mock.calls[0][1];
- const parsedYaml = YAML.parse(yamlContent);
- expect(parsedYaml.rules[0]).toEqual({
- name: "TypeScript Rule",
- rule: "Use interfaces for object shapes",
+ const fileContent = mockIde.writeFile.mock.calls[0][1];
+
+ const { frontmatter, markdown } = parseMarkdownRule(fileContent);
+
+ expect(frontmatter).toEqual({
globs: "**/*.{ts,tsx}",
});
+
+ expect(markdown).toContain("# TypeScript Rule");
+ expect(markdown).toContain("Use interfaces for object shapes");
});
it("should create a filename based on sanitized rule name", async () => {
@@ -71,8 +46,69 @@ describe("createRuleBlockImpl", () => {
await createRuleBlockImpl(args, mockExtras as any);
- // Check that the filename is sanitized
const fileUri = mockIde.writeFile.mock.calls[0][0];
- expect(fileUri).toContain("special-chracters-spaces.yaml");
+ expect(fileUri).toContain("special-chracters-spaces.md");
+ });
+
+ it("should create a rule with description pattern", async () => {
+ const args = {
+ name: "Description Test",
+ rule: "This is the rule content",
+ description: "This is a detailed explanation of the rule",
+ };
+
+ await createRuleBlockImpl(args, mockExtras as any);
+
+ const fileContent = mockIde.writeFile.mock.calls[0][1];
+
+ const { frontmatter, markdown } = parseMarkdownRule(fileContent);
+
+ expect(frontmatter).toEqual({
+ description: "This is a detailed explanation of the rule",
+ });
+
+ expect(markdown).toContain("# Description Test");
+ expect(markdown).toContain("This is the rule content");
+ });
+
+ it("should include both globs and description in frontmatter", async () => {
+ const args = {
+ name: "Complete Rule",
+ rule: "Follow this standard",
+ description: "This rule enforces our team standards",
+ globs: "**/*.js",
+ };
+
+ await createRuleBlockImpl(args, mockExtras as any);
+
+ const fileContent = mockIde.writeFile.mock.calls[0][1];
+
+ const { frontmatter, markdown } = parseMarkdownRule(fileContent);
+
+ expect(frontmatter).toEqual({
+ description: "This rule enforces our team standards",
+ globs: "**/*.js",
+ });
+
+ expect(markdown).toContain("# Complete Rule");
+ expect(markdown).toContain("Follow this standard");
+ });
+
+ it("should create a rule with alwaysApply set to false", async () => {
+ const args = {
+ name: "Conditional Rule",
+ rule: "This rule should not always be applied",
+ alwaysApply: false,
+ };
+
+ await createRuleBlockImpl(args, mockExtras as any);
+
+ const fileContent = mockIde.writeFile.mock.calls[0][1];
+
+ const { frontmatter } = parseMarkdownRule(fileContent);
+
+ expect(frontmatter).toEqual({
+ alwaysApply: false,
+ });
});
});
diff --git a/core/tools/implementations/createRuleBlock.ts b/core/tools/implementations/createRuleBlock.ts
index 87702e866..0d2d58f68 100644
--- a/core/tools/implementations/createRuleBlock.ts
+++ b/core/tools/implementations/createRuleBlock.ts
@@ -1,13 +1,14 @@
-import { ConfigYaml } from "@continuedev/config-yaml";
import * as YAML from "yaml";
import { ToolImpl } from ".";
+import { RuleWithSource } from "../..";
+import { RuleFrontmatter } from "../../config/markdown/parseMarkdownRule";
import { joinPathsToUri } from "../../util/uri";
-export interface CreateRuleBlockArgs {
- name: string;
- rule: string;
- globs?: string;
-}
+export type CreateRuleBlockArgs = Pick<
+ Required,
+ "rule" | "description" | "alwaysApply" | "name"
+> &
+ Pick;
export const createRuleBlockImpl: ToolImpl = async (
args: CreateRuleBlockArgs,
@@ -19,41 +20,52 @@ export const createRuleBlockImpl: ToolImpl = async (
.replace(/[^a-z0-9\s-]/g, "")
.replace(/\s+/g, "-");
- const ruleObject = {
- name: args.name,
- rule: args.rule,
- ...(args.globs ? { globs: args.globs.trim() } : {}),
- };
+ const fileExtension = "md";
- const ruleBlock: ConfigYaml = {
- name: args.name,
- version: "0.0.1",
- schema: "v1",
- rules: [ruleObject],
- };
+ const frontmatter: RuleFrontmatter = {};
- const ruleYaml = YAML.stringify(ruleBlock);
+ if (args.globs) {
+ frontmatter.globs =
+ typeof args.globs === "string" ? args.globs.trim() : args.globs;
+ }
+ if (args.description) {
+ frontmatter.description = args.description.trim();
+ }
+
+ if (args.alwaysApply !== undefined) {
+ frontmatter.alwaysApply = args.alwaysApply;
+ }
+
+ const frontmatterYaml = YAML.stringify(frontmatter).trim();
+ let fileContent = `---
+${frontmatterYaml}
+---
+
+# ${args.name}
+
+${args.rule}
+`;
const [localContinueDir] = await extras.ide.getWorkspaceDirs();
const rulesDirUri = joinPathsToUri(
localContinueDir,
".continue",
"rules",
- `${safeRuleName}.yaml`,
+ `${safeRuleName}.${fileExtension}`,
);
- await extras.ide.writeFile(rulesDirUri, ruleYaml);
+ await extras.ide.writeFile(rulesDirUri, fileContent);
await extras.ide.openFile(rulesDirUri);
return [
{
name: "New Rule Block",
- description: "", // No description throws an error in the GUI
+ description: args.description || "",
uri: {
type: "file",
value: rulesDirUri,
},
- content: "Rule created successfully",
+ content: `Rule created successfully`,
},
];
};
diff --git a/core/tools/implementations/requestRule.ts b/core/tools/implementations/requestRule.ts
new file mode 100644
index 000000000..86aff6280
--- /dev/null
+++ b/core/tools/implementations/requestRule.ts
@@ -0,0 +1,28 @@
+import { ToolImpl } from ".";
+import { parseMarkdownRule } from "../../config/markdown/parseMarkdownRule";
+
+export const requestRuleImpl: ToolImpl = async (args, extras) => {
+ // Find the rule by name in the config
+ const rule = extras.config.rules.find((r) => r.name === args.name);
+
+ if (!rule || !rule.ruleFile) {
+ throw new Error(
+ `Rule with name "${args.name}" not found or has no file path`,
+ );
+ }
+
+ const fileContent = await extras.ide.readFile(rule.ruleFile);
+ const { markdown, frontmatter } = parseMarkdownRule(fileContent);
+
+ return [
+ {
+ name: frontmatter.name ?? "",
+ description: frontmatter.description ?? "",
+ content: markdown,
+ uri: {
+ type: "file",
+ value: rule.ruleFile,
+ },
+ },
+ ];
+};
diff --git a/core/tools/index.ts b/core/tools/index.ts
index d89cf8744..f7ed3be4b 100644
--- a/core/tools/index.ts
+++ b/core/tools/index.ts
@@ -1,3 +1,4 @@
+import { ConfigDependentToolParams, Tool } from "..";
import { createNewFileTool } from "./definitions/createNewFile";
import { createRuleBlock } from "./definitions/createRuleBlock";
import { editFileTool } from "./definitions/editFile";
@@ -6,11 +7,12 @@ import { grepSearchTool } from "./definitions/grepSearch";
import { lsTool } from "./definitions/lsTool";
import { readCurrentlyOpenFileTool } from "./definitions/readCurrentlyOpenFile";
import { readFileTool } from "./definitions/readFile";
+import { requestRuleTool } from "./definitions/requestRule";
import { runTerminalCommandTool } from "./definitions/runTerminalCommand";
import { searchWebTool } from "./definitions/searchWeb";
import { viewDiffTool } from "./definitions/viewDiff";
-export const allTools = [
+export const baseToolDefinitions = [
readFileTool,
editFileTool,
createNewFileTool,
@@ -26,3 +28,7 @@ export const allTools = [
// viewSubdirectoryTool,
// viewRepoMapTool,
];
+
+export const getConfigDependentToolDefinitions = (
+ params: ConfigDependentToolParams,
+): Tool[] => [requestRuleTool(params)];
diff --git a/core/util/abortManager.ts b/core/util/abortManager.ts
new file mode 100644
index 000000000..e7de53bca
--- /dev/null
+++ b/core/util/abortManager.ts
@@ -0,0 +1,37 @@
+export class StreamAbortManager {
+ private static instance: StreamAbortManager;
+ private controllers: Map;
+
+ private constructor() {
+ this.controllers = new Map();
+ }
+
+ public static getInstance(): StreamAbortManager {
+ if (!StreamAbortManager.instance) {
+ StreamAbortManager.instance = new StreamAbortManager();
+ }
+ return StreamAbortManager.instance;
+ }
+
+ public get(id: string): AbortController {
+ let controller = this.controllers.get(id);
+ if (!controller) {
+ controller = new AbortController();
+ this.controllers.set(id, controller);
+ }
+ return controller;
+ }
+
+ public abort(id: string): void {
+ const controller = this.controllers.get(id);
+ if (controller) {
+ controller.abort();
+ this.controllers.delete(id);
+ }
+ }
+
+ public clear(): void {
+ this.controllers.forEach((controller) => controller.abort());
+ this.controllers.clear();
+ }
+}
diff --git a/core/util/parameters.ts b/core/util/parameters.ts
index 05ab61e06..aa50de122 100644
--- a/core/util/parameters.ts
+++ b/core/util/parameters.ts
@@ -6,6 +6,7 @@ export const DEFAULT_AUTOCOMPLETE_OPTS: TabAutocompleteOptions = {
prefixPercentage: 0.3,
maxSuffixPercentage: 0.2,
debounceDelay: 350,
+ modelTimeout: 150,
multilineCompletions: "auto",
// @deprecated TO BE REMOVED
slidingWindowPrefixPercentage: 0.75,
diff --git a/core/util/shellPath.ts b/core/util/shellPath.ts
new file mode 100644
index 000000000..a1772ba81
--- /dev/null
+++ b/core/util/shellPath.ts
@@ -0,0 +1,29 @@
+import { execSync } from "child_process";
+
+/**
+ * Gets the PATH env var from the user's login shell on non-Windows platforms.
+ * Windows is not implemented primarily because it is not needed at the moment.
+ * @returns The enhanced PATH from the user's shell, or the current PATH if it cannot be determined
+ */
+export function getEnvPathFromUserShell(): string | undefined {
+ if (process.platform === "win32") {
+ console.warn(`${getEnvPathFromUserShell.name} not implemented for Windows`);
+ return undefined;
+ }
+
+ if (!process.env.SHELL) {
+ return undefined;
+ }
+
+ try {
+ const command = `${process.env.SHELL} -l -c 'echo $PATH'`;
+
+ const stdout = execSync(command, {
+ encoding: "utf8",
+ });
+
+ return stdout.trim();
+ } catch (error) {
+ return process.env.PATH; // Fallback to current PATH
+ }
+}
diff --git a/core/vendor/.gitignore b/core/vendor/.gitignore
index 736e8ae58..b512c09d4 100644
--- a/core/vendor/.gitignore
+++ b/core/vendor/.gitignore
@@ -1 +1 @@
-!node_modules
\ No newline at end of file
+node_modules
\ No newline at end of file
diff --git a/core/vendor/package-lock.json b/core/vendor/package-lock.json
index 3f8229af6..2a59b297b 100644
--- a/core/vendor/package-lock.json
+++ b/core/vendor/package-lock.json
@@ -10,6 +10,9 @@
"license": "Apache-2.0",
"dependencies": {
"@xenova/transformers": "^2.14.0"
+ },
+ "engines": {
+ "node": ">=20.19.0"
}
},
"node_modules/@huggingface/jinja": {
@@ -105,6 +108,78 @@
"resolved": "https://registry.npmjs.org/b4a/-/b4a-1.6.4.tgz",
"integrity": "sha512-fpWrvyVHEKyeEvbKZTVOeZF3VSKKWtJxFIxX/jaVPf+cLbGUSitjb49pHLqPV2BUNNZ0LcoeEGfE/YCpyDYHIw=="
},
+ "node_modules/bare-events": {
+ "version": "2.5.4",
+ "resolved": "https://registry.npmjs.org/bare-events/-/bare-events-2.5.4.tgz",
+ "integrity": "sha512-+gFfDkR8pj4/TrWCGUGWmJIkBwuxPS5F+a5yWjOHQt2hHvNZd5YLzadjmDUtFmMM4y429bnKLa8bYBMHcYdnQA==",
+ "license": "Apache-2.0",
+ "optional": true
+ },
+ "node_modules/bare-fs": {
+ "version": "4.1.5",
+ "resolved": "https://registry.npmjs.org/bare-fs/-/bare-fs-4.1.5.tgz",
+ "integrity": "sha512-1zccWBMypln0jEE05LzZt+V/8y8AQsQQqxtklqaIyg5nu6OAYFhZxPXinJTSG+kU5qyNmeLgcn9AW7eHiCHVLA==",
+ "license": "Apache-2.0",
+ "optional": true,
+ "dependencies": {
+ "bare-events": "^2.5.4",
+ "bare-path": "^3.0.0",
+ "bare-stream": "^2.6.4"
+ },
+ "engines": {
+ "bare": ">=1.16.0"
+ },
+ "peerDependencies": {
+ "bare-buffer": "*"
+ },
+ "peerDependenciesMeta": {
+ "bare-buffer": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/bare-os": {
+ "version": "3.6.1",
+ "resolved": "https://registry.npmjs.org/bare-os/-/bare-os-3.6.1.tgz",
+ "integrity": "sha512-uaIjxokhFidJP+bmmvKSgiMzj2sV5GPHaZVAIktcxcpCyBFFWO+YlikVAdhmUo2vYFvFhOXIAlldqV29L8126g==",
+ "license": "Apache-2.0",
+ "optional": true,
+ "engines": {
+ "bare": ">=1.14.0"
+ }
+ },
+ "node_modules/bare-path": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/bare-path/-/bare-path-3.0.0.tgz",
+ "integrity": "sha512-tyfW2cQcB5NN8Saijrhqn0Zh7AnFNsnczRcuWODH0eYAXBsJ5gVxAUuNr7tsHSC6IZ77cA0SitzT+s47kot8Mw==",
+ "license": "Apache-2.0",
+ "optional": true,
+ "dependencies": {
+ "bare-os": "^3.0.1"
+ }
+ },
+ "node_modules/bare-stream": {
+ "version": "2.6.5",
+ "resolved": "https://registry.npmjs.org/bare-stream/-/bare-stream-2.6.5.tgz",
+ "integrity": "sha512-jSmxKJNJmHySi6hC42zlZnq00rga4jjxcgNZjY9N5WlOe/iOoGRtdwGsHzQv2RlH2KOYMwGUXhf2zXd32BA9RA==",
+ "license": "Apache-2.0",
+ "optional": true,
+ "dependencies": {
+ "streamx": "^2.21.0"
+ },
+ "peerDependencies": {
+ "bare-buffer": "*",
+ "bare-events": "*"
+ },
+ "peerDependenciesMeta": {
+ "bare-buffer": {
+ "optional": true
+ },
+ "bare-events": {
+ "optional": true
+ }
+ }
+ },
"node_modules/base64-js": {
"version": "1.5.1",
"resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz",
@@ -444,9 +519,10 @@
}
},
"node_modules/prebuild-install/node_modules/tar-fs": {
- "version": "2.1.1",
- "resolved": "https://registry.npmjs.org/tar-fs/-/tar-fs-2.1.1.tgz",
- "integrity": "sha512-V0r2Y9scmbDRLCNex/+hYzvp/zyYjvFbHPNgVTKfQvVrb6guiE/fxP+XblDNR011utopbkex2nM4dHNV6GDsng==",
+ "version": "2.1.2",
+ "resolved": "https://registry.npmjs.org/tar-fs/-/tar-fs-2.1.2.tgz",
+ "integrity": "sha512-EsaAXwxmx8UB7FRKqeozqEPop69DXcmYwTQwXvyAPF352HJsPdkVhvTaDPYqfNgruveJIJy3TA2l+2zj8LJIJA==",
+ "license": "MIT",
"dependencies": {
"chownr": "^1.1.1",
"mkdirp-classic": "^0.5.2",
@@ -503,11 +579,6 @@
"once": "^1.3.1"
}
},
- "node_modules/queue-tick": {
- "version": "1.0.1",
- "resolved": "https://registry.npmjs.org/queue-tick/-/queue-tick-1.0.1.tgz",
- "integrity": "sha512-kJt5qhMxoszgU/62PLP1CJytzd2NKetjSRnyuj31fDd3Rlcz3fzlFdFLD1SItunPwyqEOkca6GbV612BWfaBag=="
- },
"node_modules/rc": {
"version": "1.2.8",
"resolved": "https://registry.npmjs.org/rc/-/rc-1.2.8.tgz",
@@ -642,12 +713,16 @@
}
},
"node_modules/streamx": {
- "version": "2.15.6",
- "resolved": "https://registry.npmjs.org/streamx/-/streamx-2.15.6.tgz",
- "integrity": "sha512-q+vQL4AAz+FdfT137VF69Cc/APqUbxy+MDOImRrMvchJpigHj9GksgDU2LYbO9rx7RX6osWgxJB2WxhYv4SZAw==",
+ "version": "2.22.0",
+ "resolved": "https://registry.npmjs.org/streamx/-/streamx-2.22.0.tgz",
+ "integrity": "sha512-sLh1evHOzBy/iWRiR6d1zRcLao4gGZr3C1kzNz4fopCOKJb6xD9ub8Mpi9Mr1R6id5o43S+d93fI48UC5uM9aw==",
+ "license": "MIT",
"dependencies": {
- "fast-fifo": "^1.1.0",
- "queue-tick": "^1.0.1"
+ "fast-fifo": "^1.3.2",
+ "text-decoder": "^1.1.0"
+ },
+ "optionalDependencies": {
+ "bare-events": "^2.2.0"
}
},
"node_modules/string_decoder": {
@@ -667,13 +742,17 @@
}
},
"node_modules/tar-fs": {
- "version": "3.0.4",
- "resolved": "https://registry.npmjs.org/tar-fs/-/tar-fs-3.0.4.tgz",
- "integrity": "sha512-5AFQU8b9qLfZCX9zp2duONhPmZv0hGYiBPJsyUdqMjzq/mqVpy/rEUSeHk1+YitmxugaptgBh5oDGU3VsAJq4w==",
+ "version": "3.0.8",
+ "resolved": "https://registry.npmjs.org/tar-fs/-/tar-fs-3.0.8.tgz",
+ "integrity": "sha512-ZoROL70jptorGAlgAYiLoBLItEKw/fUxg9BSYK/dF/GAGYFJOJJJMvjPAKDJraCXFwadD456FCuvLWgfhMsPwg==",
+ "license": "MIT",
"dependencies": {
- "mkdirp-classic": "^0.5.2",
"pump": "^3.0.0",
"tar-stream": "^3.1.5"
+ },
+ "optionalDependencies": {
+ "bare-fs": "^4.0.1",
+ "bare-path": "^3.0.0"
}
},
"node_modules/tar-stream": {
@@ -686,6 +765,15 @@
"streamx": "^2.15.0"
}
},
+ "node_modules/text-decoder": {
+ "version": "1.2.3",
+ "resolved": "https://registry.npmjs.org/text-decoder/-/text-decoder-1.2.3.tgz",
+ "integrity": "sha512-3/o9z3X0X0fTupwsYvR03pJ/DjWuqqrfwBgTQzdWDiQSm9KitAyz/9WqsT2JQW7KV2m+bC2ol/zqpW37NHxLaA==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "b4a": "^1.6.4"
+ }
+ },
"node_modules/tunnel-agent": {
"version": "0.6.0",
"resolved": "https://registry.npmjs.org/tunnel-agent/-/tunnel-agent-0.6.0.tgz",
diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md
deleted file mode 100644
index 148526daa..000000000
--- a/docs/CHANGELOG.md
+++ /dev/null
@@ -1,7 +0,0 @@
-# Changelog
-All notable changes to this project will be documented in this file.
-
-The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
-adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html),
-and is generated by [Changie](https://github.com/miniscruff/changie).
-
diff --git a/docs/docs/CLA.md b/docs/docs/CLA.md
new file mode 100644
index 000000000..00cd9ef07
--- /dev/null
+++ b/docs/docs/CLA.md
@@ -0,0 +1,48 @@
+# Individual Contributor License Agreement (v1.0, Continue)
+
+_Based on the Apache Software Foundation Individual CLA v 2.2._
+
+By commenting **“I have read the CLA Document and I hereby sign the CLA”**
+on a Pull Request, **you (“Contributor”) agree to the following terms** for any
+past and future “Contributions” submitted to **Continue (the “Project”)**.
+
+---
+
+## 1. Definitions
+
+- **“Contribution”** – any original work of authorship submitted to the Project
+ (code, documentation, designs, etc.).
+- **“You” / “Your”** – the individual (or legal entity) posting the acceptance
+ comment.
+
+## 2. Copyright License
+
+You grant **Continue Dev, Inc.** and all recipients of software distributed by the
+Project a perpetual, worldwide, non‑exclusive, royalty‑free, irrevocable
+license to reproduce, prepare derivative works of, publicly display, publicly
+perform, sublicense, and distribute Your Contributions and derivative works.
+
+## 3. Patent License
+
+You grant **Continue Dev, Inc.** and all recipients of the Project a perpetual,
+worldwide, non‑exclusive, royalty‑free, irrevocable (except as below) patent
+license to make, have made, use, sell, offer to sell, import, and otherwise
+transfer Your Contributions alone or in combination with the Project.
+
+If any entity brings patent litigation alleging that the Project or a
+Contribution infringes a patent, the patent licenses granted by You to that
+entity under this CLA terminate.
+
+## 4. Representations
+
+1. You are legally entitled to grant the licenses above.
+2. Each Contribution is either Your original creation or You have authority to
+ submit it under this CLA.
+3. Your Contributions are provided **“AS IS”** without warranties of any kind.
+4. You will notify the Project if any statement above becomes inaccurate.
+
+## 5. Miscellany
+
+This Agreement is governed by the laws of the **State of California**, USA,
+excluding its conflict‑of‑laws rules. If any provision is held unenforceable,
+the remaining provisions remain in force.
diff --git a/docs/docs/agent/model-setup.mdx b/docs/docs/agent/model-setup.mdx
index f0acf6f85..088d368da 100644
--- a/docs/docs/agent/model-setup.mdx
+++ b/docs/docs/agent/model-setup.mdx
@@ -7,14 +7,12 @@ sidebar_position: 2
Agent can be used with models that support tool use through Continue.
-For the best Agent experience we recommend Claude 3.7 Sonnet from Anthropic. Add Claude 3.7 Sonnet to your assistant from the hub [here](https://hub.continue.dev/anthropic/claude-3-7-sonnet). You can get an API key from the [Anthropic console](https://console.anthropic.com/settings/keys).
+For the best Agent experience we recommend Claude Sonnet 4 from Anthropic. Add Claude 3.7 Sonnet to your assistant from the hub [here](https://hub.continue.dev/anthropic/claude-4-sonnet). You can get an API key from the [Anthropic console](https://console.anthropic.com/settings/keys).
-Currently the following providers are supported:
+Currently the following models are recommended:
-- [Anthropic](../customize/model-providers/top-level/anthropic.mdx) - we recommend [Claude Sonnet 3.7](https://hub.continue.dev/anthropic/claude-3-7-sonnet)
-- [Ollama](../customize/model-providers/top-level/ollama.mdx) - we recommend [Qwen 2.5 Coder 7b](https://hub.continue.dev/ollama/qwen2.5-coder-7b). Also see all Ollama models that support tools [here](https://ollama.com/search?c=tools).
+- [Anthropic](../customize/model-providers/top-level/anthropic.mdx) - we recommend [Claude Sonnet 4](https://hub.continue.dev/anthropic/claude-4-sonnet)
- [OpenAI](../customize/model-providers/top-level/openai.mdx) - we recommend [GPT-4o](https://hub.continue.dev/openai/gpt-4o)
-- [Gemini](../customize/model-providers/top-level/gemini.mdx) - we recommend [Gemini 2.0 Flash](https://hub.continue.dev/google/gemini-2.0-flash)
-- [Mistral](../customize/model-providers/top-level/mistral.mdx) - we recommend [Codestral](https://hub.continue.dev/mistral/codestral)
+- [Gemini](../customize/model-providers/top-level/gemini.mdx) - we recommend [Gemini 2.5 Pro](https://hub.continue.dev/google/gemini-2.5-pro)
-The best chat models generally support tool usage. See [recommended chat models](../customize/model-roles/chat.mdx#recommended-chat-models) for more.
+The best chat models generally support tool use. See [recommended chat models](../customize/model-roles/chat.mdx#recommended-chat-models) for more.
diff --git a/docs/docs/blocks/mcp.md b/docs/docs/blocks/mcp.md
index 7201c4ac1..604d80203 100644
--- a/docs/docs/blocks/mcp.md
+++ b/docs/docs/blocks/mcp.md
@@ -1,13 +1,9 @@
---
-title: MCP Blocks
----
-
title: MCP Blocks
sidebar_label: MCP
description: Model Context Protocol servers provide specialized functionality
keywords: [mcp, blocks, model context protocol, integrations, tools]
sidebar_position: 4
-
---
Model Context Protocol servers provide specialized functionality:
diff --git a/docs/docs/customize/changelog.md b/docs/docs/customize/changelog.md
new file mode 100644
index 000000000..ba501267a
--- /dev/null
+++ b/docs/docs/customize/changelog.md
@@ -0,0 +1,13 @@
+---
+title: Continue Changelog
+description: Redirecting to our Changelog
+hide_table_of_contents: true
+---
+
+# Redirecting to Changelog
+
+If you are not redirected automatically, follow this [link to the changelog](https://changelog.continue.dev).
+
+
+
+
\ No newline at end of file
diff --git a/docs/docs/customize/changelog.mdx b/docs/docs/customize/changelog.mdx
deleted file mode 100644
index 5a43266a3..000000000
--- a/docs/docs/customize/changelog.mdx
+++ /dev/null
@@ -1,30 +0,0 @@
----
-title: Changelog
-description: Changelogs for the latest releases of the VSCode and JetBrains extensions
-keywords: [changelog]
-hide_table_of_contents: true
----
-
-import VSCodeChangelog from "../../../extensions/vscode/CHANGELOG.md";
-import JetBrainsChangelog from "../../../extensions/intellij/CHANGELOG.md";
-
-Below are the changelogs for the latest releases of the VSCode and JetBrains extensions. Prior to 2024-07-02, the changelogs do not reflect all updates.
-
-import TOCInline from "@theme/TOCInline";
-
-
- node.value === "VSCode Changelog" || node.value === "JetBrains Changelog",
- )}
-/>
-
-
-
-## VSCode Changelog
-
-
-
-## JetBrains Changelog
-
-
diff --git a/docs/docs/customize/deep-dives/mcp.mdx b/docs/docs/customize/deep-dives/mcp.mdx
index e4e828520..04366d210 100644
--- a/docs/docs/customize/deep-dives/mcp.mdx
+++ b/docs/docs/customize/deep-dives/mcp.mdx
@@ -13,6 +13,10 @@ Currently custom tools can be configured using the [Model Context Protocol](http
MCP Servers can be added to hub Assistants using `mcpServers` blocks. You can explore available MCP server blocks [here](https://hub.continue.dev/explore/mcp).
+:::info
+MCP can only be used in the **agent** mode.
+:::
+
To set up your own MCP server, read the [MCP quickstart](https://modelcontextprotocol.io/quickstart) and then [create an `mcpServers` block](https://hub.continue.dev/new?type=block&blockType=mcpServers) or add the following to your [config file](./configuration.md):
diff --git a/docs/docs/customize/deep-dives/rules.md b/docs/docs/customize/deep-dives/rules.md
index 6113a0e33..52ea34e0c 100644
--- a/docs/docs/customize/deep-dives/rules.md
+++ b/docs/docs/customize/deep-dives/rules.md
@@ -27,7 +27,7 @@ For example, you can say "Create a rule for this", and a rule will be created fo
### Syntax
-Rules blocks can be simple text, or have the following properties:
+Rules blocks can be simple text, written in YAML configuration files, or as Markdown (`.md`) files. They can have the following properties:
- `name` (**required**): A display name/title for the rule
- `rule` (**required**): The text content of the rule
diff --git a/docs/docs/customize/deep-dives/settings.md b/docs/docs/customize/deep-dives/settings.md
index 0d3b57127..82af98c15 100644
--- a/docs/docs/customize/deep-dives/settings.md
+++ b/docs/docs/customize/deep-dives/settings.md
@@ -6,11 +6,11 @@ keywords: [config, settings, configuration, customize, customization, sidebar]
# The User Settings Page
-The **User Settings page** can be accessed by clicking the gear icon in the header of the Continue sidebar.
+The **User Settings page** can be accessed by clicking the gear icon in the header of the Continue sidebar and then selecting the "Settings" tab.
-
+
-Which takes you to this page:
+Which takes you to this page (select the "Settings" tab):

@@ -26,7 +26,15 @@ Below that, the following settings which are not part of a configuration file ar
- `Enable Indexing`: Enables indexing of the codebase for the @codebase and @code context providers. **On** by default.
- `Font Size`: Specifies base font size for UI elements
- `Multiline Autocompletions`: Controls multiline completions for autocomplete. Can be set to `always`, `never`, or `auto`. Defaults to `auto`
-- `Disable autocomplete in files`: List of comma-separated glob pattern to disable autocomplete in matching files. E.g., "\_/.md, \*/.txt"
+- `Autocomplete timeout`: Maximum time in milliseconds for autocomplete request/retreival. Defaults to 150
+- `Autocomplete debounce`: Minimum time in milliseconds to trigger an autocomplete request after a change. Defaults to 250
+- `Disable autocomplete in files`: List of comma-separated glob pattern to disable autocomplete in matching files. E.g., `**/*.{txt,md}`
+
+### Experimental settings
+
+At the bottom of the User Settings page there is an "Experimental Settings" section which contains new or otherwise experimental settings, including:
+
+- `Auto-Accept Agent Edits`: **CAUTION: Be very careful with this setting. When turned on, Agent mode's edit tool can make changes to files with no manual review or guaranteed stopping point. If on, diffs generated by the edit tool are automatically accepted and Agent proceeds with the next conversational turn.** Off by default.
diff --git a/docs/docs/reference.md b/docs/docs/reference.md
index 647608fa5..f4ec4ea73 100644
--- a/docs/docs/reference.md
+++ b/docs/docs/reference.md
@@ -47,10 +47,6 @@ are pulled from [https://hub.continue.dev](https://hub.continue.dev).
Blocks can be imported into an assistant by adding a `uses` clause under the block type. This can be alongside other
`uses` clauses or explicit blocks of that type.
-:::info
-Note that local assistants cannot use blocks that require organization-level secrets.
-:::
-
For example, the following assistant imports an Anthropic model and defines an Ollama DeepSeek one.
```yaml title="Assistant models section"
@@ -85,6 +81,12 @@ Blocks:
You can find many examples of each of these block types on
the [Continue Explore Page](https://hub.continue.dev/explore/models)
+:::info
+Local blocks utilizing mustache notation for secrets (`${{ secrets.SECRET_NAME }}`) can read secret values:
+- globally, from a `.env` located in the global `.continue` folder (`~/.continue/.env`)
+- per-workspace, from a `.env` file located at the root of the current workspace.
+:::
+
### Inputs
Blocks can be passed user inputs, including hub secrets and raw text values. To create a block that has an input, use
@@ -111,7 +113,7 @@ models:
TEMP: 0.9
```
-Note that hub secrets can be passed as inputs, using the a similar mustache format: `secrets.SECRET_NAME`.
+Note that hub secrets can be passed as inputs, using a similar mustache format: `secrets.SECRET_NAME`.
### Overrides
@@ -186,6 +188,7 @@ chat, editing, and summarizing.
not currently used.
- `capabilities`: Array of strings denoting model capabilities, which will overwrite Continue's autodetection based on
provider and model. Supported capabilities include `tool_use` and `image_input`.
+- `maxStopWords`: Maximum number of stop words allowed, to avoid API errors with extensive lists.
- `promptTemplates`: Can be used to override the default prompt templates for different model roles. Valid values are
`chat`, [`edit`](./customize/model-roles/edit.mdx#prompt-templating), [
`apply`](./customize/model-roles/apply.mdx#prompt-templating) and [
@@ -204,7 +207,6 @@ chat, editing, and summarizing.
- `topP`: The cumulative probability for nucleus sampling.
- `topK`: Maximum number of tokens considered at each step.
- `stop`: An array of stop tokens that will terminate the completion.
- - `n`: Number of completions to generate.
- `reasoning`: Boolean to enable thinking/reasoning for Anthropic Claude 3.7+ models.
- `reasoningBudgetTokens`: Budget tokens for thinking/reasoning in Anthropic Claude 3.7+ models.
- `requestOptions`: HTTP request options specific to the model.
@@ -405,7 +407,7 @@ Destinations to which [development data](./customize/deep-dives/development-data
- `destination` (**required**): The destination/endpoint that will receive the data. Can be:
- an HTTP endpoint that will receive a POST request with a JSON blob
- a file URL to a directory in which events will be dumpted to `.jsonl` files
-- `schema` (**required**): the schema version of the JSON blobs to be sent
+- `schema` (**required**): the schema version of the JSON blobs to be sent. Options include `0.1.0` and `0.2.0`
- `events`: an array of event names to include. Defaults to all events if not specified.
- `level`: a pre-defined filter for event fields. Options include `all` and `noCode`; the latter excludes data like file
contents, prompts, and completions. Defaults to `all`
diff --git a/docs/docs/troubleshooting.mdx b/docs/docs/troubleshooting.mdx
index 71eac9d9b..405417a27 100644
--- a/docs/docs/troubleshooting.mdx
+++ b/docs/docs/troubleshooting.mdx
@@ -7,8 +7,6 @@ keywords: [reload, delete, manually, logs, server, console]
import TabItem from "@theme/TabItem";
import Tabs from "@theme/Tabs";
-The Continue VS Code extension is currently in beta, and the JetBrains extension is in Alpha. If you are having trouble, please follow the steps below.
-
1. [Check the logs](#check-the-logs)
2. [Try the latest pre-release](#download-the-latest-pre-release)
3. [Download an older version](#download-an-older-version)
@@ -122,6 +120,8 @@ If you're seeing a `fetch failed` error and your network requires custom certifi
You may also set `requestOptions.caBundlePath` to an array of paths to multiple certificates.
+***Windows VS Code Users***: Installing the [win-ca](https://marketplace.visualstudio.com/items?itemName=ukoloff.win-ca) extension should also correct this issue.
+
#### VS Code Proxy Settings
If you are using VS Code and require requests to be made through a proxy, you are likely already set up through VS Code's [Proxy Server Support](https://code.visualstudio.com/docs/setup/network#_proxy-server-support). To double-check that this is enabled, use cmd/ctrl + , to open settings and search for "Proxy Support". Unless it is set to "off", then VS Code is responsible for making the request to the proxy.
diff --git a/docs/docusaurus.config.js b/docs/docusaurus.config.js
index c12f063da..f973d446b 100644
--- a/docs/docusaurus.config.js
+++ b/docs/docusaurus.config.js
@@ -65,6 +65,12 @@ const config = {
],
],
+ scripts: [
+ {
+ src: "/scripts/custom-reo.js", // it references from static folder
+ },
+ ],
+
themeConfig:
/** @type {import("@docusaurus/preset-classic").ThemeConfig} */
({
diff --git a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/changelog.mdx b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/changelog.mdx
deleted file mode 100644
index ab9b5cb58..000000000
--- a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/changelog.mdx
+++ /dev/null
@@ -1,30 +0,0 @@
----
-title: 变更日志
-description: VSCode 和 JetBrains 扩展最新版本的变更日志
-keywords: [变更日志]
-hide_table_of_contents: true
----
-
-import VSCodeChangelog from "../../../../../../extensions/vscode/CHANGELOG.md";
-import JetBrainsChangelog from "../../../../../../extensions/intellij/CHANGELOG.md";
-
-以下是 VSCode 和 JetBrains 扩展最新版本的变更日志。在 2024-07-02 之前,变更日志没有反映所有更新。
-
-import TOCInline from "@theme/TOCInline";
-
-
- node.value === "VSCode Changelog" || node.value === "JetBrains Changelog",
- )}
-/>
-
-
-
-## VSCode 变更日志
-
-
-
-## JetBrains 变更日志
-
-
diff --git a/docs/static/img/header-buttons.png b/docs/static/img/header-buttons.png
deleted file mode 100644
index 6824043cf..000000000
Binary files a/docs/static/img/header-buttons.png and /dev/null differ
diff --git a/docs/static/img/settings-header.png b/docs/static/img/settings-header.png
new file mode 100644
index 000000000..9b241b164
Binary files /dev/null and b/docs/static/img/settings-header.png differ
diff --git a/docs/static/scripts/custom-reo.js b/docs/static/scripts/custom-reo.js
new file mode 100644
index 000000000..cc8c7bebc
--- /dev/null
+++ b/docs/static/scripts/custom-reo.js
@@ -0,0 +1 @@
+!function(){var e,t,n;e="7aa28ed11570734",t=function(){Reo.init({clientID:"7aa28ed11570734"})},(n=document.createElement("script")).src="https://static.reo.dev/"+e+"/reo.js",n.async=!0,n.onload=t,document.head.appendChild(n)}();
\ No newline at end of file
diff --git a/extensions/intellij/.run/Start Core Dev Server (CE).run.xml b/extensions/intellij/.run/Start Core Dev Server (CE).run.xml
index d6c646ef9..53c668ab2 100644
--- a/extensions/intellij/.run/Start Core Dev Server (CE).run.xml
+++ b/extensions/intellij/.run/Start Core Dev Server (CE).run.xml
@@ -1,6 +1,6 @@
-
+
diff --git a/extensions/intellij/CHANGELOG.md b/extensions/intellij/CHANGELOG.md
deleted file mode 100644
index c5378bd45..000000000
--- a/extensions/intellij/CHANGELOG.md
+++ /dev/null
@@ -1,104 +0,0 @@
-All notable changes to this project will be documented in this file.
-
-The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
-adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html),
-and is generated by [Changie](https://github.com/miniscruff/changie).
-
-
-## 1.0.0 - 2025-02-26
-### Added
-* Introduces hub.continue.dev
-* Improved theme matching
-### Fixed
-* Fixes interference between SonarQube and Continue autocomplete
-* Numerous reliability improvements
-
-## 0.0.92 - 2025-02-26
-### Fixed
-* Off-screen rendering to solve white flash on load and lack of changing cursor type
-* OSR-related fixes for non-Mac users
-* Fixes for inline edit in JetBrains
-
-## 0.0.72 - 2024-10-04
-### Added
-* Listen for changes to Intellij settings without requiring window reload
-### Changed
-* Updated tutorial file
-### Fixed
-* Fix ability to load config.ts in JetBrains IDEs
-
-## 0.0.69 - 2024-09-22
-### Added
-* Support for the "search" context provider
-### Fixed
-* Fixed bug where only first module would be recognized
-* Improved concurrency handling to avoid freezes
-* Made compatible with latest JetBrains versions
-
-## 0.0.54 - 2024-07-13
-### Added
-* Partial autocomplete acceptance
-* Autocomplete status bar spinner
-### Fixed
-* Fixed duplicate completion bug and others
-
-## 0.0.53 - 2024-07-10
-### Added
-* Support for .prompt files
-* New onboarding experience
-### Fixed
-* Indexing fixes from VS Code versions merged into IntelliJ
-* Improved codebase indexing reliability and testing
-* Fixes for autocomplete text positioning and timing
-
-## 0.0.42 - 2024-04-12
-### Added
-* Inline cmd/ctrl+I in JetBrains
-### Fixed
-* Fixed character encoding error causing display issues
-* Fixed error causing input to constantly demand focus
-* Fixed automatic reloading of config.json
-
-## 0.0.38 - 2024-03-15
-### Added
-* Remote config server support
-* Autocomplete support in JetBrains
-
-## 0.0.34 - 2024-03-03
-### Added
-* diff context provider
-### Changed
-* Allow LLM servers to handle templating
-### Fixed
-* Fix a few context providers / slash commands
-* Fixed issues preventing proper extension startup
-
-## v0.0.26 - 2023-12-28
-### Added
-* auto-reloading of config on save
-### Fixed
-* Fixed /edit bug for versions without Python server
-
-## v0.0.25 - 2023-12-25
-
-### Changed
-
-- Intellij extension no longer relies on the Continue Python server
-
-## v0.0.21 - 2023-12-05
-
-### Added
-
-- updated to match latest VS Code updates
-
-## v0.0.19 - 2023-11-19
-
-### Changed
-
-- migrated to .json config file format
-
-## v0.0.1 - 2023-09-01
-
-### Added
-
-- Initial scaffold created from [IntelliJ Platform Plugin Template](https://github.com/JetBrains/intellij-platform-plugin-template)
diff --git a/extensions/intellij/CONTRIBUTING.md b/extensions/intellij/CONTRIBUTING.md
index 145ea59bf..b655451c2 100644
--- a/extensions/intellij/CONTRIBUTING.md
+++ b/extensions/intellij/CONTRIBUTING.md
@@ -173,6 +173,12 @@ to run.
./gradlew test
```
+Run a single test
+
+```sh
+./gradlew test --tests "com.github.continuedev.continueintellijextension.e2e.TESTNAME"
+```
+
#### Identifying selectors
While the `runIdeForUiTests` task is running, you can visit the following URL
diff --git a/extensions/intellij/build.gradle.kts b/extensions/intellij/build.gradle.kts
index d61966b3a..a1b27e801 100644
--- a/extensions/intellij/build.gradle.kts
+++ b/extensions/intellij/build.gradle.kts
@@ -6,7 +6,6 @@ fun environment(key: String) = providers.environmentVariable(key)
fun Sync.prepareSandbox() {
from("../../binary/bin") { into("${intellij.pluginName.get()}/core/") }
- from("../vscode/node_modules/@vscode/ripgrep") { into("${intellij.pluginName.get()}/ripgrep/") }
}
val remoteRobotVersion = "0.11.23"
@@ -43,10 +42,12 @@ dependencies {
implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:1.5.0")
testImplementation("com.intellij.remoterobot:remote-robot:$remoteRobotVersion")
testImplementation("com.intellij.remoterobot:remote-fixtures:$remoteRobotVersion")
+ testImplementation("io.mockk:mockk:1.14.2")
testImplementation("org.junit.jupiter:junit-jupiter-api:5.10.0")
testRuntimeOnly("org.junit.jupiter:junit-jupiter-engine:5.9.2")
testImplementation("com.squareup.okhttp3:logging-interceptor:4.12.0")
implementation("com.automation-remarks:video-recorder-junit5:2.0")
+ testImplementation("org.jetbrains.kotlinx:kotlinx-coroutines-test:1.7.3")
// Exclude vulnerable Log4j from all dependencies
@@ -63,6 +64,7 @@ dependencies {
// Add Log4j 2.x explicitly
implementation("org.apache.logging.log4j:log4j-core:2.20.0")
implementation("org.apache.logging.log4j:log4j-api:2.20.0")
+ testImplementation(kotlin("test"))
}
// Set the JVM language level used to build the project. Use Java 11 for 2020.3+, and Java 17 for
@@ -163,6 +165,7 @@ tasks {
// This is to ensure we load the GUI with OSR enabled. We have logic that
// renders with OSR disabled below a particular IDE version.
// See ContinueExtensionSettingsService.kt for more info.
+ // Currently commented out however since test fail in CI with this version
// intellij {
// version.set("2024.1")
// }
diff --git a/extensions/intellij/gradle.properties b/extensions/intellij/gradle.properties
index e1571f5aa..533553649 100644
--- a/extensions/intellij/gradle.properties
+++ b/extensions/intellij/gradle.properties
@@ -3,13 +3,13 @@ pluginGroup=com.github.continuedev.continueintellijextension
pluginName=continue-intellij-extension
pluginRepositoryUrl=https://github.com/continuedev/continue
# SemVer format -> https://semver.org
-pluginVersion=1.0.16
+pluginVersion=1.0.21
# Supported build number ranges and IntelliJ Platform versions -> https://plugins.jetbrains.com/docs/intellij/build-number-ranges.html
pluginSinceBuild=223
# IntelliJ Platform Properties -> https://plugins.jetbrains.com/docs/intellij/tools-gradle-intellij-plugin.html#configuration-intellij-extension
platformType=IC
platformVersion=2022.3.3
-#org.gradle.java.home=/opt/homebrew/opt/openjdk@17
+# org.gradle.java.home=/opt/homebrew/opt/openjdk@17
#platformVersion = LATEST-EAP-SNAPSHOT
# Plugin Dependencies -> https://plugins.jetbrains.com/docs/intellij/plugin-dependencies.html
# Example: platformPlugins = com.intellij.java, com.jetbrains.php:203.4449.22
diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/actions/ContinueActionPromote.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/actions/ContinueActionPromote.kt
index ae26033e5..8c046c342 100644
--- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/actions/ContinueActionPromote.kt
+++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/actions/ContinueActionPromote.kt
@@ -11,15 +11,19 @@ import org.jetbrains.annotations.NotNull
class ContinueActionPromote : ActionPromoter {
override fun promote(@NotNull actions: List, @NotNull context: DataContext): List? {
-
- if (actions.none { it is AcceptAutocompleteAction }) {
- return null
- } else {
+ // For autocomplete actions
+ if (actions.any { it is AcceptAutocompleteAction }) {
val settings = ServiceManager.getService(ContinueExtensionSettings::class.java)
- if (!settings.continueState.showIDECompletionSideBySide) {
- return null;
+ if (settings.continueState.showIDECompletionSideBySide) {
+ return actions.filterIsInstance()
}
- return actions.filterIsInstance()
}
+
+ val rejectDiffActions = actions.filterIsInstance()
+ if (rejectDiffActions.isNotEmpty()) {
+ return rejectDiffActions
+ }
+
+ return null
}
}
\ No newline at end of file
diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/actions/ContinuePluginActions.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/actions/ContinuePluginActions.kt
index 27e4aebe2..863bbec56 100644
--- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/actions/ContinuePluginActions.kt
+++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/actions/ContinuePluginActions.kt
@@ -1,25 +1,12 @@
package com.github.continuedev.continueintellijextension.actions
import com.github.continuedev.continueintellijextension.editor.DiffStreamService
-import com.github.continuedev.continueintellijextension.services.ContinuePluginService
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.PlatformDataKeys
-import com.intellij.openapi.components.ServiceManager
import com.intellij.openapi.components.service
import com.intellij.openapi.fileEditor.FileEditorManager
-import com.intellij.openapi.project.Project
-import com.intellij.openapi.wm.ToolWindowManager
-fun getPluginService(project: Project?): ContinuePluginService? {
- if (project == null) {
- return null
- }
- return ServiceManager.getService(
- project,
- ContinuePluginService::class.java
- )
-}
class AcceptDiffAction : AnAction() {
override fun actionPerformed(e: AnActionEvent) {
@@ -29,7 +16,7 @@ class AcceptDiffAction : AnAction() {
private fun acceptHorizontalDiff(e: AnActionEvent) {
val continuePluginService = getPluginService(e.project) ?: return
- continuePluginService?.diffManager?.acceptDiff(null)
+ continuePluginService.diffManager?.acceptDiff(null)
}
private fun acceptVerticalDiff(e: AnActionEvent) {
@@ -61,28 +48,6 @@ class RejectDiffAction : AnAction() {
}
}
-fun getContinuePluginService(project: Project?): ContinuePluginService? {
- if (project != null) {
- val toolWindowManager = ToolWindowManager.getInstance(project)
- val toolWindow = toolWindowManager.getToolWindow("Continue")
-
- if (toolWindow != null) {
- if (!toolWindow.isVisible) {
- toolWindow.activate(null)
- }
- }
- }
-
- return getPluginService(project)
-}
-
-fun focusContinueInput(project: Project?) {
- val continuePluginService = getContinuePluginService(project) ?: return
- continuePluginService.continuePluginWindow?.content?.components?.get(0)?.requestFocus()
- continuePluginService.sendToWebview("focusContinueInputWithoutClear", null)
-
- continuePluginService.ideProtocolClient?.sendHighlightedCode()
-}
class FocusContinueInputWithoutClearAction : AnAction() {
override fun actionPerformed(e: AnActionEvent) {
@@ -134,8 +99,11 @@ class OpenLogsAction : AnAction() {
if (logFile.exists()) {
val virtualFile = com.intellij.openapi.vfs.LocalFileSystem.getInstance().findFileByIoFile(logFile)
if (virtualFile != null) {
- com.intellij.openapi.fileEditor.FileEditorManager.getInstance(project).openFile(virtualFile, true)
+ FileEditorManager.getInstance(project).openFile(virtualFile, true)
}
}
}
}
+
+
+
diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/actions/utils.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/actions/utils.kt
new file mode 100644
index 000000000..1bd31c463
--- /dev/null
+++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/actions/utils.kt
@@ -0,0 +1,39 @@
+package com.github.continuedev.continueintellijextension.actions
+
+import com.github.continuedev.continueintellijextension.services.ContinuePluginService
+import com.intellij.openapi.components.ServiceManager
+import com.intellij.openapi.project.Project
+import com.intellij.openapi.wm.ToolWindowManager
+
+fun getContinuePluginService(project: Project?): ContinuePluginService? {
+ if (project != null) {
+ val toolWindowManager = ToolWindowManager.getInstance(project)
+ val toolWindow = toolWindowManager.getToolWindow("Continue")
+
+ if (toolWindow != null) {
+ if (!toolWindow.isVisible) {
+ toolWindow.activate(null)
+ }
+ }
+ }
+
+ return getPluginService(project)
+}
+
+fun focusContinueInput(project: Project?) {
+ val continuePluginService = getContinuePluginService(project) ?: return
+ continuePluginService.continuePluginWindow?.content?.components?.get(0)?.requestFocus()
+ continuePluginService.sendToWebview("focusContinueInputWithoutClear", null)
+
+ continuePluginService.ideProtocolClient?.sendHighlightedCode()
+}
+
+fun getPluginService(project: Project?): ContinuePluginService? {
+ if (project == null) {
+ return null
+ }
+ return ServiceManager.getService(
+ project,
+ ContinuePluginService::class.java
+ )
+}
\ No newline at end of file
diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/activities/ContinuePluginStartupActivity.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/activities/ContinuePluginStartupActivity.kt
index 500398241..030b7d6f2 100644
--- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/activities/ContinuePluginStartupActivity.kt
+++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/activities/ContinuePluginStartupActivity.kt
@@ -1,6 +1,5 @@
package com.github.continuedev.continueintellijextension.activities
-import IntelliJIDE
import com.intellij.openapi.fileEditor.FileEditorManagerListener
import com.github.continuedev.continueintellijextension.auth.AuthListener
import com.github.continuedev.continueintellijextension.auth.ContinueAuthService
diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/AutocompleteActionGroup.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/AutocompleteActionGroup.kt
deleted file mode 100644
index 75f0d3aff..000000000
--- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/AutocompleteActionGroup.kt
+++ /dev/null
@@ -1,29 +0,0 @@
-package com.github.continuedev.continueintellijextension.autocomplete
-
-import com.github.continuedev.continueintellijextension.services.ContinueExtensionSettings
-import com.intellij.openapi.actionSystem.ActionUpdateThread
-import com.intellij.openapi.actionSystem.AnActionEvent
-import com.intellij.openapi.actionSystem.DefaultActionGroup
-import com.intellij.openapi.components.service
-
-class AutocompleteActionGroup : DefaultActionGroup() {
- override fun getActionUpdateThread(): ActionUpdateThread {
- return ActionUpdateThread.EDT
- }
-
- override fun update(e: AnActionEvent) {
- super.update(e)
- removeAll()
-
- val continueSettingsService = service()
- if (continueSettingsService.continueState.enableTabAutocomplete) {
- addAll(
- DisableTabAutocompleteAction(),
- )
- } else {
- addAll(
- EnableTabAutocompleteAction(),
- )
- }
- }
-}
\ No newline at end of file
diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/constants/PluginConstants.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/constants/PluginConstants.kt
new file mode 100644
index 000000000..ef362a372
--- /dev/null
+++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/constants/PluginConstants.kt
@@ -0,0 +1,11 @@
+package com.github.continuedev.continueintellijextension.constants
+
+/**
+ * Constants related to the Continue plugin.
+ */
+object ContinueConstants {
+ /**
+ * The unique identifier for the Continue plugin.
+ */
+ const val PLUGIN_ID = "com.github.continuedev.continueintellijextension"
+}
\ No newline at end of file
diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/ApplyToFileHandler.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/ApplyToFileHandler.kt
new file mode 100644
index 000000000..755b16d85
--- /dev/null
+++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/ApplyToFileHandler.kt
@@ -0,0 +1,187 @@
+package com.github.continuedev.continueintellijextension.`continue`
+
+import com.github.continuedev.continueintellijextension.ApplyState
+import com.github.continuedev.continueintellijextension.ApplyStateStatus
+import com.github.continuedev.continueintellijextension.IDE
+import com.github.continuedev.continueintellijextension.ToastType
+import com.github.continuedev.continueintellijextension.editor.DiffStreamHandler
+import com.github.continuedev.continueintellijextension.editor.DiffStreamService
+import com.github.continuedev.continueintellijextension.editor.EditorUtils
+import com.github.continuedev.continueintellijextension.protocol.ApplyToFileParams
+import com.github.continuedev.continueintellijextension.services.ContinuePluginService
+import com.github.continuedev.continueintellijextension.utils.castNestedOrNull
+import com.intellij.openapi.editor.Editor
+import com.intellij.openapi.project.Project
+import kotlinx.coroutines.suspendCancellableCoroutine
+import kotlin.coroutines.resume
+import kotlin.coroutines.resumeWithException
+
+/**
+ * Handles applying text to a file with streaming diff preview
+ */
+class ApplyToFileHandler(
+ private val project: Project,
+ private val continuePluginService: ContinuePluginService,
+ private val ide: IDE,
+ private val params: ApplyToFileParams,
+ private val editorUtils: EditorUtils?,
+ private val diffStreamService: DiffStreamService
+) {
+
+ suspend fun handleApplyToFile() {
+ // Notify webview that we're starting to stream
+ notifyStreamStarted()
+
+ if (editorUtils == null) {
+ ide.showToast(ToastType.ERROR, "No active editor to apply edits to")
+ notifyStreamClosed()
+ return
+ }
+
+ if (editorUtils.isDocumentEmpty()) {
+ editorUtils.insertTextIntoEmptyDocument(params.text)
+ notifyStreamClosed()
+ return
+ }
+
+ // Get the LLM configuration for applying edits
+ val llm = fetchApplyLLMConfig() ?: run {
+ ide.showToast(ToastType.ERROR, "Failed to fetch model configuration")
+ notifyStreamClosed()
+ return
+ }
+
+ setupAndStreamDiffs(editorUtils, llm)
+ }
+
+ private fun notifyStreamStarted() {
+ sendApplyStateUpdate(ApplyStateStatus.STREAMING)
+ }
+
+ private fun notifyStreamClosed(numDiffs: Int? = 0) {
+ sendApplyStateUpdate(ApplyStateStatus.CLOSED, numDiffs)
+ }
+
+ private fun sendApplyStateUpdate(
+ status: ApplyStateStatus,
+ numDiffs: Int? = null
+ ) {
+ val payload = ApplyState(
+ streamId = params.streamId,
+ status = status.status,
+ numDiffs = numDiffs,
+ filepath = params.filepath,
+ fileContent = params.text,
+ toolCallId = params.toolCallId.toString()
+ )
+
+ continuePluginService.sendToWebview("updateApplyState", payload)
+ }
+
+ private suspend fun fetchApplyLLMConfig(): Any? {
+ return try {
+ suspendCancellableCoroutine { continuation ->
+ continuePluginService.coreMessenger?.request(
+ "config/getSerializedProfileInfo",
+ null,
+ null
+ ) { response ->
+ try {
+ val selectedModels = response.castNestedOrNull