Merge branch 'main' into nate/fix-openai-adapters
This commit is contained in:
commit
2b318f8140
333 changed files with 9646 additions and 4880 deletions
|
|
@ -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
|
||||
|
|
@ -1,4 +0,0 @@
|
|||
## 0.0.38 - 2024-03-15
|
||||
### Added
|
||||
* Remote config server support
|
||||
* Autocomplete support in JetBrains
|
||||
|
|
@ -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
|
||||
|
|
@ -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
|
||||
|
|
@ -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
|
||||
|
|
@ -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
|
||||
|
|
@ -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
|
||||
|
|
@ -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
|
||||
|
|
@ -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
|
||||
|
|
@ -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)
|
||||
|
|
@ -1,5 +0,0 @@
|
|||
## v0.0.19 - 2023-11-19
|
||||
|
||||
### Changed
|
||||
|
||||
- migrated to .json config file format
|
||||
|
|
@ -1,5 +0,0 @@
|
|||
## v0.0.21 - 2023-12-05
|
||||
|
||||
### Added
|
||||
|
||||
- updated to match latest VS Code updates
|
||||
|
|
@ -1,5 +0,0 @@
|
|||
## v0.0.25 - 2023-12-25
|
||||
|
||||
### Changed
|
||||
|
||||
- Intellij extension no longer relies on the Continue Python server
|
||||
|
|
@ -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
|
||||
|
|
@ -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
|
||||
|
|
@ -1,3 +0,0 @@
|
|||
## 0.8.15 - 2024-03-05
|
||||
### Added
|
||||
* Tab-autocomplete in beta
|
||||
|
|
@ -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
|
||||
|
|
@ -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
|
||||
|
|
@ -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
|
||||
|
|
@ -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
|
||||
|
|
@ -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
|
||||
|
|
@ -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
|
||||
|
|
@ -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
|
||||
|
|
@ -1,3 +0,0 @@
|
|||
## 0.8.49 - 2024-09-01
|
||||
### Fixed
|
||||
* Hotfix: submenu context providers
|
||||
|
|
@ -1,3 +0,0 @@
|
|||
## 0.8.50 - 2024-09-02
|
||||
### Fixed
|
||||
* Hotfix for ability to use more than one inline context provider
|
||||
|
|
@ -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
|
||||
|
|
@ -1,4 +0,0 @@
|
|||
## 0.8.52 - 2024-09-16
|
||||
### Changed
|
||||
* Use Chromium only as a fallback after asking user
|
||||
* Redesigned onboarding flow
|
||||
|
|
@ -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
|
||||
|
|
@ -1,3 +0,0 @@
|
|||
## 0.8.54 - 2024-10-15
|
||||
### Fixed
|
||||
* Hotfix: throttle transformers.js embeddings provider
|
||||
|
|
@ -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
|
||||
|
|
@ -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
|
||||
|
|
@ -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
|
||||
|
|
@ -1,3 +0,0 @@
|
|||
## 0.8.59 - 2024-11-25
|
||||
### Fixed
|
||||
* Hotfix for Ollama onboarding
|
||||
|
|
@ -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
|
||||
|
|
@ -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
|
||||
|
|
@ -1,6 +0,0 @@
|
|||
## 1.0.0 - 2025-02-26
|
||||
### Added
|
||||
* Introduces hub.continue.dev
|
||||
* Improved apply quality
|
||||
### Fixed
|
||||
* Numerous reliability improvements
|
||||
|
|
@ -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
|
||||
|
|
@ -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
|
||||
|
|
@ -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
|
||||
|
|
@ -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
|
||||
|
|
@ -1,5 +0,0 @@
|
|||
## v0.6.4 - 2023-11-19
|
||||
|
||||
### Changed
|
||||
|
||||
- migrated to .json config file format
|
||||
|
|
@ -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
|
||||
|
|
@ -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)
|
||||
|
|
@ -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).
|
||||
|
|
@ -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
|
||||
15
.continue/rules/intellij-plugin-test-execution.yaml
Normal file
15
.continue/rules/intellij-plugin-test-execution.yaml
Normal file
|
|
@ -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
|
||||
10
.continue/rules/intellij-test-standards.yaml
Normal file
10
.continue/rules/intellij-test-standards.yaml
Normal file
|
|
@ -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"
|
||||
30
.continue/rules/unit-testing-rules.yaml
Normal file
30
.continue/rules/unit-testing-rules.yaml
Normal file
|
|
@ -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
|
||||
4
.github/pull_request_template.md
vendored
4
.github/pull_request_template.md
vendored
|
|
@ -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? ]
|
||||
|
|
|
|||
30
.github/workflows/cla.yaml
vendored
Normal file
30
.github/workflows/cla.yaml
vendored
Normal file
|
|
@ -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"
|
||||
2
.github/workflows/jetbrains-release.yaml
vendored
2
.github/workflows/jetbrains-release.yaml
vendored
|
|
@ -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)
|
||||
|
|
|
|||
2
.github/workflows/main.yaml
vendored
2
.github/workflows/main.yaml
vendored
|
|
@ -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 }}
|
||||
|
||||
|
|
|
|||
3
.github/workflows/pr_checks.yaml
vendored
3
.github/workflows/pr_checks.yaml
vendored
|
|
@ -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]
|
||||
|
|
|
|||
2
.github/workflows/preview.yaml
vendored
2
.github/workflows/preview.yaml
vendored
|
|
@ -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 }}
|
||||
|
||||
|
|
|
|||
6
.gitignore
vendored
6
.gitignore
vendored
|
|
@ -162,5 +162,9 @@ extensions/.continue-debug/
|
|||
|
||||
*.vsix
|
||||
|
||||
# intellij module library files
|
||||
*.iml
|
||||
|
||||
.continuerules
|
||||
**/.continue/assistants/
|
||||
**/.continue/assistants/
|
||||
keys
|
||||
6
.idea/jsLinters/eslint.xml
generated
Normal file
6
.idea/jsLinters/eslint.xml
generated
Normal file
|
|
@ -0,0 +1,6 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="EslintConfiguration">
|
||||
<option name="fix-on-save" value="true" />
|
||||
</component>
|
||||
</project>
|
||||
1
.idea/prettier.xml
generated
1
.idea/prettier.xml
generated
|
|
@ -2,5 +2,6 @@
|
|||
<project version="4">
|
||||
<component name="PrettierConfiguration">
|
||||
<option name="myConfigurationMode" value="AUTOMATIC" />
|
||||
<option name="myRunOnSave" value="true" />
|
||||
</component>
|
||||
</project>
|
||||
22
.idea/runConfigurations/config_yaml_tests.xml
generated
Normal file
22
.idea/runConfigurations/config_yaml_tests.xml
generated
Normal file
|
|
@ -0,0 +1,22 @@
|
|||
<component name="ProjectRunConfigurationManager">
|
||||
<configuration default="false" name="config-yaml tests" type="JavaScriptTestRunnerJest">
|
||||
<config-file value="$PROJECT_DIR$/packages/config-yaml/jest.config.mjs" />
|
||||
<node-interpreter value="project" />
|
||||
<node-options value="--experimental-vm-modules" />
|
||||
<jest-package value="$PROJECT_DIR$/binary/node_modules/jest" />
|
||||
<working-dir value="$PROJECT_DIR$/packages/config-yaml" />
|
||||
<envs />
|
||||
<scope-kind value="ALL" />
|
||||
<method v="2">
|
||||
<option name="NpmBeforeRunTask" enabled="true">
|
||||
<package-json value="$PROJECT_DIR$/packages/config-yaml/package.json" />
|
||||
<command value="run" />
|
||||
<scripts>
|
||||
<script value="build" />
|
||||
</scripts>
|
||||
<node-interpreter value="project" />
|
||||
<envs />
|
||||
</option>
|
||||
</method>
|
||||
</configuration>
|
||||
</component>
|
||||
12
.idea/runConfigurations/core_tests.xml
generated
Normal file
12
.idea/runConfigurations/core_tests.xml
generated
Normal file
|
|
@ -0,0 +1,12 @@
|
|||
<component name="ProjectRunConfigurationManager">
|
||||
<configuration default="false" name="core tests" type="JavaScriptTestRunnerJest">
|
||||
<config-file value="$PROJECT_DIR$/core/jest.config.js" />
|
||||
<node-interpreter value="project" />
|
||||
<node-options value="--experimental-vm-modules" />
|
||||
<jest-package value="$PROJECT_DIR$/binary/node_modules/jest" />
|
||||
<working-dir value="$PROJECT_DIR$/core" />
|
||||
<envs />
|
||||
<scope-kind value="ALL" />
|
||||
<method v="2" />
|
||||
</configuration>
|
||||
</component>
|
||||
25
.idea/runConfigurations/openai_adapters_configuration.xml
generated
Normal file
25
.idea/runConfigurations/openai_adapters_configuration.xml
generated
Normal file
|
|
@ -0,0 +1,25 @@
|
|||
<component name="ProjectRunConfigurationManager">
|
||||
<configuration default="false" name="openai-adapters configuration" type="JavaScriptTestRunnerJest">
|
||||
<node-interpreter value="project" />
|
||||
<node-options value="--experimental-vm-modules" />
|
||||
<jest-package value="$PROJECT_DIR$/binary/node_modules/jest" />
|
||||
<working-dir value="$PROJECT_DIR$/packages/openai-adapters" />
|
||||
<envs />
|
||||
<scope-kind value="SUITE" />
|
||||
<test-file value="$PROJECT_DIR$/packages/openai-adapters/src/test/main.test.ts" />
|
||||
<test-names>
|
||||
<test-name value="openai configuration" />
|
||||
</test-names>
|
||||
<method v="2">
|
||||
<option name="NpmBeforeRunTask" enabled="true">
|
||||
<package-json value="$PROJECT_DIR$/packages/openai-adapters/package.json" />
|
||||
<command value="run" />
|
||||
<scripts>
|
||||
<script value="build" />
|
||||
</scripts>
|
||||
<node-interpreter value="project" />
|
||||
<envs />
|
||||
</option>
|
||||
</method>
|
||||
</configuration>
|
||||
</component>
|
||||
6
.idea/vcs.xml
generated
6
.idea/vcs.xml
generated
|
|
@ -1,5 +1,11 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="CommitMessageInspectionProfile">
|
||||
<profile version="1.0">
|
||||
<inspection_tool class="CommitFormat" enabled="true" level="WARNING" enabled_by_default="true" />
|
||||
<inspection_tool class="CommitNamingConvention" enabled="true" level="WARNING" enabled_by_default="true" />
|
||||
</profile>
|
||||
</component>
|
||||
<component name="VcsDirectoryMappings">
|
||||
<mapping directory="" vcs="Git" />
|
||||
</component>
|
||||
|
|
|
|||
3
.vscode/extensions.json
vendored
3
.vscode/extensions.json
vendored
|
|
@ -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"
|
||||
]
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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)
|
||||
213
CONTRIBUTING.md
213
CONTRIBUTING.md
|
|
@ -3,44 +3,49 @@
|
|||
## Table of Contents
|
||||
|
||||
- [Contributing to Continue](#contributing-to-continue)
|
||||
- [Table of Contents](#table-of-contents)
|
||||
- [Table of Contents](#table-of-contents)
|
||||
- [❤️ Ways to Contribute](#️-ways-to-contribute)
|
||||
- [👋 Continue Contribution Ideas](#-continue-contribution-ideas)
|
||||
- [🐛 Report Bugs](#-report-bugs)
|
||||
- [✨ Suggest Enhancements](#-suggest-enhancements)
|
||||
- [📖 Updating / Improving Documentation](#-updating--improving-documentation)
|
||||
- [Running the Documentation Server Locally](#running-the-documentation-server-locally)
|
||||
- [Method 1: NPM Script](#method-1-npm-script)
|
||||
- [Method 2: VS Code Task](#method-2-vs-code-task)
|
||||
- [🧑💻 Contributing Code](#-contributing-code)
|
||||
- [Environment Setup](#environment-setup)
|
||||
- [Pre-requisites](#pre-requisites)
|
||||
- [Fork the Continue Repository](#fork-the-continue-repository)
|
||||
- [VS Code](#vs-code)
|
||||
- [Debugging](#debugging)
|
||||
- [JetBrains](#jetbrains)
|
||||
- [Our Git Workflow](#our-git-workflow)
|
||||
- [Development workflow](#development-workflow)
|
||||
- [Formatting](#formatting)
|
||||
- [Testing](#testing)
|
||||
- [Review Process](#review-process)
|
||||
- [Getting help](#getting-help)
|
||||
- [Contribtuing new LLM Providers/Models](#contribtuing-new-llm-providersmodels)
|
||||
- [Adding an LLM Provider](#adding-an-llm-provider)
|
||||
- [Adding Models](#adding-models)
|
||||
- [📐 Continue Architecture](#-continue-architecture)
|
||||
- [Continue VS Code Extension](#continue-vs-code-extension)
|
||||
- [Continue JetBrains Extension](#continue-jetbrains-extension)
|
||||
- [👋 Continue Contribution Ideas](#-continue-contribution-ideas)
|
||||
- [🐛 Report Bugs](#-report-bugs)
|
||||
- [✨ Suggest Enhancements](#-suggest-enhancements)
|
||||
- [📖 Updating / Improving Documentation](#-updating--improving-documentation)
|
||||
- [Running the Documentation Server Locally](#running-the-documentation-server-locally)
|
||||
- [Method 1: NPM Script](#method-1-npm-script)
|
||||
- [Method 2: VS Code Task](#method-2-vs-code-task)
|
||||
- [🧑💻 Contributing Code](#-contributing-code)
|
||||
- [Environment Setup](#environment-setup)
|
||||
- [Pre-requisites](#pre-requisites)
|
||||
- [Fork the Continue Repository](#fork-the-continue-repository)
|
||||
- [VS Code](#vs-code)
|
||||
- [Debugging](#debugging)
|
||||
- [JetBrains](#jetbrains)
|
||||
- [Our Git Workflow](#our-git-workflow)
|
||||
- [Development workflow](#development-workflow)
|
||||
- [Formatting](#formatting)
|
||||
- [Testing](#testing)
|
||||
- [Review Process](#review-process)
|
||||
- [Getting help](#getting-help)
|
||||
- [Contribtuing new LLM Providers/Models](#contribtuing-new-llm-providersmodels)
|
||||
- [Adding an LLM Provider](#adding-an-llm-provider)
|
||||
- [Adding Models](#adding-models)
|
||||
- [📐 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,19 +55,22 @@ 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
|
||||
|
||||
- First, check whether a similar proposal has already been made
|
||||
- If not, [create an issue](https://github.com/continuedev/continue/issues)
|
||||
- Please describe the enhancement in as much detail as you can, and why it would be useful
|
||||
- First, check whether a similar proposal has already been made
|
||||
- If not, [create an issue](https://github.com/continuedev/continue/issues)
|
||||
- Please describe the enhancement in as much detail as you can, and why it would be useful
|
||||
|
||||
- Join the [Continue Discord](https://discord.gg/NWtdYexhMs) and tell us about your idea in the `#feedback` channel
|
||||
|
||||
## 📖 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 +78,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 +101,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,32 +128,39 @@ 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:
|
||||
|
||||
1. Switch to Run and Debug view
|
||||
2. Select `Launch extension` from drop down
|
||||
3. Hit play button
|
||||
4. This will start the extension in debug mode and open a new VS Code window with it installed
|
||||
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_
|
||||
1. Switch to Run and Debug view
|
||||
2. Select `Launch extension` from drop down
|
||||
3. Hit play button
|
||||
4. This will start the extension in debug mode and open a new VS Code window with it installed
|
||||
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 +168,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 <http://releaseflow.org>.
|
||||
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 <http://releaseflow.org>.
|
||||
|
||||
### 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 +189,22 @@ 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.
|
||||
|
||||
### 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 +215,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.
|
||||
28
README.md
28
README.md
|
|
@ -8,7 +8,10 @@
|
|||
|
||||
<div align="center">
|
||||
|
||||
**[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)**
|
||||
|
||||
</div>
|
||||
|
||||
|
|
@ -20,15 +23,25 @@
|
|||
<a target="_blank" href="https://docs.continue.dev" style="background:none">
|
||||
<img src="https://img.shields.io/badge/continue_docs-%23BE1B55" style="height: 22px;" />
|
||||
</a>
|
||||
<a target="_blank" href="https://changelog.continue.dev" style="background:none">
|
||||
<img src="https://img.shields.io/badge/changelog-%96EFF3" style="height: 22px;" />
|
||||
</a>
|
||||
<a target="_blank" href="https://discord.gg/vapESyrFmJ" style="background:none">
|
||||
<img src="https://img.shields.io/badge/discord-join-continue.svg?labelColor=191937&color=6F6FF7&logo=discord" style="height: 22px;" />
|
||||
</a>
|
||||
|
||||
<p></p>
|
||||
|
||||
## 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
|
||||
|
||||

|
||||
|
||||
</div>
|
||||
|
||||
|
|
@ -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
|
||||
|
||||
|
|
|
|||
|
|
@ -64,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
|
||||
|
|
|
|||
28
binary/package-lock.json
generated
28
binary/package-lock.json
generated
|
|
@ -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",
|
||||
|
|
@ -92,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",
|
||||
|
|
@ -128,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",
|
||||
|
|
@ -2586,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",
|
||||
|
|
@ -3196,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",
|
||||
|
|
|
|||
|
|
@ -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",
|
||||
|
|
|
|||
|
|
@ -72,7 +72,8 @@ export class StreamTransformPipeline {
|
|||
fullStop,
|
||||
);
|
||||
|
||||
const timeoutValue = helper.options.showWhateverWeHaveAtXMs;
|
||||
const timeoutValue = helper.options.modelTimeout;
|
||||
|
||||
|
||||
lineGenerator = showWhateverWeHaveAtXMs(lineGenerator, timeoutValue!);
|
||||
|
||||
|
|
|
|||
|
|
@ -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", () => {
|
||||
|
|
|
|||
|
|
@ -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 = ["<COMPLETION>"];
|
||||
export const LINES_TO_STOP_AT = ["# End of file.", "<STOP EDITING HERE"];
|
||||
|
|
@ -343,34 +343,48 @@ export async function* removeTrailingWhitespace(
|
|||
* 4. Yields processed lines that are part of the actual code block content.
|
||||
*/
|
||||
export async function* filterCodeBlockLines(rawLines: LineStream): LineStream {
|
||||
let seenValidLine = false;
|
||||
let waitingToSeeIfLineIsLast = undefined;
|
||||
let seenFirstFence = false;
|
||||
// nestCount is set to 1 when the entire code block is wrapped with ``` or START blocks. It's then incremented
|
||||
// when an inner code block is discovered to avoid exiting the function prematurly. The function will exit early
|
||||
// when all blocks are matched. When no outer fence is discovered the function will always continue to the end.
|
||||
let nestCount = 0;
|
||||
|
||||
for await (const line of rawLines) {
|
||||
// Filter out starting ```
|
||||
if (!seenValidLine) {
|
||||
|
||||
|
||||
if (!seenFirstFence) {
|
||||
if (shouldRemoveLineBeforeStart(line)) {
|
||||
continue;
|
||||
// Filter out starting ``` or START block
|
||||
continue
|
||||
}
|
||||
seenValidLine = true;
|
||||
// Regardless of a fence or START block start tracking the nesting level
|
||||
seenFirstFence = true;
|
||||
nestCount = 1;
|
||||
}
|
||||
|
||||
// Filter out ending ```
|
||||
if (typeof waitingToSeeIfLineIsLast !== "undefined") {
|
||||
yield waitingToSeeIfLineIsLast;
|
||||
waitingToSeeIfLineIsLast = undefined;
|
||||
}
|
||||
|
||||
const changedEndLine = shouldChangeLineAndStop(line);
|
||||
if (typeof changedEndLine === "string") {
|
||||
yield changedEndLine;
|
||||
return;
|
||||
}
|
||||
|
||||
if (line.startsWith("```")) {
|
||||
waitingToSeeIfLineIsLast = line;
|
||||
} else {
|
||||
yield line;
|
||||
if (nestCount > 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;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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<CompletionOptions> | 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) {
|
||||
|
|
|
|||
138
core/autocomplete/generation/utils.test.ts
Normal file
138
core/autocomplete/generation/utils.test.ts
Normal file
|
|
@ -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<string> {
|
||||
for (const chunk of chunks) {
|
||||
yield chunk;
|
||||
}
|
||||
}
|
||||
|
||||
async function streamToString(
|
||||
stream: AsyncGenerator<string>,
|
||||
): Promise<string> {
|
||||
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<string> {
|
||||
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();
|
||||
});
|
||||
});
|
||||
27
core/autocomplete/generation/utils.ts
Normal file
27
core/autocomplete/generation/utils.ts
Normal file
|
|
@ -0,0 +1,27 @@
|
|||
export async function* stopAfterMaxProcessingTime(
|
||||
stream: AsyncGenerator<string>,
|
||||
maxTimeMs: number,
|
||||
fullStop: () => void,
|
||||
): AsyncGenerator<string> {
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -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") ||
|
||||
|
|
|
|||
|
|
@ -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<boolean> {
|
||||
// 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<boolean>((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);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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",
|
||||
|
|
|
|||
|
|
@ -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<OrgWithProfiles[]> {
|
||||
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,
|
||||
|
|
|
|||
|
|
@ -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,
|
||||
};
|
||||
|
|
@ -970,6 +977,5 @@ export {
|
|||
finalToBrowserConfig,
|
||||
intermediateToFinalConfig,
|
||||
loadContinueConfigFromJson,
|
||||
type BrowserSerializedContinueConfig
|
||||
type BrowserSerializedContinueConfig,
|
||||
};
|
||||
|
||||
|
|
|
|||
|
|
@ -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(
|
||||
|
|
|
|||
47
core/config/markdown/loadMarkdownRules.ts
Normal file
47
core/config/markdown/loadMarkdownRules.ts
Normal file
|
|
@ -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 };
|
||||
}
|
||||
174
core/config/markdown/parseMarkdownRule.test.ts
Normal file
174
core/config/markdown/parseMarkdownRule.test.ts
Normal file
|
|
@ -0,0 +1,174 @@
|
|||
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",
|
||||
);
|
||||
});
|
||||
});
|
||||
69
core/config/markdown/parseMarkdownRule.ts
Normal file
69
core/config/markdown/parseMarkdownRule.ts
Normal file
|
|
@ -0,0 +1,69 @@
|
|||
import { basename } from "path";
|
||||
import * as YAML from "yaml";
|
||||
import { RuleWithSource } from "../..";
|
||||
|
||||
/**
|
||||
* Parses markdown content with YAML frontmatter
|
||||
*/
|
||||
export function parseMarkdownRule(content: string): {
|
||||
frontmatter: Record<string, any>;
|
||||
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,
|
||||
source: "rules-block",
|
||||
ruleFile: path,
|
||||
};
|
||||
}
|
||||
|
|
@ -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;
|
||||
|
|
|
|||
|
|
@ -32,6 +32,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 +129,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);
|
||||
|
||||
|
|
|
|||
|
|
@ -26,11 +26,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 +106,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 +134,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;
|
||||
|
|
|
|||
|
|
@ -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) {
|
||||
|
|
|
|||
|
|
@ -9,6 +9,7 @@ import {
|
|||
PackageIdentifier,
|
||||
RegistryClient,
|
||||
Rule,
|
||||
TEMPLATE_VAR_REGEX,
|
||||
unrollAssistant,
|
||||
validateConfigYaml,
|
||||
} from "@continuedev/config-yaml";
|
||||
|
|
@ -40,9 +41,8 @@ import { GlobalContext } from "../../util/GlobalContext";
|
|||
import { modifyAnyConfigWithSharedConfig } from "../sharedConfig";
|
||||
|
||||
import { getControlPlaneEnvSync } from "../../control-plane/env";
|
||||
import { logger } from "../../util/logger";
|
||||
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 ??
|
||||
|
|
@ -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,
|
||||
);
|
||||
|
|
|
|||
|
|
@ -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",
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
|
|
@ -172,7 +172,7 @@ describe("MCPConnection", () => {
|
|||
expect(mockConnect).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('should handle custom connection timeout', async () => {
|
||||
it("should handle custom connection timeout", async () => {
|
||||
const conn = new MCPConnection({ ...options, timeout: 11 });
|
||||
const mockConnect = jest
|
||||
.spyOn(Client.prototype, "connect")
|
||||
|
|
@ -199,7 +199,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();
|
||||
});
|
||||
|
||||
|
|
|
|||
|
|
@ -13,22 +13,31 @@ import {
|
|||
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<unknown> | null = null;
|
||||
public abortController: AbortController;
|
||||
|
||||
public status: MCPConnectionStatus = "not-connected";
|
||||
public errors: string[] = [];
|
||||
|
||||
public prompts: MCPPrompt[] = [];
|
||||
public tools: MCPTool[] = [];
|
||||
public resources: MCPResource[] = [];
|
||||
private transport: Transport;
|
||||
private connectionPromise: Promise<unknown> | null = null;
|
||||
|
||||
constructor(public options: MCPOptions) {
|
||||
this.transport = this.constructTransport(options);
|
||||
|
|
@ -52,43 +61,6 @@ class MCPConnection {
|
|||
await this.transport.close();
|
||||
}
|
||||
|
||||
private constructTransport(options: MCPOptions): Transport {
|
||||
switch (options.transport.type) {
|
||||
case "stdio":
|
||||
const env: Record<string, string> = 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<string, string> | undefined),
|
||||
}
|
||||
}),
|
||||
},
|
||||
requestInit: { headers: options.transport.requestOptions?.headers }
|
||||
});
|
||||
default:
|
||||
throw new Error(
|
||||
`Unsupported transport type: ${(options.transport as any).type}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
getStatus(): MCPServerStatus {
|
||||
return {
|
||||
...this.options,
|
||||
|
|
@ -232,14 +204,14 @@ 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;
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -254,6 +226,93 @@ 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<string, string> = 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 || [],
|
||||
);
|
||||
|
||||
return new StdioClientTransport({
|
||||
command,
|
||||
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<string, string>
|
||||
| undefined),
|
||||
},
|
||||
}),
|
||||
},
|
||||
requestInit: { headers: options.transport.requestOptions?.headers },
|
||||
});
|
||||
default:
|
||||
throw new Error(
|
||||
`Unsupported transport type: ${(options.transport as any).type}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export default MCPConnection;
|
||||
|
|
|
|||
55
core/control-plane/AuthTypes.ts
Normal file
55
core/control-plane/AuthTypes.ts
Normal file
|
|
@ -0,0 +1,55 @@
|
|||
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 isHubSession(
|
||||
sessionInfo: ControlPlaneSessionInfo | undefined,
|
||||
): sessionInfo is HubSessionInfo {
|
||||
return (
|
||||
sessionInfo !== undefined &&
|
||||
(sessionInfo.AUTH_TYPE === AuthType.WorkOsProd ||
|
||||
sessionInfo.AUTH_TYPE === AuthType.WorkOsStaging)
|
||||
);
|
||||
}
|
||||
|
||||
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
|
||||
);
|
||||
}
|
||||
|
|
@ -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<string> {
|
||||
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",
|
||||
|
|
|
|||
|
|
@ -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, isHubSession } 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,24 @@ export class ControlPlaneClient {
|
|||
return (await resp.json()) as any;
|
||||
}
|
||||
|
||||
get userId(): Promise<string | undefined> {
|
||||
return this.sessionInfoPromise.then(
|
||||
(sessionInfo) => sessionInfo?.account.id,
|
||||
);
|
||||
async isSignedIn(): Promise<boolean> {
|
||||
const sessionInfo = await this.sessionInfoPromise;
|
||||
return !!sessionInfo;
|
||||
}
|
||||
|
||||
async getAccessToken(): Promise<string | undefined> {
|
||||
return (await this.sessionInfoPromise)?.accessToken;
|
||||
const sessionInfo = await this.sessionInfoPromise;
|
||||
return isHubSession(sessionInfo) ? sessionInfo.accessToken : undefined;
|
||||
}
|
||||
|
||||
private async request(path: string, init: RequestInit): Promise<Response> {
|
||||
const accessToken = await this.getAccessToken();
|
||||
if (!accessToken) {
|
||||
const sessionInfo = await this.sessionInfoPromise;
|
||||
const hubSession = isHubSession(sessionInfo);
|
||||
|
||||
const accessToken = hubSession ? sessionInfo.accessToken : undefined;
|
||||
|
||||
// Bearer token not necessary for on-prem auth type
|
||||
if (!accessToken && hubSession) {
|
||||
throw new Error("No access token");
|
||||
}
|
||||
|
||||
|
|
@ -99,22 +96,6 @@ export class ControlPlaneClient {
|
|||
return resp;
|
||||
}
|
||||
|
||||
public async listWorkspaces(): Promise<ControlPlaneWorkspace[]> {
|
||||
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<AssistantUnrolled>;
|
||||
|
|
@ -124,8 +105,7 @@ export class ControlPlaneClient {
|
|||
rawYaml: string;
|
||||
}[]
|
||||
> {
|
||||
const userId = await this.userId;
|
||||
if (!userId) {
|
||||
if (!(await this.isSignedIn())) {
|
||||
return [];
|
||||
}
|
||||
|
||||
|
|
@ -144,9 +124,7 @@ export class ControlPlaneClient {
|
|||
}
|
||||
|
||||
public async listOrganizations(): Promise<Array<OrganizationDescription>> {
|
||||
const userId = await this.userId;
|
||||
|
||||
if (!userId) {
|
||||
if (!(await this.isSignedIn())) {
|
||||
return [];
|
||||
}
|
||||
|
||||
|
|
@ -164,8 +142,7 @@ export class ControlPlaneClient {
|
|||
public async listAssistantFullSlugs(
|
||||
organizationId: string | null,
|
||||
): Promise<FullSlug[] | null> {
|
||||
const userId = await this.userId;
|
||||
if (!userId) {
|
||||
if (!(await this.isSignedIn())) {
|
||||
return null;
|
||||
}
|
||||
|
||||
|
|
@ -183,16 +160,4 @@ export class ControlPlaneClient {
|
|||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
async getSettingsForWorkspace(workspaceId: string): Promise<ConfigJson> {
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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;
|
||||
|
|
|
|||
127
core/control-plane/mdm.test.ts
Normal file
127
core/control-plane/mdm.test.ts
Normal file
|
|
@ -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);
|
||||
});
|
||||
262
core/control-plane/mdm.ts
Normal file
262
core/control-plane/mdm.ts
Normal file
|
|
@ -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<string, string> {
|
||||
const configObj: Record<string, string> = {};
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
|
@ -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",
|
||||
|
|
|
|||
135
core/core.ts
135
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<string>,
|
||||
msg: Message<ToCoreProtocol["streamDiffLines"][0]>,
|
||||
): AsyncGenerator<DiffLine> {
|
||||
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<string> = new Set();
|
||||
private messageAbortControllers = new Map<string, AbortController>();
|
||||
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<T extends keyof ToCoreProtocol>(
|
||||
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));
|
||||
|
||||
|
|
|
|||
192
core/data/log.test.ts
Normal file
192
core/data/log.test.ts
Normal file
|
|
@ -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);
|
||||
});
|
||||
});
|
||||
});
|
||||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Add table
Reference in a new issue