Merge branch 'main' into workspace-continue-env

This commit is contained in:
uinstinct 2025-05-31 10:53:45 +05:30
commit 16b1d3fea7
418 changed files with 14070 additions and 6464 deletions

View file

@ -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

View file

@ -1,4 +0,0 @@
## 0.0.38 - 2024-03-15
### Added
* Remote config server support
* Autocomplete support in JetBrains

View file

@ -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

View file

@ -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

View file

@ -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

View file

@ -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

View file

@ -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

View file

@ -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

View file

@ -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

View file

@ -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)

View file

@ -1,5 +0,0 @@
## v0.0.19 - 2023-11-19
### Changed
- migrated to .json config file format

View file

@ -1,5 +0,0 @@
## v0.0.21 - 2023-12-05
### Added
- updated to match latest VS Code updates

View file

@ -1,5 +0,0 @@
## v0.0.25 - 2023-12-25
### Changed
- Intellij extension no longer relies on the Continue Python server

View file

@ -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

View file

@ -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

View file

@ -1,3 +0,0 @@
## 0.8.15 - 2024-03-05
### Added
* Tab-autocomplete in beta

View file

@ -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

View file

@ -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

View file

@ -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

View file

@ -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

View file

@ -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

View file

@ -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

View file

@ -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

View file

@ -1,3 +0,0 @@
## 0.8.49 - 2024-09-01
### Fixed
* Hotfix: submenu context providers

View file

@ -1,3 +0,0 @@
## 0.8.50 - 2024-09-02
### Fixed
* Hotfix for ability to use more than one inline context provider

View file

@ -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

View file

@ -1,4 +0,0 @@
## 0.8.52 - 2024-09-16
### Changed
* Use Chromium only as a fallback after asking user
* Redesigned onboarding flow

View file

@ -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

View file

@ -1,3 +0,0 @@
## 0.8.54 - 2024-10-15
### Fixed
* Hotfix: throttle transformers.js embeddings provider

View file

@ -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

View file

@ -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

View file

@ -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

View file

@ -1,3 +0,0 @@
## 0.8.59 - 2024-11-25
### Fixed
* Hotfix for Ollama onboarding

View file

@ -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

View file

@ -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

View file

@ -1,6 +0,0 @@
## 1.0.0 - 2025-02-26
### Added
* Introduces hub.continue.dev
* Improved apply quality
### Fixed
* Numerous reliability improvements

View file

@ -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

View file

@ -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

View file

@ -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

View file

@ -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

View file

@ -1,5 +0,0 @@
## v0.6.4 - 2023-11-19
### Changed
- migrated to .json config file format

View file

@ -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

View file

@ -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)

View file

@ -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).

View file

@ -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

View file

@ -0,0 +1,13 @@
name: bigger-picture-description-rules
version: 0.0.1
schema: v1
rules:
- name: bigger-picture-description-rules
rule: >-
When a user asks how a certain part of the code works:
1. Describe what the code does in isolation.
2. If the code interacts with other parts of the codebase, describe how the code is imported and used in other parts of the codebase.
3. When describing each use-case, include the parent function for clarity.

View file

@ -0,0 +1,27 @@
name: GUI
version: 0.0.1
schema: v1
rules:
- name: Extension Color Themes
rule: |
When adding colors to components, use tailwind color classes.
Do NOT use explicit colors like text-gray-400. Instead, use theme colors.
The common available theme colors are:
- For normal text: foreground, description, description-muted
- For other text, icons, etc: success, warning, error, accent, link
- For general components background, border, border-focus
- For specific components:
- Button: primary, primary-foreground, primary-hover, secondary, secondary-foreground, secondary-hover
- Input: input, input-foreground, input-border, input-placeholder
- Badge: badge, badge-foreground
- List/Dropdown items: list-hover, list-active, list-active-foreground
- Code Editor: editor, editor-foreground
Any of these colors can be used in tailwind e.g. bg-primary, text-success, border-error, hover:bg-list-hover, etc.
globs: "gui/**/*.tsx"
# Excluding the following less-used colors:
# Command (only used by tip-tap): command, command-foreground, command-border, command-border-focus
# Find widget colors: find-match, find-match-selected
# table-oddRow

View file

@ -0,0 +1,9 @@
---
globs: /**/*.
description: General questions about code completion should be answered specific to Continue
---
# Continue Specificity
- In chat mode, if the user asks generally about code completion or developer tools, answer specifically regarding Continue and not other similar software.
- Keep all suggestions and comments concentrated on Continue, unless the user asks otherwise. If the user does this, answer with no particular specificity to Continue.

View file

@ -0,0 +1,16 @@
---
globs: docs/**/*.{md,mdx}
description: Standards for writing and maintaining Continue Docs
---
# Continue Docs Standards
- Follow Docusaurus documentation standards
- Include YAML frontmatter with title, description, and keywords
- Use consistent heading hierarchy starting with h2 (##)
- Include relevant Admonition components for tips, warnings, and info
- Use descriptive alt text for images
- Include cross-references to related documentation
- Reference other docs with relative paths
- Keep paragraphs concise and scannable
- Use code blocks with appropriate language tags

View 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

View 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"

View file

@ -0,0 +1,11 @@
---
globs: core/llm/llms/**/*.{ts,test.ts}
description: Tailor recommendations for LLM code based on which specific LLM is being used.
---
# LLM Model Specificity
- Refer to the file name and names of big classes to determine which LLM is being used in a file.
- Ground all observations and recommendations with knowledge of that LLM.
- Consider items such as context length, architecture, speed, and such.
- Pay attention to the parent classes in these files.

View 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

View file

@ -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
View 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"

View file

@ -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)

View file

@ -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 }}

75
.github/workflows/metrics.yaml vendored Normal file
View file

@ -0,0 +1,75 @@
name: Monthly issue metrics
on:
workflow_dispatch:
schedule:
# Runs every Monday at 9:00 AM PST (17:00 UTC)
- cron: "0 17 * * 1"
push:
branches:
- nate/metrics-action
permissions:
contents: read
jobs:
build:
name: issue metrics
runs-on: ubuntu-latest
permissions:
issues: write
pull-requests: read
steps:
- name: Get dates for last month
shell: bash
run: |
# Calculate the first day of the previous month
first_day=$(date -d "last month" +%Y-%m-01)
# Calculate the last day of the previous month
last_day=$(date -d "$first_day +1 month -1 day" +%Y-%m-%d)
#Set an environment variable with the date range
echo "$first_day..$last_day"
echo "last_month=$first_day..$last_day" >> "$GITHUB_ENV"
- name: Run issue-metrics tool
uses: github/issue-metrics@v3
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
SEARCH_QUERY: 'repo:continuedev/continue created:${{ env.last_month }} -reason:"not planned"'
- name: Read metrics file content
id: read-metrics
run: |
content=$(cat ./issue_metrics.md)
# This prepares the content in a way that can be used in GitHub Actions
content="${content//'%'/'%25'}"
content="${content//$'\n'/'%0A'}"
# content="${content//$'\r'/'%0D'}"
echo "metrics_content=$content" >> "$GITHUB_OUTPUT"
- name: Post a message in a channel
uses: slackapi/slack-github-action@v2.1.0
with:
webhook: ${{ secrets.ISSUE_PR_METRICS_SLACK_WEBHOOK_URL }}
webhook-type: incoming-webhook
payload: |
text: "Issue / PR Metrics Report"
blocks:
- type: "header"
text:
type: "plain_text"
text: "Monthly Issue Metrics Report"
emoji: true
- type: "section"
text:
type: "mrkdwn"
text: |
${{ steps.read-metrics.outputs.metrics_content }}
- name: Upload metrics report as artifact
uses: actions/upload-artifact@v4
with:
name: issue-metrics-report
path: ./issue_metrics.md

View file

@ -235,10 +235,11 @@ jobs:
cd packages/config-yaml
npm run build
- name: Type check
- name: Type check and lint
run: |
cd gui
npx tsc --noEmit
npm run lint
binary-checks:
needs: [install-root, install-core, install-config-yaml]
@ -670,13 +671,6 @@ jobs:
cd extensions/vscode
rm -rf e2e/.test-extensions/continue*
- name: Upload e2e test screenshots
if: failure()
uses: actions/upload-artifact@v4
with:
name: e2e-failure-screenshots
path: extensions/vscode/e2e/storage/screenshots
- name: Sanitize test file name
id: sanitize_filename
if: always()
@ -685,6 +679,13 @@ jobs:
SANITIZED_FILENAME="${FILENAME//\//-}" # Replace / with - using bash parameter expansion
echo "sanitized_test_file=${SANITIZED_FILENAME}" >> $GITHUB_OUTPUT
- name: Upload e2e test screenshots
if: failure()
uses: actions/upload-artifact@v4
with:
name: e2e-failure-screenshots-${{ steps.sanitize_filename.outputs.sanitized_test_file || 'unknown' }}-${{ matrix.command == 'e2e:ci:run-yaml' && 'yaml' || 'json' }}
path: extensions/vscode/e2e/storage/screenshots
- name: Find e2e log file
if: always()
run: |

View file

@ -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 }}

7
.gitignore vendored
View file

@ -144,6 +144,7 @@ Icon?
.continuerc.json
.aider*
*.notes.md
notes.md
manual-testing-sandbox/.idea/**
@ -162,5 +163,9 @@ extensions/.continue-debug/
*.vsix
# intellij module library files
*.iml
.continuerules
**/.continue/assistants/
**/.continue/assistants/
keys

6
.idea/jsLinters/eslint.xml generated Normal file
View 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
View file

@ -2,5 +2,6 @@
<project version="4">
<component name="PrettierConfiguration">
<option name="myConfigurationMode" value="AUTOMATIC" />
<option name="myRunOnSave" value="true" />
</component>
</project>

View 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
View 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>

View 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
View file

@ -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>

View file

@ -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"
]
}

View file

@ -45,6 +45,7 @@
"extensions/.continue-debug": true
// "sync/**": true
},
"editor.formatOnSave": true,
"eslint.workingDirectories": ["./core"],
"typescript.tsdk": "node_modules/typescript/lib",
"conventionalCommits.showNewVersionNotes": false,

View file

@ -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)

View file

@ -22,6 +22,7 @@
- [Our Git Workflow](#our-git-workflow)
- [Development workflow](#development-workflow)
- [Formatting](#formatting)
- [Theme Colors](#theme-colors)
- [Testing](#testing)
- [Review Process](#review-process)
- [Getting help](#getting-help)
@ -31,16 +32,21 @@
- [📐 Continue Architecture](#-continue-architecture)
- [Continue VS Code Extension](#continue-vs-code-extension)
- [Continue JetBrains Extension](#continue-jetbrains-extension)
- [Contibutor License Agreement](#contributor-license-agreement-cla)
# ❤️ Ways to Contribute
## 👋 Continue Contribution Ideas
[This GitHub project board](https://github.com/orgs/continuedev/projects/2) is a list of ideas for how you can contribute to Continue. These aren't the only ways, but are a great starting point if you are new to the project.
[This GitHub project board](https://github.com/orgs/continuedev/projects/2) is a list of ideas for how you can
contribute to Continue. These aren't the only ways, but are a great starting point if you are new to the project. You
can also browse the list
of [good first issues](https://github.com/continuedev/continue/issues?q=is:issue%20state:open%20label:good-first-issue).
## 🐛 Report Bugs
If you find a bug, please [create an issue](https://github.com/continuedev/continue/issues) to report it! A great bug report includes:
If you find a bug, please [create an issue](https://github.com/continuedev/continue/issues) to report it! A great bug
report includes:
- A description of the bug
- Steps to reproduce
@ -50,7 +56,8 @@ If you find a bug, please [create an issue](https://github.com/continuedev/conti
## ✨ Suggest Enhancements
Continue is quickly adding features, and we'd love to hear which are the most important to you. The best ways to suggest an enhancement are:
Continue is quickly adding features, and we'd love to hear which are the most important to you. The best ways to suggest
an enhancement are:
- Create an issue
@ -62,7 +69,9 @@ Continue is quickly adding features, and we'd love to hear which are the most im
## 📖 Updating / Improving Documentation
Continue is continuously improving, but a feature isn't complete until it is reflected in the documentation! If you see something out-of-date or missing, you can help by clicking "Edit this page" at the bottom of any page on [docs.continue.dev](https://docs.continue.dev).
Continue is continuously improving, but a feature isn't complete until it is reflected in the documentation! If you see
something out-of-date or missing, you can help by clicking "Edit this page" at the bottom of any page
on [docs.continue.dev](https://docs.continue.dev).
### Running the Documentation Server Locally
@ -70,7 +79,8 @@ You can run the documentation server locally using either of the following metho
#### Method 1: NPM Script
1. Open your terminal and navigate to the `docs` subdirectory of the project. The `docusaurus.config.js` file you'll see there is a sign you're in the right place.
1. Open your terminal and navigate to the `docs` subdirectory of the project. The `docusaurus.config.js` file you'll see
there is a sign you're in the right place.
2. Run the following command to install the necessary dependencies for the documentation server:
@ -92,17 +102,22 @@ You can run the documentation server locally using either of the following metho
3. Look for the `docs:start` task and select it.
This will start a local server and you can see the documentation rendered in your default browser, typically accessible at `http://localhost:3000`.
This will start a local server and you can see the documentation rendered in your default browser, typically accessible
at `http://localhost:3000`.
## 🧑‍💻 Contributing Code
We welcome contributions from developers of all experience levels - from first-time contributors to seasoned open source maintainers. While we aim to maintain high standards for reliability and maintainability, our goal is to keep the process as welcoming and straightforward as possible.
We welcome contributions from developers of all experience levels - from first-time contributors to seasoned open source
maintainers. While we aim to maintain high standards for reliability and maintainability, our goal is to keep the
process as welcoming and straightforward as possible.
### Environment Setup
#### Pre-requisites
You should have Node.js version 20.19.0 (LTS) or higher installed. You can get it on [nodejs.org](https://nodejs.org/en/download) or, if you are using NVM (Node Version Manager), you can set the correct version of Node.js for this project by running the following command in the root of the project:
You should have Node.js version 20.19.0 (LTS) or higher installed. You can get it
on [nodejs.org](https://nodejs.org/en/download) or, if you are using NVM (Node Version Manager), you can set the correct
version of Node.js for this project by running the following command in the root of the project:
```bash
nvm use
@ -114,13 +129,15 @@ nvm use
2. Clone your forked repository to your local machine. Use: `git clone https://github.com/YOUR_USERNAME/continue.git`
3. Navigate to the cloned directory and make sure you are on the main branch. Create your feature/fix branch from there, like so: `git checkout -b 123-my-feature-branch`
3. Navigate to the cloned directory and make sure you are on the main branch. Create your feature/fix branch from there,
like so: `git checkout -b 123-my-feature-branch`
4. Send your pull request to the main branch.
#### VS Code
1. Open the VS Code command pallet (`cmd/ctrl+shift+p`) and select `Tasks: Run Task` and then select `install-all-dependencies`
1. Open the VS Code command pallet (`cmd/ctrl+shift+p`) and select `Tasks: Run Task` and then select
`install-all-dependencies`
2. Start debugging:
@ -131,15 +148,20 @@ nvm use
1. The new VS Code window with the extension is referred to as the _Host VS Code_
2. The window you started debugging from is referred to as the _Main VS Code_
3. To package the extension, run `npm run package` in the `extensions/vscode` directory, select `Tasks: Run Task` and then select `vscode-extension:package`. This will generate `extensions/vscode/build/continue-{VERSION}.vsix`, which you can install by right-clicking and selecting "Install Extension VSIX".
3. To package the extension, run `npm run package` in the `extensions/vscode` directory, select `Tasks: Run Task` and
then select `vscode-extension:package`. This will generate `extensions/vscode/build/continue-{VERSION}.vsix`, which
you can install by right-clicking and selecting "Install Extension VSIX".
##### Debugging
**Breakpoints** can be used in both the `core` and `extensions/vscode` folders while debugging, but are not currently supported inside of `gui` code.
**Breakpoints** can be used in both the `core` and `extensions/vscode` folders while debugging, but are not currently
supported inside of `gui` code.
**Hot-reloading** is enabled with Vite, so if you make any changes to the `gui`, they should be automatically reflected without rebuilding. In some cases, you may need to refresh the _Host VS Code_ window to see the changes.
**Hot-reloading** is enabled with Vite, so if you make any changes to the `gui`, they should be automatically reflected
without rebuilding. In some cases, you may need to refresh the _Host VS Code_ window to see the changes.
Similarly, any changes to `core` or `extensions/vscode` will be automatically included by just reloading the _Host VS Code_ window with cmd/ctrl+shift+p "Reload Window".
Similarly, any changes to `core` or `extensions/vscode` will be automatically included by just reloading the _Host VS
Code_ window with cmd/ctrl+shift+p "Reload Window".
#### JetBrains
@ -147,11 +169,20 @@ See [`intellij/CONTRIBUTING.md`](./extensions/intellij/CONTRIBUTING.md) for the
### Our Git Workflow
We keep a single permanent branch: `main`. When we are ready to create a "pre-release" version, we create a tag on the `main` branch titled `v0.9.x-vscode`, which automatically triggers the workflow in [preview.yaml](./.github/workflows/preview.yaml), which builds and releases a version of the VS Code extension. When a release has been sufficiently tested, we will create a new release titled `v0.8.x-vscode`, triggering a similar workflow in [main.yaml](./.github/workflows/main.yaml), which will build and release a main release of the VS Code extension. Any hotfixes can be made by creating a feature branch from the tag for the release in question. This workflow is well explained by <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 +190,38 @@ We keep a single permanent branch: `main`. When we are ready to create a "pre-re
### Formatting
Continue uses [Prettier](https://marketplace.visualstudio.com/items?itemName=esbenp.prettier-vscode) to format JavaScript/TypeScript. Please install the Prettier extension in VS Code and enable "Format on Save" in your settings.
Continue uses [Prettier](https://marketplace.visualstudio.com/items?itemName=esbenp.prettier-vscode) to format
JavaScript/TypeScript. Please install the Prettier extension in VS Code and enable "Format on Save" in your settings.
### Theme Colors
Continue has a set of named theme colors that we map to extension colors and tailwind classes, which can be found in [gui/src/styles/theme.ts](gui/src/styles/theme.ts)
Guidelines for using theme colors:
- Use Tailwind colors whenever possible. If developing in VS Code, download the [Tailwind CSS Intellisense extension](https://marketplace.visualstudio.com/items?itemName=bradlc.vscode-tailwindcss) for great suggestions
- Avoid using any explicit classes and CSS variables outside the theme (e.g. `text-yellow-400`)
Guidelines for adding/updating theme colors:
- Choose sensible VS Code variables to add/update in [gui/src/styles/theme.ts](gui/src/styles/theme.ts) (see [here](https://code.visualstudio.com/api/references/theme-color) and [here](https://www.notion.so/1fa1d55165f78097b551e3bc296fcf76?pvs=25) for inspiration)
- Choose sensible Jetbrains named colors to add/update in `GetTheme.kt` (flagship LLMs can give you good suggestions to try)
- Update `tailwind.config.js` if needed
- Use the Theme Test Page to check colors. This can be accessed by going to `Settings` -> `Help` -> `Theme Test Page` in dev/debug mode.
### Testing
We have a mix of unit, functional, and e2e test suites, with a primary focus on functional testing. These tests run on each pull request. If your PR causes one of these tests to fail, we will ask that you to resolve the issue before we merge.
We have a mix of unit, functional, and e2e test suites, with a primary focus on functional testing. These tests run on
each pull request. If your PR causes one of these tests to fail, we will ask that you to resolve the issue before we
merge.
When contributing, please update or create the appropriate tests to help verify the correctness of your implementaiton.
### Review Process
- **Initial Review** - A maintainer will be assigned as primary reviewer
- **Feedback Loop** - The reviewer may request changes. We value your work, but also want to ensure the code is maintainable and follows our patterns.
- **Feedback Loop** - The reviewer may request changes. We value your work, but also want to ensure the code is
maintainable and follows our patterns.
- **Approval & Merge** - Once the PR is approved, it will be merged into the `main` branch.
### Getting help
@ -181,42 +232,53 @@ Join [#contribute on Discord](https://discord.gg/vapESyrFmJ) to engage with main
### Adding an LLM Provider
Continue has support for more than a dozen different LLM "providers", making it easy to use models running on OpenAI, Ollama, Together, LM Studio, Msty, and more. You can find all of the existing providers [here](https://github.com/continuedev/continue/tree/main/core/llm/llms), and if you see one missing, you can add it with the following steps:
1. Create a new file in the `core/llm/llms` directory. The name of the file should be the name of the provider, and it should export a class that extends `BaseLLM`. This class should contain the following minimal implementation. We recommend viewing pre-existing providers for more details. The [LlamaCpp Provider](./core/llm/llms/LlamaCpp.ts) is a good simple example.
- `providerName` - the identifier for your provider.
- At least one of `_streamComplete` or `_streamChat` - This is the function that makes the request to the API and returns the streamed response. You only need to implement one because Continue can automatically convert between "chat" and "raw completion".
Continue has support for more than a dozen different LLM "providers", making it easy to use models running on OpenAI,
Ollama, Together, LM Studio, Msty, and more. You can find all of the existing
providers [here](https://github.com/continuedev/continue/tree/main/core/llm/llms), and if you see one missing, you can
add it with the following steps:
1. Create a new file in the `core/llm/llms` directory. The name of the file should be the name of the provider, and it
should export a class that extends `BaseLLM`. This class should contain the following minimal implementation. We
recommend viewing pre-existing providers for more details. The [LlamaCpp Provider](./core/llm/llms/LlamaCpp.ts) is a
good simple example.
2. Add your provider to the `LLMs` array in [core/llm/llms/index.ts](./core/llm/llms/index.ts).
3. If your provider supports images, add it to the `PROVIDER_SUPPORTS_IMAGES` array in [core/llm/autodetect.ts](./core/llm/autodetect.ts).
4. Add the necessary JSON Schema types to [`config_schema.json`](./extensions/vscode/config_schema.json). This makes sure that Intellisense shows users what options are available for your provider when they are editing `config.json`.
5. Add a documentation page for your provider in [`docs/docs/customize/model-providers`](./docs/docs/customize/model-providers). This should show an example of configuring your provider in `config.json` and explain what options are available.
3. If your provider supports images, add it to the `PROVIDER_SUPPORTS_IMAGES` array
in [core/llm/autodetect.ts](./core/llm/autodetect.ts).
4. Add a documentation page for your provider in [
`docs/docs/customize/model-providers/more`](./docs/docs/customize/model-providers/more). This should show an example
of configuring your provider in `config.yaml` and explain what options are available.
### Adding Models
While any model that works with a supported provider can be used with Continue, we keep a list of recommended models that can be automatically configured from the UI or `config.json`. The following files should be updated when adding a model:
While any model that works with a supported provider can be used with Continue, we keep a list of recommended models
that can be automatically configured from the UI or `config.json`. The following files should be updated when adding a
model:
- [config_schema.json](./extensions/vscode/config_schema.json) - This is the JSON Schema definition that is used to validate `config.json`. You'll notice a number of rules defined in "definitions.ModelDescription.allOf". Here is where you write rules that can specify something like "for the provider 'anthropic', only models 'claude-2' and 'claude-instant-1' are allowed. Look through all of these rules and make sure that your model is included for providers that support it.
- [AddNewModel page](./gui/src/pages/AddNewModel) - This directory defines which model options are shown in the side bar model selection UI. To add a new model:
1. Add a `ModelPackage` entry for the model into [configs/models.ts](./gui/src/pages/AddNewModel/configs/models.ts), following the lead of the many examples near the top of the file
2. Add the model within its provider's array to [AddNewModel.tsx](./gui/src/pages/AddNewModel/AddNewModel.tsx) (add provider if needed)
- [index.d.ts](./core/index.d.ts) - This file defines the TypeScript types used throughout Continue. You'll find a `ModelName` type. Be sure to add the name of your model to this.
- LLM Providers: Since many providers use their own custom strings to identify models, you'll have to add the translation from Continue's model name (the one you added to `index.d.ts`) and the model string for each of these providers: [Ollama](./core/llm/llms/Ollama.ts), [Together](./core/llm/llms/Together.ts), and [Replicate](./core/llm/llms/Replicate.ts). You can find their full model lists here: [Ollama](https://ollama.ai/library), [Together](https://docs.together.ai/docs/inference-models), [Replicate](https://replicate.com/collections/streaming-language-models).
- [Prompt Templates](./core/llm/index.ts) - In this file you'll find the `autodetectTemplateType` function. Make sure that for the model name you just added, this function returns the correct template type. This is assuming that the chat template for that model is already built in Continue. If not, you will have to add the template type and corresponding edit and chat templates.
- [AddNewModel page](./gui/src/pages/AddNewModel/configs/) - This directory defines which model options are shown in the
side bar model selection UI. To add a new model:
1. Add a `ModelPackage` entry for the model into [configs/models.ts](./gui/src/pages/AddNewModel/configs/models.ts),
following the lead of the many examples near the top of the file
2. Add the model within its provider's array
to [configs/providers.ts](./gui/src/pages/AddNewModel/configs/providers.ts) (add provider if needed)
- LLM Providers: Since many providers use their own custom strings to identify models, you'll have to add the
translation from Continue's model name (the one you added to `index.d.ts`) and the model string for each of these
providers: [Ollama](./core/llm/llms/Ollama.ts), [Together](./core/llm/llms/Together.ts),
and [Replicate](./core/llm/llms/Replicate.ts). You can find their full model lists
here: [Ollama](https://ollama.ai/library), [Together](https://docs.together.ai/docs/inference-models), [Replicate](https://replicate.com/collections/streaming-language-models).
- [Prompt Templates](./core/llm/autodetect.ts) - In this file you'll find the `autodetectTemplateType` function. Make
sure that for the model name you just added, this function returns the correct template type. This is assuming that
the chat template for that model is already built in Continue. If not, you will have to add the template type and
corresponding edit and chat templates.
## 📐 Continue Architecture
## Contributor License Agreement (CLA)
Continue consists of 2 parts that are split so that it can be extended to work in other IDEs as easily as possible:
We require all contributors to accept the CLA and have made it as easy as commenting on your PR:
1. **Continue GUI** - The Continue GUI is a React application that gives the user control over Continue. It displays the current chat history, allows the user to ask questions, invoke slash commands, and use context providers. The GUI also handles most state and holds as much of the logic as possible so that it can be reused between IDEs.
1. Open your pull request.
2. Paste the following comment (or reply `recheck` if you’ve signed before):
2. **Continue Extension** - The Continue Extension is a plugin for the IDE which implements the [IDE Interface](./core/index.d.ts#L229). This allows the GUI to request information from or actions to be taken within the IDE. This same interface is used regardless of IDE. The first Continue extensions we have built are for VS Code and JetBrains, but we plan to build clients for other IDEs in the future. The IDE Client must 1. implement IDE Interface, as is done [here](./extensions/vscode/src/VsCodeIde.ts) for VS Code and 2. display the Continue GUI in a sidebar, like [here](./extensions/vscode/src/ContinueGUIWebviewViewProvider.ts).
```text
I have read the CLA Document and I hereby sign the CLA
```
### Continue VS Code Extension
The starting point for the VS Code extension is [activate.ts](./extensions/vscode/src/activation/activate.ts). The `activateExtension` function here will register all commands and load the Continue GUI in the sidebar of the IDE as a webview.
### Continue JetBrains Extension
The JetBrains extension is currently in alpha testing. Please reach out on [Discord](https://discord.gg/vapESyrFmJ) if you are interested in contributing to its development.
3. The CLA‑Assistant bot records your signature in the repo and marks the status check as passed.

View file

@ -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
![agent](docs/static/img/agent.gif)
## 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
![chat](docs/static/img/chat.gif)
@ -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
![edit](docs/static/img/edit.gif)
## Agent
[Agent](https://continue.dev/docs/agent/how-to-use-it) enables you to make more substantial changes to your codebase
![agent](docs/static/img/agent.gif)
</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

View file

@ -8,13 +8,15 @@ const {
execCmdSync,
autodetectPlatformAndArch,
} = require("../scripts/util");
const { downloadRipgrep } = require("./utils/ripgrep");
const { ALL_TARGETS, TARGET_TO_LANCEDB } = require("./utils/targets");
const bin = path.join(__dirname, "bin");
const out = path.join(__dirname, "out");
const build = path.join(__dirname, "build");
function cleanSlate() {
// Clean slate
// Clean slate
rimrafSync(bin);
rimrafSync(out);
rimrafSync(build);
@ -25,13 +27,7 @@ function cleanSlate() {
}
const esbuildOutputFile = "out/index.js";
let targets = [
"darwin-x64",
"darwin-arm64",
"linux-x64",
"linux-arm64",
"win32-x64",
];
let targets = [...ALL_TARGETS];
const [currentPlatform, currentArch] = autodetectPlatformAndArch();
@ -50,15 +46,6 @@ for (let i = 2; i < process.argv.length; i++) {
}
}
const targetToLanceDb = {
"darwin-arm64": "@lancedb/vectordb-darwin-arm64",
"darwin-x64": "@lancedb/vectordb-darwin-x64",
"linux-arm64": "@lancedb/vectordb-linux-arm64-gnu",
"linux-x64": "@lancedb/vectordb-linux-x64-gnu",
"win32-x64": "@lancedb/vectordb-win32-x64-msvc",
"win32-arm64": "@lancedb/vectordb-win32-arm64-msvc",
};
// Bundles the extension into one file
async function buildWithEsbuild() {
console.log("[info] Building with esbuild...");
@ -77,7 +64,7 @@ async function buildWithEsbuild() {
format: "cjs",
platform: "node",
sourcemap: true,
minify: true,
minify: !esbuildOnly,
treeShaking: true,
loader: {
// eslint-disable-next-line @typescript-eslint/naming-convention
@ -89,7 +76,6 @@ async function buildWithEsbuild() {
inject: ["./importMetaUrl.js"],
define: { "import.meta.url": "importMetaUrl" },
});
}
async function installNodeModuleInTempDirAndCopyToCurrent(packageName, toCopy) {
@ -153,13 +139,31 @@ async function installNodeModuleInTempDirAndCopyToCurrent(packageName, toCopy) {
}
}
/**
* Downloads and installs ripgrep binaries for the specified target
*
* @param {string} target - Target platform-arch (e.g., 'darwin-x64')
* @param {string} targetDir - Directory to install ripgrep to
* @returns {Promise<void>}
*/
async function downloadRipgrepForTarget(target, targetDir) {
console.log(`[info] Downloading ripgrep for ${target}...`);
try {
await downloadRipgrep(target, targetDir);
console.log(`[info] Successfully installed ripgrep for ${target}`);
} catch (error) {
console.error(`[error] Failed to download ripgrep for ${target}:`, error);
throw error;
}
}
(async () => {
if (esbuildOnly) {
await buildWithEsbuild();
return;
}
cleanSlate()
cleanSlate();
// Informs of where to look for node_sqlite3.node https://www.npmjs.com/package/bindings#:~:text=The%20searching%20for,file%20is%20found
// This is only needed for our `pkg` command at build time
@ -179,10 +183,10 @@ async function installNodeModuleInTempDirAndCopyToCurrent(packageName, toCopy) {
console.log("[info] Downloading prebuilt lancedb...");
for (const target of targets) {
if (targetToLanceDb[target]) {
if (TARGET_TO_LANCEDB[target]) {
console.log(`[info] Downloading for ${target}...`);
await installNodeModuleInTempDirAndCopyToCurrent(
targetToLanceDb[target],
TARGET_TO_LANCEDB[target],
"@lancedb",
);
}
@ -290,10 +294,13 @@ async function installNodeModuleInTempDirAndCopyToCurrent(packageName, toCopy) {
// copy @lancedb to bin folders
console.log("[info] Copying @lancedb files to bin");
fs.copyFileSync(
`node_modules/${targetToLanceDb[target]}/index.node`,
`node_modules/${TARGET_TO_LANCEDB[target]}/index.node`,
`${targetDir}/index.node`,
);
// Download and install ripgrep for the target
await downloadRipgrepForTarget(target, targetDir);
// Informs the `continue-binary` of where to look for node_sqlite3.node
// https://www.npmjs.com/package/bindings#:~:text=The%20searching%20for,file%20is%20found
fs.writeFileSync(`${targetDir}/package.json`, "");
@ -310,6 +317,7 @@ async function installNodeModuleInTempDirAndCopyToCurrent(packageName, toCopy) {
`${targetDir}/continue-binary${exe}`,
`${targetDir}/index.node`, // @lancedb
`${targetDir}/build/Release/node_sqlite3.node`,
`${targetDir}/rg${exe}`, // ripgrep binary
);
}

128
binary/package-lock.json generated
View file

@ -10,6 +10,7 @@
"license": "Apache-2.0",
"dependencies": {
"@octokit/rest": "^20.0.2",
"adm-zip": "^0.5.16",
"commander": "^12.0.0",
"core": "file:../core",
"follow-redirects": "^1.15.5",
@ -18,6 +19,7 @@
"node-fetch": "^3.3.2",
"posthog-node": "^3.6.3",
"system-ca": "^1.0.2",
"tar": "^7.4.3",
"uuid": "^9.0.1",
"vectordb": "^0.4.20",
"win-ca": "^3.5.1"
@ -31,6 +33,7 @@
"@types/jest": "^29.5.12",
"@types/uuid": "^9.0.8",
"@vercel/ncc": "^0.38.1",
"cross-env": "^7.0.3",
"esbuild": "0.19.11",
"jest": "^29.7.0",
"pkg": "^5.8.1",
@ -49,10 +52,10 @@
"@aws-sdk/credential-providers": "^3.778.0",
"@continuedev/config-types": "^1.0.13",
"@continuedev/config-yaml": "file:../packages/config-yaml",
"@continuedev/fetch": "^1.0.4",
"@continuedev/fetch": "^1.0.10",
"@continuedev/llm-info": "^1.0.8",
"@continuedev/openai-adapters": "^1.0.19",
"@modelcontextprotocol/sdk": "^1.5.0",
"@continuedev/openai-adapters": "^1.0.25",
"@modelcontextprotocol/sdk": "^1.12.0",
"@mozilla/readability": "^0.5.0",
"@octokit/rest": "^20.1.1",
"@typescript-eslint/eslint-plugin": "^7.8.0",
@ -90,6 +93,7 @@
"p-limit": "^6.1.0",
"partial-json": "^0.1.7",
"pg": "^8.11.3",
"plist": "^3.1.0",
"posthog-node": "^3.6.3",
"puppeteer": "^22.4.0",
"puppeteer-chromium-resolver": "^23.0.0",
@ -126,6 +130,7 @@
"@types/mustache": "^4.2.5",
"@types/node-fetch": "^2.6.11",
"@types/pg": "^8.11.6",
"@types/plist": "^3.0.5",
"@types/request": "^2.48.12",
"@types/tar": "^6.1.13",
"@types/uuid": "^9.0.7",
@ -1526,6 +1531,18 @@
"node": ">=12"
}
},
"node_modules/@isaacs/fs-minipass": {
"version": "4.0.1",
"resolved": "https://registry.npmjs.org/@isaacs/fs-minipass/-/fs-minipass-4.0.1.tgz",
"integrity": "sha512-wgm9Ehl2jpeqP3zw/7mo3kRHFp5MEDhqAdwy1fTGkHAwnkGOVsgpvQhL8B5n1qlb01jV3n/bI0ZfZp5lWA1k4w==",
"license": "ISC",
"dependencies": {
"minipass": "^7.0.4"
},
"engines": {
"node": ">=18.0.0"
}
},
"node_modules/@istanbuljs/load-nyc-config": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/@istanbuljs/load-nyc-config/-/load-nyc-config-1.1.0.tgz",
@ -2434,6 +2451,15 @@
"ncc": "dist/ncc/cli.js"
}
},
"node_modules/adm-zip": {
"version": "0.5.16",
"resolved": "https://registry.npmjs.org/adm-zip/-/adm-zip-0.5.16.tgz",
"integrity": "sha512-TGw5yVi4saajsSEgz25grObGHEUaDrniwvA2qwSC060KfqGPdglhvPMA2lPIoxs3PQIItj2iag35fONcQqgUaQ==",
"license": "MIT",
"engines": {
"node": ">=12.0"
}
},
"node_modules/agent-base": {
"version": "6.0.2",
"resolved": "https://registry.npmjs.org/agent-base/-/agent-base-6.0.2.tgz",
@ -2563,9 +2589,9 @@
}
},
"node_modules/axios": {
"version": "1.7.9",
"resolved": "https://registry.npmjs.org/axios/-/axios-1.7.9.tgz",
"integrity": "sha512-LhLcE7Hbiryz8oMDdDptSrWowmB4Bl6RCt6sIJKpRB4XtVf0iEgewX3au/pJqm+Py1kCASkb/FFKjxQaLtxJvw==",
"version": "1.9.0",
"resolved": "https://registry.npmjs.org/axios/-/axios-1.9.0.tgz",
"integrity": "sha512-re4CqKTJaURpzbLHtIi6XpDv20/CnpXOtjRY5/CU32L8gU8ek9UIivcfvSWvmKEngmVbrUtPpdDwWDWL7DNHvg==",
"license": "MIT",
"dependencies": {
"follow-redirects": "^1.15.6",
@ -3173,6 +3199,25 @@
"node": "^14.15.0 || ^16.10.0 || >=18.0.0"
}
},
"node_modules/cross-env": {
"version": "7.0.3",
"resolved": "https://registry.npmjs.org/cross-env/-/cross-env-7.0.3.tgz",
"integrity": "sha512-+/HKd6EgcQCJGh2PSjZuUitQBQynKor4wrFbRg4DtAgS1aWO+gU52xpH7M9ScGgXSYmAVS9bIJ8EzuaGw0oNAw==",
"dev": true,
"license": "MIT",
"dependencies": {
"cross-spawn": "^7.0.1"
},
"bin": {
"cross-env": "src/bin/cross-env.js",
"cross-env-shell": "src/bin/cross-env-shell.js"
},
"engines": {
"node": ">=10.14",
"npm": ">=6",
"yarn": ">=1"
}
},
"node_modules/cross-spawn": {
"version": "7.0.6",
"resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz",
@ -5222,14 +5267,41 @@
}
},
"node_modules/minipass": {
"version": "7.1.1",
"resolved": "https://registry.npmjs.org/minipass/-/minipass-7.1.1.tgz",
"integrity": "sha512-UZ7eQ+h8ywIRAW1hIEl2AqdwzJucU/Kp59+8kkZeSvafXhZjul247BvIJjEVFVeON6d7lM46XX1HXCduKAS8VA==",
"dev": true,
"version": "7.1.2",
"resolved": "https://registry.npmjs.org/minipass/-/minipass-7.1.2.tgz",
"integrity": "sha512-qOOzS1cBTWYF4BH8fVePDBOO9iptMnGUEZwNc/cMWnTV2nVLZ7VoNWEPHkYczZA0pdoA7dl6e7FL659nX9S2aw==",
"license": "ISC",
"engines": {
"node": ">=16 || 14 >=14.17"
}
},
"node_modules/minizlib": {
"version": "3.0.2",
"resolved": "https://registry.npmjs.org/minizlib/-/minizlib-3.0.2.tgz",
"integrity": "sha512-oG62iEk+CYt5Xj2YqI5Xi9xWUeZhDI8jjQmC5oThVH5JGCTgIjr7ciJDzC7MBzYd//WvR1OTmP5Q38Q8ShQtVA==",
"license": "MIT",
"dependencies": {
"minipass": "^7.1.2"
},
"engines": {
"node": ">= 18"
}
},
"node_modules/mkdirp": {
"version": "3.0.1",
"resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-3.0.1.tgz",
"integrity": "sha512-+NsyUUAZDmo6YVHzL/stxSu3t9YS1iljliy3BSDrXJ/dkn1KYdmtZODGGjLcc9XLgVVpH4KshHB8XmZgMhaBXg==",
"license": "MIT",
"bin": {
"mkdirp": "dist/cjs/src/bin.js"
},
"engines": {
"node": ">=10"
},
"funding": {
"url": "https://github.com/sponsors/isaacs"
}
},
"node_modules/mkdirp-classic": {
"version": "0.5.3",
"resolved": "https://registry.npmjs.org/mkdirp-classic/-/mkdirp-classic-0.5.3.tgz",
@ -5340,6 +5412,7 @@
"version": "3.3.2",
"resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-3.3.2.tgz",
"integrity": "sha512-dRB78srN/l6gqWulah9SrxeYnxeddIG30+GOqK/9OlLVyLg3HPnr6SqOWTWOXKRwC2eGYCkZ59NNuSgvSrpgOA==",
"license": "MIT",
"dependencies": {
"data-uri-to-buffer": "^4.0.0",
"fetch-blob": "^3.1.4",
@ -6410,6 +6483,23 @@
"node": ">=12.17"
}
},
"node_modules/tar": {
"version": "7.4.3",
"resolved": "https://registry.npmjs.org/tar/-/tar-7.4.3.tgz",
"integrity": "sha512-5S7Va8hKfV7W5U6g3aYxXmlPoZVAwUMy9AOKyF2fVuZa2UD3qZjg578OrLRt8PcNN1PleVaL/5/yYATNL0ICUw==",
"license": "ISC",
"dependencies": {
"@isaacs/fs-minipass": "^4.0.0",
"chownr": "^3.0.0",
"minipass": "^7.1.2",
"minizlib": "^3.0.1",
"mkdirp": "^3.0.1",
"yallist": "^5.0.0"
},
"engines": {
"node": ">=18"
}
},
"node_modules/tar-fs": {
"version": "2.1.2",
"resolved": "https://registry.npmjs.org/tar-fs/-/tar-fs-2.1.2.tgz",
@ -6453,6 +6543,24 @@
"node": ">= 6"
}
},
"node_modules/tar/node_modules/chownr": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/chownr/-/chownr-3.0.0.tgz",
"integrity": "sha512-+IxzY9BZOQd/XuYPRmrvEVjF/nqj5kgT4kEq7VofrDoM1MxoRjEWkrCC3EtLi59TVawxTAn+orJwFQcrqEN1+g==",
"license": "BlueOak-1.0.0",
"engines": {
"node": ">=18"
}
},
"node_modules/tar/node_modules/yallist": {
"version": "5.0.0",
"resolved": "https://registry.npmjs.org/yallist/-/yallist-5.0.0.tgz",
"integrity": "sha512-YgvUTfwqyc7UXVMrB+SImsVYSmTS8X/tSrtdNZMImM+n7+QTriRXyXim0mBrTXNeqzVF0KWGgHPeiyViFFrNDw==",
"license": "BlueOak-1.0.0",
"engines": {
"node": ">=18"
}
},
"node_modules/test-exclude": {
"version": "6.0.0",
"resolved": "https://registry.npmjs.org/test-exclude/-/test-exclude-6.0.0.tgz",

View file

@ -33,6 +33,7 @@
"@types/jest": "^29.5.12",
"@types/uuid": "^9.0.8",
"@vercel/ncc": "^0.38.1",
"cross-env": "^7.0.3",
"esbuild": "0.19.11",
"jest": "^29.7.0",
"pkg": "^5.8.1",
@ -42,6 +43,7 @@
},
"dependencies": {
"@octokit/rest": "^20.0.2",
"adm-zip": "^0.5.16",
"commander": "^12.0.0",
"core": "file:../core",
"follow-redirects": "^1.15.5",
@ -50,6 +52,7 @@
"node-fetch": "^3.3.2",
"posthog-node": "^3.6.3",
"system-ca": "^1.0.2",
"tar": "^7.4.3",
"uuid": "^9.0.1",
"vectordb": "^0.4.20",
"win-ca": "^3.5.1"

View file

@ -4,17 +4,35 @@ const path = require('path');
const logDirPath = path.join(__dirname, '..', 'extensions', '.continue-debug', 'logs');
const logFilePath = path.join(logDirPath, "prompt.log");
// Ensure the log directory exists
if (!fs.existsSync(logDirPath)) {
fs.mkdirSync(logDirPath, { recursive: true });
console.log("Created log directory at " + logDirPath);
}
// Create the log file if it doesn't exist
if (!fs.existsSync(logFilePath)) {
fs.createWriteStream(logFilePath).end();
fs.writeFileSync(logFilePath, ''); // Create an empty file synchronously
console.log("Created empty log file at " + logFilePath);
}
console.log("Watching logs at " + logFilePath)
console.log("Watching logs at " + logFilePath);
fs.watch(logFilePath, () => {
// console.clear();
fs.createReadStream(logFilePath).pipe(process.stdout);
});
// Set up the file watcher
try {
fs.watch(logFilePath, () => {
try {
// console.clear();
const stream = fs.createReadStream(logFilePath);
stream.pipe(process.stdout);
stream.on('error', (err) => {
console.error('Error reading log file:', err.message);
});
} catch (err) {
console.error('Error while handling file change:', err.message);
}
});
} catch (err) {
console.error('Error setting up file watcher:', err.message);
console.log('You may need to restart the script after the extension generates the first log entry.');
}

View file

@ -226,6 +226,7 @@ describe("Test Suite", () => {
title: "Test Model",
provider: "openai",
model: "gpt-3.5-turbo",
underlyingProviderName: "openai",
};
await messenger.request("config/addModel", {
model,
@ -252,6 +253,7 @@ describe("Test Suite", () => {
title: "Test Model",
provider: "mock",
model: "gpt-3.5-turbo",
underlyingProviderName: "mock",
};
await messenger.request("config/addModel", {
model,

120
binary/utils/ripgrep.js Normal file
View file

@ -0,0 +1,120 @@
const fs = require("fs");
const path = require("path");
const { rimrafSync } = require("rimraf");
const tar = require("tar");
const { RIPGREP_VERSION, TARGET_TO_RIPGREP_RELEASE } = require("./targets");
const AdmZip = require("adm-zip");
const RIPGREP_BASE_URL = `https://github.com/BurntSushi/ripgrep/releases/download/${RIPGREP_VERSION}`;
/**
* Downloads a file from a URL to a specified path
*
* @param {string} url - The URL to download from
* @param {string} destPath - The destination path for the downloaded file
* @returns {Promise<void>}
*/
async function downloadFile(url, destPath) {
// Use the built-in fetch API instead of node-fetch
const response = await fetch(url, {
redirect: "follow", // Automatically follow redirects
});
if (!response.ok) {
throw new Error(`Failed to download file, status code: ${response.status}`);
}
// Get the response as an array buffer and write it to the file
const buffer = await response.arrayBuffer();
fs.writeFileSync(destPath, Buffer.from(buffer));
}
/**
* Extracts an archive to a specified directory
*
* @param {string} archivePath - Path to the archive file
* @param {string} targetDir - Directory to extract the archive to
* @param {string} platform - Platform identifier (e.g., 'darwin', 'linux', 'win32')
* @returns {Promise<void>}
*/
async function extractArchive(archivePath, targetDir, platform) {
if (platform === "win32" || archivePath.endsWith(".zip")) {
// Simple zip extraction for Windows - extract rg.exe
const zip = new AdmZip(archivePath);
const rgEntry = zip
.getEntries()
.find((entry) => entry.entryName.endsWith("rg.exe"));
if (!rgEntry) {
throw new Error("Could not find rg.exe in the downloaded archive");
}
// Extract the found rg.exe file to the target directory
const entryData = rgEntry.getData();
fs.writeFileSync(path.join(targetDir, "rg.exe"), entryData);
} else {
await tar.extract({
file: archivePath,
cwd: targetDir,
strip: 1, // Strip the top-level directory
filter: (path) => path.endsWith("/rg"),
});
}
}
/**
* Downloads and installs ripgrep for the specified target
*
* @param {string} target - Target platform-arch (e.g., 'darwin-x64')
* @param {string} targetDir - Directory to install ripgrep to
* @returns {Promise<string>} - Path to the installed ripgrep binary
*/
async function downloadRipgrep(target, targetDir) {
// Get the ripgrep release file name for the target
const releaseFile = TARGET_TO_RIPGREP_RELEASE[target];
if (!releaseFile) {
throw new Error(`Unsupported target: ${target}`);
}
const platform = target.split("-")[0];
const downloadUrl = `${RIPGREP_BASE_URL}/${releaseFile}`;
const tempDir = path.join(targetDir, "temp");
// Create temp directory
fs.mkdirSync(tempDir, { recursive: true });
const archivePath = path.join(tempDir, releaseFile);
try {
// Download the ripgrep release
console.log(`[info] Downloading ripgrep from ${downloadUrl}`);
await downloadFile(downloadUrl, archivePath);
// Extract the archive
console.log(`[info] Extracting ripgrep to ${targetDir}`);
await extractArchive(archivePath, targetDir, platform);
// Make the binary executable on Unix-like systems
if (platform !== "win32") {
const rgPath = path.join(targetDir, "rg");
fs.chmodSync(rgPath, 0o755);
}
// Clean up
rimrafSync(tempDir);
// Return the path to the ripgrep binary
const binName = platform === "win32" ? "rg.exe" : "rg";
return path.join(targetDir, binName);
} catch (error) {
console.error(`[error] Failed to download ripgrep for ${target}:`, error);
// Clean up temp directory on error
rimrafSync(tempDir);
throw error;
}
}
module.exports = {
downloadRipgrep,
RIPGREP_VERSION,
};

42
binary/utils/targets.js Normal file
View file

@ -0,0 +1,42 @@
const RIPGREP_VERSION = "14.1.1";
/**
* All supported platform-architecture targets
*/
const ALL_TARGETS = [
"darwin-x64",
"darwin-arm64",
"linux-x64",
"linux-arm64",
"win32-x64",
];
/**
* Mapping from target triplets to ripgrep release file names
*/
const TARGET_TO_RIPGREP_RELEASE = {
"darwin-x64": `ripgrep-${RIPGREP_VERSION}-x86_64-apple-darwin.tar.gz`,
"darwin-arm64": `ripgrep-${RIPGREP_VERSION}-aarch64-apple-darwin.tar.gz`,
"linux-x64": `ripgrep-${RIPGREP_VERSION}-x86_64-unknown-linux-musl.tar.gz`,
"linux-arm64": `ripgrep-${RIPGREP_VERSION}-aarch64-unknown-linux-gnu.tar.gz`,
"win32-x64": `ripgrep-${RIPGREP_VERSION}-x86_64-pc-windows-msvc.zip`,
};
/**
* Mapping from target triplets to LanceDB package names
*/
const TARGET_TO_LANCEDB = {
"darwin-arm64": "@lancedb/vectordb-darwin-arm64",
"darwin-x64": "@lancedb/vectordb-darwin-x64",
"linux-arm64": "@lancedb/vectordb-linux-arm64-gnu",
"linux-x64": "@lancedb/vectordb-linux-x64-gnu",
"win32-x64": "@lancedb/vectordb-win32-x64-msvc",
"win32-arm64": "@lancedb/vectordb-win32-arm64-msvc",
};
module.exports = {
ALL_TARGETS,
TARGET_TO_RIPGREP_RELEASE,
TARGET_TO_LANCEDB,
RIPGREP_VERSION,
};

View file

@ -244,7 +244,7 @@ export class CompletionProvider {
prefix,
suffix,
prompt,
modelProvider: llm.providerName,
modelProvider: llm.underlyingProviderName,
modelName: llm.model,
completionOptions,
cacheHit,

View file

@ -72,7 +72,8 @@ export class StreamTransformPipeline {
fullStop,
);
const timeoutValue = helper.options.showWhateverWeHaveAtXMs;
const timeoutValue = helper.options.modelTimeout;
lineGenerator = showWhateverWeHaveAtXMs(lineGenerator, timeoutValue!);

View file

@ -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", () => {

View file

@ -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;
}
}
}
}

View file

@ -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) {

View 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();
});
});

View 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;
}
}
}
}

View file

@ -1,4 +1,4 @@
import { IDE } from "../../index";
import { IDE, IdeInfo } from "../../index";
import { findUriInDirs } from "../../util/uri";
import { ContextRetrievalService } from "../context/ContextRetrievalService";
import { GetLspDefinitionsFunction } from "../types";
@ -112,13 +112,22 @@ const getClipboardSnippets = async (
const getDiffSnippets = async (
ide: IDE,
ideInfo: IdeInfo | undefined,
): Promise<AutocompleteDiffSnippet[]> => {
const currentTimestamp = ide.getLastFileSaveTimestamp ?
ide.getLastFileSaveTimestamp() :
Math.floor(Date.now() / 10000) * 10000; // Defaults to update once in every 10 seconds
if (ideInfo?.ideType !== "vscode") {
// Disabling for non-vscode IDEs for now
// See https://github.com/continuedev/continue/issues/4130
// https://github.com/continuedev/continue/issues/5819
return [];
}
const currentTimestamp = ide.getLastFileSaveTimestamp
? ide.getLastFileSaveTimestamp()
: Math.floor(Date.now() / 10000) * 10000; // Defaults to update once in every 10 seconds
// Check cache first
const cached = diffSnippetsCache.get(currentTimestamp) as AutocompleteDiffSnippet[];
const cached = diffSnippetsCache.get(
currentTimestamp,
) as AutocompleteDiffSnippet[];
if (cached) {
return cached;
@ -131,13 +140,15 @@ const getDiffSnippets = async (
console.error("Error getting diff for autocomplete", e);
}
return diffSnippetsCache.set(currentTimestamp, diff.map((item) => {
return {
content: item,
type: AutocompleteSnippetType.Diff,
};
}));
return diffSnippetsCache.set(
currentTimestamp,
diff.map((item) => {
return {
content: item,
type: AutocompleteSnippetType.Diff,
};
}),
);
};
export const getAllSnippets = async ({
@ -162,9 +173,13 @@ export const getAllSnippets = async ({
clipboardSnippets,
] = await Promise.all([
racePromise(contextRetrievalService.getRootPathSnippets(helper)),
racePromise(contextRetrievalService.getSnippetsFromImportDefinitions(helper)),
IDE_SNIPPETS_ENABLED ? racePromise(getIdeSnippets(helper, ide, getDefinitionsFromLsp)) : [],
racePromise(getDiffSnippets(ide)),
racePromise(
contextRetrievalService.getSnippetsFromImportDefinitions(helper),
),
IDE_SNIPPETS_ENABLED
? racePromise(getIdeSnippets(helper, ide, getDefinitionsFromLsp))
: [],
racePromise(getDiffSnippets(ide, helper.ideInfo)),
racePromise(getClipboardSnippets(ide)),
]);

View file

@ -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") ||

View file

@ -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);
});
}
}

View file

@ -1,4 +1,4 @@
import { IDE, TabAutocompleteOptions } from "../..";
import { IDE, IdeInfo, TabAutocompleteOptions } from "../..";
import {
countTokens,
pruneLinesFromBottom,
@ -21,6 +21,7 @@ export class HelperVars {
lang: AutocompleteLanguageInfo;
treePath: AstPath | undefined;
workspaceUris: string[] = [];
ideInfo: IdeInfo | undefined;
private _fileContents: string | undefined;
private _fileLines: string[] | undefined;
@ -43,7 +44,7 @@ export class HelperVars {
if (this._fileContents !== undefined) {
return;
}
this.ideInfo = await this.ide.getIdeInfo();
this.workspaceUris = await this.ide.getWorkspaceDirs();
this._fileContents =

View file

@ -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",

View file

@ -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,

View file

@ -51,7 +51,6 @@ import { LLMReranker } from "../llm/llms/llm";
import TransformersJsEmbeddingsProvider from "../llm/llms/TransformersJsEmbeddingsProvider";
import { slashCommandFromPromptFileV1 } from "../promptFiles/v1/slashCommandFromPromptFile";
import { getAllPromptFiles } from "../promptFiles/v2/getPromptFiles";
import { allTools } from "../tools";
import { copyOf } from "../util";
import { GlobalContext } from "../util/GlobalContext";
import mergeJson from "../util/merge";
@ -67,6 +66,7 @@ import {
} from "../util/paths";
import { localPathToUri } from "../util/pathToUri";
import { baseToolDefinitions } from "../tools";
import { modifyAnyConfigWithSharedConfig } from "./sharedConfig";
import {
getModelByRole,
@ -101,7 +101,14 @@ export function resolveSerializedConfig(
const configMergeKeys = {
models: (a: any, b: any) => a.title === b.title,
contextProviders: (a: any, b: any) => a.name === b.name,
contextProviders: (a: any, b: any) => {
// If not HTTP providers, use the name only
if (a.name !== "http" || b.name !== "http") {
return a.name === b.name;
}
// For HTTP providers, consider them different if they have different URLs
return a.name === b.name && a.params?.url === b.params?.url;
},
slashCommands: (a: any, b: any) => a.name === b.name,
customCommands: (a: any, b: any) => a.name === b.name,
};
@ -522,7 +529,7 @@ async function intermediateToFinalConfig({
const continueConfig: ContinueConfig = {
...config,
contextProviders,
tools: [...allTools],
tools: [...baseToolDefinitions],
mcpServerStatuses: [],
slashCommands: config.slashCommands ?? [],
modelsByRole: {
@ -620,6 +627,7 @@ async function intermediateToFinalConfig({
function llmToSerializedModelDescription(llm: ILLM): ModelDescription {
return {
provider: llm.providerName,
underlyingProviderName: llm.underlyingProviderName,
model: llm.model,
title: llm.title ?? llm.model,
apiKey: llm.apiKey,
@ -970,6 +978,5 @@ export {
finalToBrowserConfig,
intermediateToFinalConfig,
loadContinueConfigFromJson,
type BrowserSerializedContinueConfig
type BrowserSerializedContinueConfig,
};

View file

@ -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(

View 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 };
}

View file

@ -0,0 +1,192 @@
import {
convertMarkdownRuleToContinueRule,
parseMarkdownRule,
} from "./parseMarkdownRule";
describe("parseMarkdownRule", () => {
it("should correctly parse markdown with YAML frontmatter", () => {
const content = `---
globs: "**/test/**/*.kt"
---
# Test Rule
This is a test rule.`;
const result = parseMarkdownRule(content);
expect(result.frontmatter).toEqual({ globs: "**/test/**/*.kt" });
expect(result.markdown).toBe("# Test Rule\n\nThis is a test rule.");
});
it("should handle missing frontmatter", () => {
const content = `# Test Rule
This is a test rule without frontmatter.`;
const result = parseMarkdownRule(content);
expect(result.frontmatter).toEqual({});
expect(result.markdown).toBe(content);
});
it("should handle empty frontmatter", () => {
const content = `---
---
# Test Rule
This is a test rule with empty frontmatter.`;
const result = parseMarkdownRule(content);
// Log exact strings for debugging
console.log("Actual:", JSON.stringify(result.markdown));
console.log(
"Expected:",
JSON.stringify(
"# Test Rule\n\nThis is a test rule with empty frontmatter.",
),
);
expect(result.frontmatter).toEqual({});
expect(result.markdown).toBe(
"# Test Rule\n\nThis is a test rule with empty frontmatter.",
);
});
it("should handle frontmatter with whitespace", () => {
const content = `---
globs: "**/test/**/*.kt"
---
# Test Rule
This is a test rule.`;
const result = parseMarkdownRule(content);
expect(result.frontmatter).toEqual({ globs: "**/test/**/*.kt" });
expect(result.markdown).toBe("# Test Rule\n\nThis is a test rule.");
});
it("should handle Windows line endings (CRLF)", () => {
// Using \r\n for CRLF line endings
const content = `---\r
globs: "**/test/**/*.kt"\r
---\r
\r
# Test Rule\r
\r
This is a test rule.`;
const result = parseMarkdownRule(content);
expect(result.frontmatter).toEqual({ globs: "**/test/**/*.kt" });
// The result should be normalized to \n
expect(result.markdown).toBe("# Test Rule\n\nThis is a test rule.");
});
it("should handle malformed frontmatter", () => {
const content = `---
globs: - "**/test/**/*.kt"
invalid: yaml: content
---
# Test Rule
This is a test rule.`;
// Should treat as only markdown when frontmatter is malformed
const result = parseMarkdownRule(content);
expect(result.frontmatter).toEqual({});
expect(result.markdown).toBe(content);
});
});
describe("convertMarkdownRuleToContinueRule", () => {
it("should convert markdown with frontmatter to a rule", () => {
const content = `---
globs: "**/test/**/*.kt"
name: Custom Name
---
# Test Rule
This is a test rule.`;
const result = convertMarkdownRuleToContinueRule(
"/path/to/rule.md",
content,
);
expect(result.rule).toBe("# Test Rule\n\nThis is a test rule.");
expect(result.globs).toBe("**/test/**/*.kt");
expect(result.name).toBe("Custom Name");
expect(result.source).toBe("rules-block");
expect(result.ruleFile).toBe("/path/to/rule.md");
});
it("should use the first heading as name if not in frontmatter", () => {
const content = `---
globs: "**/test/**/*.kt"
---
# Test Rule Title
This is a test rule.`;
const result = convertMarkdownRuleToContinueRule(
"/path/to/rule.md",
content,
);
expect(result.name).toBe("Test Rule Title");
});
it("should use filename as name if no heading or frontmatter name", () => {
const content = `---
globs: "**/test/**/*.kt"
---
This is a test rule without a heading.`;
const result = convertMarkdownRuleToContinueRule(
"/path/to/custom-rule.md",
content,
);
expect(result.name).toBe("custom-rule");
});
it("should include description from frontmatter", () => {
const content = `---
globs: "**/test/**/*.kt"
name: Test Rule
description: This is a rule description from frontmatter
---
# Test Rule
This is the content of the rule.`;
const result = convertMarkdownRuleToContinueRule(
"/path/to/rule.md",
content,
);
expect(result.description).toBe(
"This is a rule description from frontmatter",
);
});
it("should include `alwaysApply` from frontmatter", () => {
const content = `---
globs: "**/test/**/*.kt"
name: Test Rule
alwaysApply: false
---
# Test Rule
This is a rule with alwaysApply explicitly set to false.`;
const result = convertMarkdownRuleToContinueRule(
"/path/to/rule.md",
content,
);
expect(result.alwaysApply).toBe(false);
});
});

View file

@ -0,0 +1,77 @@
import { basename } from "path";
import * as YAML from "yaml";
import { RuleWithSource } from "../..";
export interface RuleFrontmatter {
globs?: RuleWithSource["globs"];
name?: RuleWithSource["name"];
description?: RuleWithSource["description"];
alwaysApply?: RuleWithSource["alwaysApply"];
}
/**
* Parses markdown content with YAML frontmatter
*/
export function parseMarkdownRule(content: string): {
frontmatter: RuleFrontmatter;
markdown: string;
} {
// Normalize line endings to \n
const normalizedContent = content.replace(/\r\n/g, "\n");
// More reliable frontmatter detection
const parts = normalizedContent.split(/^---\s*$/m);
// If we have at least 3 parts (before ---, frontmatter, after ---), we have frontmatter
if (parts.length >= 3) {
const frontmatterStr = parts[1];
// Join the remaining parts back together (in case there are more --- in the markdown)
const markdownContent = parts.slice(2).join("---");
try {
// Parse YAML frontmatter
const frontmatter = YAML.parse(frontmatterStr) || {}; // Handle empty frontmatter
return { frontmatter, markdown: markdownContent.trim() };
} catch (e) {
// Error parsing frontmatter, treat as markdown only
console.warn("Error parsing markdown frontmatter:", e);
return { frontmatter: {}, markdown: normalizedContent };
}
}
// No frontmatter found
return { frontmatter: {}, markdown: normalizedContent };
}
/**
* Converts a markdown file with YAML frontmatter to a RuleWithSource object
*/
export function convertMarkdownRuleToContinueRule(
path: string,
content: string,
): RuleWithSource {
const { frontmatter, markdown } = parseMarkdownRule(content);
// Try to extract title from first heading if no name in frontmatter
let name = frontmatter.name;
if (!name) {
// Look for a heading in the markdown
const headingMatch = markdown.match(/^#\s+(.+)$/m);
if (headingMatch) {
name = headingMatch[1].trim();
} else {
// Fall back to filename
name = basename(path).replace(/\.md$/, "");
}
}
return {
name,
rule: markdown,
globs: frontmatter.globs,
description: frontmatter.description,
alwaysApply: frontmatter.alwaysApply,
source: "rules-block",
ruleFile: path,
};
}

View file

@ -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;

View file

@ -25,6 +25,7 @@ import { ControlPlaneClient } from "../../control-plane/client.js";
import { getControlPlaneEnv } from "../../control-plane/env.js";
import { TeamAnalytics } from "../../control-plane/TeamAnalytics.js";
import ContinueProxy from "../../llm/llms/stubs/ContinueProxy";
import { getConfigDependentToolDefinitions } from "../../tools";
import { encodeMCPToolUri } from "../../tools/callTool";
import { getConfigJsonPath, getConfigYamlPath } from "../../util/paths";
import { localPathOrUriToPath } from "../../util/pathToUri";
@ -32,6 +33,7 @@ import { Telemetry } from "../../util/posthog";
import { TTS } from "../../util/tts";
import { getWorkspaceContinueRuleDotFiles } from "../getWorkspaceContinueRuleDotFiles";
import { loadContinueConfigFromJson } from "../load";
import { loadMarkdownRules } from "../markdown/loadMarkdownRules";
import { migrateJsonSharedConfig } from "../migrateSharedConfig";
import { rectifySelectedModelsFromGlobalContext } from "../selectedModels";
import { loadContinueConfigFromYaml } from "../yaml/loadYaml";
@ -128,6 +130,12 @@ export default async function doLoadConfig(options: {
newConfig.rules.unshift(...rules);
errors.push(...continueRulesErrors);
// Add rules from markdown files in .continue/rules
const { rules: markdownRules, errors: markdownRulesErrors } =
await loadMarkdownRules(ide);
newConfig.rules.unshift(...markdownRules);
errors.push(...markdownRulesErrors);
// Rectify model selections for each role
newConfig = rectifySelectedModelsFromGlobalContext(newConfig, profileId);
@ -169,12 +177,21 @@ export default async function doLoadConfig(options: {
);
newConfig.slashCommands.push(...serverSlashCommands);
const submenuItems = server.resources.map((resource) => ({
title: resource.name,
description: resource.description ?? resource.name,
id: resource.uri,
icon: server.faviconUrl,
}));
const submenuItems = server.resources
.map((resource) => ({
title: resource.name,
description: resource.description ?? resource.name,
id: resource.uri,
icon: server.faviconUrl,
}))
.concat(
server.resourceTemplates.map((template) => ({
title: template.name,
description: template.description ?? template.name,
id: template.uriTemplate,
icon: server.faviconUrl,
})),
);
if (submenuItems.length > 0) {
const serverContextProvider = new MCPContextProvider({
submenuItems,
@ -186,6 +203,12 @@ export default async function doLoadConfig(options: {
}
}
newConfig.tools.push(
...getConfigDependentToolDefinitions({
rules: newConfig.rules,
}),
);
// Detect duplicate tool names
const counts: Record<string, number> = {};
newConfig.tools.forEach((tool) => {
@ -195,6 +218,7 @@ export default async function doLoadConfig(options: {
counts[tool.function.name] = 1;
}
});
Object.entries(counts).forEach(([toolName, count]) => {
if (count > 1) {
errors!.push({
@ -204,6 +228,26 @@ export default async function doLoadConfig(options: {
}
});
const ruleCounts: Record<string, number> = {};
newConfig.rules.forEach((rule) => {
if (rule.name) {
if (ruleCounts[rule.name]) {
ruleCounts[rule.name] = ruleCounts[rule.name] + 1;
} else {
ruleCounts[rule.name] = 1;
}
}
});
Object.entries(ruleCounts).forEach(([ruleName, count]) => {
if (count > 1) {
errors!.push({
fatal: false,
message: `Duplicate (${count}) rules named "${ruleName}" detected. This may cause unexpected behavior`,
});
}
});
newConfig.allowAnonymousTelemetry =
newConfig.allowAnonymousTelemetry && (await ide.isTelemetryEnabled());

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